code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
---|---|---|---|---|---|
/*
*
* /arch/arm/mach-msm/htc_headset_mgr.c
*
* HTC headset manager driver.
*
* Copyright (C) 2010 HTC, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/gpio_event.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#include <mach/htc_headset_mgr.h>
#define DRIVER_NAME "HS_MGR"
static struct workqueue_struct *detect_wq;
static void insert_detect_work_func(struct work_struct *work);
static DECLARE_DELAYED_WORK(insert_detect_work, insert_detect_work_func);
static void remove_detect_work_func(struct work_struct *work);
static DECLARE_DELAYED_WORK(remove_detect_work, remove_detect_work_func);
static void mic_detect_work_func(struct work_struct *work);
static DECLARE_DELAYED_WORK(mic_detect_work, mic_detect_work_func);
static struct workqueue_struct *button_wq;
static void button_35mm_work_func(struct work_struct *work);
static DECLARE_DELAYED_WORK(button_35mm_work, button_35mm_work_func);
static struct workqueue_struct *debug_wq;
static void debug_work_func(struct work_struct *work);
static DECLARE_WORK(debug_work, debug_work_func);
static int hs_mgr_rpc_call(struct msm_rpc_server *server,
struct rpc_request_hdr *req, unsigned len);
static struct msm_rpc_server hs_rpc_server = {
.prog = HS_RPC_SERVER_PROG,
.vers = HS_RPC_SERVER_VERS,
.rpc_call = hs_mgr_rpc_call,
};
struct button_work {
struct delayed_work key_work;
int key_code;
};
static struct htc_headset_mgr_info *hi;
static struct hs_notifier_func hs_mgr_notifier;
static void init_next_driver(void)
{
int i = hi->driver_init_seq;
if (!hi->pdata.headset_devices_num)
return;
if (i < hi->pdata.headset_devices_num) {
hi->driver_init_seq++;
platform_device_register(hi->pdata.headset_devices[i]);
}
}
int hs_debug_log_state(void)
{
return (hi->debug_flag & DEBUG_FLAG_LOG) ? 1 : 0;
}
void hs_notify_driver_ready(char *name)
{
HS_LOG("%s ready", name);
init_next_driver();
}
void hs_notify_hpin_irq(void)
{
hi->hpin_jiffies = jiffies;
HS_LOG("HPIN IRQ");
}
struct class *hs_get_attribute_class(void)
{
return hi->htc_accessory_class;
}
int hs_hpin_stable(void)
{
unsigned long last_hpin_jiffies = 0;
unsigned long unstable_jiffies = 1.2 * HZ;
HS_DBG();
last_hpin_jiffies = hi->hpin_jiffies;
if (time_before_eq(jiffies, last_hpin_jiffies + unstable_jiffies))
return 0;
return 1;
}
static int get_mic_state(void)
{
HS_DBG();
switch (hi->hs_35mm_type) {
case HEADSET_MIC:
case HEADSET_METRICO:
case HEADSET_BEATS:
case HEADSET_BEATS_SOLO:
return 1;
default:
break;
}
return 0;
}
static void update_mic_status(int count)
{
HS_DBG();
if (hi->is_ext_insert) {
HS_LOG("Start MIC status polling (%d)", count);
cancel_delayed_work_sync(&mic_detect_work);
hi->mic_detect_counter = count;
queue_delayed_work(detect_wq, &mic_detect_work,
HS_JIFFIES_MIC_DETECT);
}
}
static void headset_notifier_update(int id)
{
if (!hi) {
HS_LOG("HS_MGR driver is not ready");
return;
}
switch (id) {
case HEADSET_REG_HPIN_GPIO:
break;
case HEADSET_REG_REMOTE_ADC:
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
break;
case HEADSET_REG_REMOTE_KEYCODE:
case HEADSET_REG_RPC_KEY:
break;
case HEADSET_REG_MIC_STATUS:
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
break;
case HEADSET_REG_MIC_BIAS:
if (!hi->pdata.headset_power &&
hi->hs_35mm_type != HEADSET_UNPLUG) {
hs_mgr_notifier.mic_bias_enable(1);
hi->mic_bias_state = 1;
msleep(HS_DELAY_MIC_BIAS);
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
}
break;
case HEADSET_REG_MIC_SELECT:
case HEADSET_REG_KEY_INT_ENABLE:
case HEADSET_REG_KEY_ENABLE:
case HEADSET_REG_INDICATOR_ENABLE:
break;
default:
break;
}
}
int headset_notifier_register(struct headset_notifier *notifier)
{
if (!notifier->func) {
HS_LOG("NULL register function");
return 0;
}
switch (notifier->id) {
case HEADSET_REG_HPIN_GPIO:
HS_LOG("Register HPIN_GPIO notifier");
hs_mgr_notifier.hpin_gpio = notifier->func;
break;
case HEADSET_REG_REMOTE_ADC:
HS_LOG("Register REMOTE_ADC notifier");
hs_mgr_notifier.remote_adc = notifier->func;
break;
case HEADSET_REG_REMOTE_KEYCODE:
HS_LOG("Register REMOTE_KEYCODE notifier");
hs_mgr_notifier.remote_keycode = notifier->func;
break;
case HEADSET_REG_RPC_KEY:
HS_LOG("Register RPC_KEY notifier");
hs_mgr_notifier.rpc_key = notifier->func;
break;
case HEADSET_REG_MIC_STATUS:
HS_LOG("Register MIC_STATUS notifier");
hs_mgr_notifier.mic_status = notifier->func;
break;
case HEADSET_REG_MIC_BIAS:
HS_LOG("Register MIC_BIAS notifier");
hs_mgr_notifier.mic_bias_enable = notifier->func;
break;
case HEADSET_REG_MIC_SELECT:
HS_LOG("Register MIC_SELECT notifier");
hs_mgr_notifier.mic_select = notifier->func;
break;
case HEADSET_REG_KEY_INT_ENABLE:
HS_LOG("Register KEY_INT_ENABLE notifier");
hs_mgr_notifier.key_int_enable = notifier->func;
break;
case HEADSET_REG_KEY_ENABLE:
HS_LOG("Register KEY_ENABLE notifier");
hs_mgr_notifier.key_enable = notifier->func;
break;
case HEADSET_REG_INDICATOR_ENABLE:
HS_LOG("Register INDICATOR_ENABLE notifier");
hs_mgr_notifier.indicator_enable = notifier->func;
break;
default:
HS_LOG("Unknown register ID");
return 0;
}
headset_notifier_update(notifier->id);
return 1;
}
static int hs_mgr_rpc_call(struct msm_rpc_server *server,
struct rpc_request_hdr *req, unsigned len)
{
struct hs_rpc_server_args_key *args_key;
wake_lock_timeout(&hi->hs_wake_lock, HS_WAKE_LOCK_TIMEOUT);
HS_DBG();
switch (req->procedure) {
case HS_RPC_SERVER_PROC_NULL:
HS_LOG("RPC_SERVER_NULL");
break;
case HS_RPC_SERVER_PROC_KEY:
args_key = (struct hs_rpc_server_args_key *)(req + 1);
args_key->adc = be32_to_cpu(args_key->adc);
HS_LOG("RPC_SERVER_KEY ADC = %u (0x%X)",
args_key->adc, args_key->adc);
if (hs_mgr_notifier.rpc_key)
hs_mgr_notifier.rpc_key(args_key->adc);
else
HS_LOG("RPC_KEY notify function doesn't exist");
break;
default:
HS_LOG("Unknown RPC procedure");
return -EINVAL;
}
return 0;
}
static ssize_t h2w_print_name(struct switch_dev *sdev, char *buf)
{
return sprintf(buf, "Headset\n");
}
static ssize_t usb_audio_print_name(struct switch_dev *sdev, char *buf)
{
return sprintf(buf, "usb_audio\n");
}
static void get_key_name(int keycode, char *buf)
{
switch (keycode) {
case HS_MGR_KEYCODE_END:
sprintf(buf, "END");
break;
case HS_MGR_KEYCODE_MUTE:
sprintf(buf, "MUTE");
break;
case HS_MGR_KEYCODE_VOLDOWN:
sprintf(buf, "VOLDOWN");
break;
case HS_MGR_KEYCODE_VOLUP:
sprintf(buf, "VOLUP");
break;
case HS_MGR_KEYCODE_FORWARD:
sprintf(buf, "FORWARD");
break;
case HS_MGR_KEYCODE_PLAY:
sprintf(buf, "PLAY");
break;
case HS_MGR_KEYCODE_BACKWARD:
sprintf(buf, "BACKWARD");
break;
case HS_MGR_KEYCODE_MEDIA:
sprintf(buf, "MEDIA");
break;
case HS_MGR_KEYCODE_SEND:
sprintf(buf, "SEND");
break;
default:
sprintf(buf, "%d", keycode);
}
}
void button_pressed(int type)
{
char key_name[16];
get_key_name(type, key_name);
HS_LOG_TIME("%s (%d) pressed", key_name, type);
atomic_set(&hi->btn_state, type);
input_report_key(hi->input, type, 1);
input_sync(hi->input);
}
void button_released(int type)
{
char key_name[16];
get_key_name(type, key_name);
HS_LOG_TIME("%s (%d) released", key_name, type);
atomic_set(&hi->btn_state, 0);
input_report_key(hi->input, type, 0);
input_sync(hi->input);
}
void headset_button_event(int is_press, int type)
{
HS_DBG();
if (hi->hs_35mm_type == HEADSET_UNPLUG &&
hi->h2w_35mm_type == HEADSET_UNPLUG) {
HS_LOG("IGNORE key %d (HEADSET_UNPLUG)", type);
return;
}
if (!hs_hpin_stable()) {
HS_LOG("IGNORE key %d (Unstable HPIN)", type);
return;
}
if (!get_mic_state()) {
HS_LOG("IGNORE key %d (Not support MIC)", type);
return;
}
if (!is_press)
button_released(type);
else if (!atomic_read(&hi->btn_state))
button_pressed(type);
}
void hs_set_mic_select(int state)
{
HS_DBG();
if (hs_mgr_notifier.mic_select)
hs_mgr_notifier.mic_select(state);
}
static int get_mic_status(void)
{
int i = 0;
int adc = 0;
int mic = HEADSET_UNKNOWN_MIC;
if (hi->pdata.headset_config_num && hs_mgr_notifier.remote_adc) {
hs_mgr_notifier.remote_adc(&adc);
for (i = 0; i < hi->pdata.headset_config_num; i++) {
if (adc >= hi->pdata.headset_config[i].adc_min &&
adc <= hi->pdata.headset_config[i].adc_max)
return hi->pdata.headset_config[i].type;
}
if (hi->pdata.driver_flag & DRIVER_HS_MGR_FLOAT_DET) {
return HEADSET_UNPLUG;
}
} else if (hs_mgr_notifier.mic_status) {
mic = hs_mgr_notifier.mic_status();
}
else
HS_LOG("Failed to get MIC status");
return mic;
}
int headset_get_type(void)
{
return hi->hs_35mm_type;
}
int headset_get_type_sync(int count, unsigned int interval)
{
int current_type = hi->hs_35mm_type;
int new_type = HEADSET_UNKNOWN_MIC;
while (count--) {
new_type = get_mic_status();
if (new_type != current_type)
break;
if (count)
msleep(interval);
}
if (new_type != current_type) {
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
return HEADSET_UNKNOWN_MIC;
}
return hi->hs_35mm_type;
}
static void set_35mm_hw_state(int state)
{
HS_DBG();
if (hi->pdata.headset_power || hs_mgr_notifier.mic_bias_enable) {
if (hi->mic_bias_state != state) {
if (hi->pdata.headset_power)
hi->pdata.headset_power(state);
else if (hs_mgr_notifier.mic_bias_enable)
hs_mgr_notifier.mic_bias_enable(state);
hi->mic_bias_state = state;
if (state) /* Wait for MIC bias stable */
msleep(HS_DELAY_MIC_BIAS);
}
}
hs_set_mic_select(state);
if (hs_mgr_notifier.key_enable)
hs_mgr_notifier.key_enable(state);
if (hs_mgr_notifier.key_int_enable)
hs_mgr_notifier.key_int_enable(state);
}
static int tv_out_detect(void)
{
int adc = 0;
int mic = HEADSET_NO_MIC;
HS_DBG();
if (!hs_mgr_notifier.remote_adc)
return HEADSET_NO_MIC;
if (!hi->pdata.hptv_det_hp_gpio || !hi->pdata.hptv_det_tv_gpio)
return HEADSET_NO_MIC;
gpio_set_value(hi->pdata.hptv_det_hp_gpio, 0);
gpio_set_value(hi->pdata.hptv_det_tv_gpio, 1);
msleep(HS_DELAY_MIC_BIAS);
hs_mgr_notifier.remote_adc(&adc);
if (adc >= HS_DEF_HPTV_ADC_16_BIT_MIN &&
adc <= HS_DEF_HPTV_ADC_16_BIT_MAX)
mic = HEADSET_TV_OUT;
gpio_set_value(hi->pdata.hptv_det_hp_gpio, 1);
gpio_set_value(hi->pdata.hptv_det_tv_gpio, 0);
return mic;
}
#if 0
static void insert_h2w_35mm(int *state)
{
int mic = HEADSET_NO_MIC;
HS_LOG_TIME("Insert H2W 3.5mm headset");
set_35mm_hw_state(1);
mic = get_mic_status();
if (mic == HEADSET_NO_MIC) {
*state |= BIT_HEADSET_NO_MIC;
hi->h2w_35mm_type = HEADSET_NO_MIC;
HS_LOG_TIME("H2W 3.5mm without microphone");
} else {
*state |= BIT_HEADSET;
hi->h2w_35mm_type = HEADSET_MIC;
HS_LOG_TIME("H2W 3.5mm with microphone");
}
}
static void remove_h2w_35mm(void)
{
HS_LOG_TIME("Remove H2W 3.5mm headset");
set_35mm_hw_state(0);
if (atomic_read(&hi->btn_state))
button_released(atomic_read(&hi->btn_state));
hi->h2w_35mm_type = HEADSET_UNPLUG;
}
#endif /* #if 0 */
static void enable_metrico_headset(int enable)
{
HS_DBG();
if (enable && !hi->metrico_status) {
#if 0
enable_mos_test(1);
#endif
hi->metrico_status = 1;
HS_LOG("Enable metrico headset");
}
if (!enable && hi->metrico_status) {
#if 0
enable_mos_test(0);
#endif
hi->metrico_status = 0;
HS_LOG("Disable metrico headset");
}
}
static void mic_detect_work_func(struct work_struct *work)
{
int mic = HEADSET_NO_MIC;
int old_state, new_state;
wake_lock_timeout(&hi->hs_wake_lock, HS_MIC_DETECT_TIMEOUT);
HS_DBG();
if (!hi->pdata.headset_config_num && !hs_mgr_notifier.mic_status) {
HS_LOG("Failed to get MIC status");
return;
}
mutex_lock(&hi->mutex_lock);
mic = get_mic_status();
if (mic == HEADSET_NO_MIC)
mic = tv_out_detect();
if (mic == HEADSET_TV_OUT && hi->pdata.hptv_sel_gpio)
gpio_set_value(hi->pdata.hptv_sel_gpio, 1);
if (mic == HEADSET_METRICO && !hi->metrico_status)
enable_metrico_headset(1);
if (mic == HEADSET_UNKNOWN_MIC) {
mutex_unlock(&hi->mutex_lock);
if (hi->mic_detect_counter--)
queue_delayed_work(detect_wq, &mic_detect_work,
HS_JIFFIES_MIC_DETECT);
else
HS_LOG("MIC polling timeout (UNKNOWN MIC status)");
return;
}
if (hi->hs_35mm_type == HEADSET_UNSTABLE && hi->mic_detect_counter--) {
mutex_unlock(&hi->mutex_lock);
queue_delayed_work(detect_wq, &mic_detect_work,
HS_JIFFIES_MIC_DETECT);
return;
}
old_state = switch_get_state(&hi->sdev_h2w);
if (!(old_state & MASK_35MM_HEADSET)) {
HS_LOG("Headset has been removed");
mutex_unlock(&hi->mutex_lock);
return;
}
new_state = old_state & ~MASK_35MM_HEADSET;
new_state |= BIT_35MM_HEADSET;
switch (mic) {
case HEADSET_NO_MIC:
new_state |= BIT_HEADSET_NO_MIC;
HS_LOG("HEADSET_NO_MIC");
break;
case HEADSET_MIC:
new_state |= BIT_HEADSET;
HS_LOG("HEADSET_MIC");
break;
case HEADSET_METRICO:
new_state |= BIT_HEADSET;
HS_LOG("HEADSET_METRICO");
break;
case HEADSET_TV_OUT:
new_state |= BIT_TV_OUT;
HS_LOG("HEADSET_TV_OUT");
#if defined(CONFIG_FB_MSM_TVOUT) && defined(CONFIG_ARCH_MSM8X60)
tvout_enable_detection(1);
#endif
break;
case HEADSET_BEATS:
new_state |= BIT_HEADSET;
HS_LOG("HEADSET_BEATS");
break;
case HEADSET_BEATS_SOLO:
new_state |= BIT_HEADSET;
HS_LOG("HEADSET_BEATS_SOLO");
break;
case HEADSET_INDICATOR:
HS_LOG("HEADSET_INDICATOR");
break;
}
if (new_state != old_state) {
HS_LOG_TIME("Unplug accessory");
switch_set_state(&hi->sdev_h2w, old_state & ~MASK_35MM_HEADSET);
hi->hs_35mm_type = mic;
HS_LOG_TIME("Plug accessory and update MIC status");
switch_set_state(&hi->sdev_h2w, new_state);
} else
HS_LOG("MIC status has not changed");
mutex_unlock(&hi->mutex_lock);
}
static void button_35mm_work_func(struct work_struct *work)
{
int key;
struct button_work *works;
wake_lock_timeout(&hi->hs_wake_lock, HS_WAKE_LOCK_TIMEOUT);
HS_DBG();
works = container_of(work, struct button_work, key_work.work);
hi->key_level_flag = works->key_code;
if (hi->key_level_flag) {
switch (hi->key_level_flag) {
case 1:
key = HS_MGR_KEYCODE_MEDIA;
break;
case 2:
key = HS_MGR_KEYCODE_BACKWARD;
break;
case 3:
key = HS_MGR_KEYCODE_FORWARD;
break;
default:
HS_LOG("3.5mm RC: WRONG Button Pressed");
kfree(works);
return;
}
headset_button_event(1, key);
} else { /* key release */
if (atomic_read(&hi->btn_state))
headset_button_event(0, atomic_read(&hi->btn_state));
else
HS_LOG("3.5mm RC: WRONG Button Release");
}
kfree(works);
}
static void debug_work_func(struct work_struct *work)
{
int flag = 0;
int adc = -EINVAL;
int hpin_gpio = -EINVAL;
HS_DBG();
while (hi->debug_flag & DEBUG_FLAG_ADC) {
flag = hi->debug_flag;
if (hs_mgr_notifier.hpin_gpio)
hpin_gpio = hs_mgr_notifier.hpin_gpio();
if (hs_mgr_notifier.remote_adc)
hs_mgr_notifier.remote_adc(&adc);
HS_LOG("Debug Flag %d, HP_DET %d, ADC %d", flag,
hpin_gpio, adc);
msleep(HS_DELAY_SEC);
}
}
static void remove_detect_work_func(struct work_struct *work)
{
int state;
wake_lock_timeout(&hi->hs_wake_lock, HS_WAKE_LOCK_TIMEOUT);
HS_DBG();
if (time_before_eq(jiffies, hi->insert_jiffies + HZ)) {
HS_LOG("Waiting for HPIN stable");
msleep(HS_DELAY_SEC - HS_DELAY_REMOVE);
}
if (hi->is_ext_insert) {
HS_LOG("Headset has been inserted");
return;
}
if (hi->hs_35mm_type == HEADSET_INDICATOR &&
hs_mgr_notifier.indicator_enable)
hs_mgr_notifier.indicator_enable(0);
set_35mm_hw_state(0);
#if defined(CONFIG_FB_MSM_TVOUT) && defined(CONFIG_ARCH_MSM8X60)
if (hi->hs_35mm_type == HEADSET_TV_OUT && hi->pdata.hptv_sel_gpio) {
HS_LOG_TIME("Remove 3.5mm TVOUT cable");
tvout_enable_detection(0);
gpio_set_value(hi->pdata.hptv_sel_gpio, 0);
}
#endif
if (hi->metrico_status)
enable_metrico_headset(0);
if (atomic_read(&hi->btn_state))
button_released(atomic_read(&hi->btn_state));
hi->hs_35mm_type = HEADSET_UNPLUG;
mutex_lock(&hi->mutex_lock);
state = switch_get_state(&hi->sdev_h2w);
if (!(state & MASK_35MM_HEADSET)) {
HS_LOG("Headset has been removed");
mutex_unlock(&hi->mutex_lock);
return;
}
#if 0
if (hi->cable_in1 && !gpio_get_value(hi->cable_in1)) {
state &= ~BIT_35MM_HEADSET;
switch_set_state(&hi->sdev_h2w, state);
queue_delayed_work(detect_wq, &detect_h2w_work,
HS_DELAY_ZERO_JIFFIES);
} else {
state &= ~(MASK_35MM_HEADSET | MASK_FM_ATTRIBUTE);
switch_set_state(&hi->sdev_h2w, state);
}
#else
state &= ~(MASK_35MM_HEADSET | MASK_FM_ATTRIBUTE);
switch_set_state(&hi->sdev_h2w, state);
#endif
HS_LOG_TIME("Remove 3.5mm accessory");
mutex_unlock(&hi->mutex_lock);
#ifdef HTC_HEADSET_CONFIG_QUICK_BOOT
if (gpio_event_get_quickboot_status())
HS_LOG("quick_boot_status = 1");
#endif
}
static void insert_detect_work_func(struct work_struct *work)
{
int state;
int mic = HEADSET_NO_MIC;
wake_lock_timeout(&hi->hs_wake_lock, HS_WAKE_LOCK_TIMEOUT);
HS_DBG();
if (!hi->is_ext_insert) {
HS_LOG("Headset has been removed");
return;
}
hi->insert_jiffies = jiffies;
set_35mm_hw_state(1);
mutex_lock(&hi->mutex_lock);
mic = get_mic_status();
if (hi->pdata.driver_flag & DRIVER_HS_MGR_FLOAT_DET) {
HS_LOG("Headset float detect enable");
if (mic == HEADSET_UNPLUG) {
set_35mm_hw_state(0);
hi->hs_35mm_type = mic;
mutex_unlock(&hi->mutex_lock);
HS_LOG("Headset float detected");
return;
}
}
if (mic == HEADSET_NO_MIC)
mic = tv_out_detect();
if (mic == HEADSET_TV_OUT && hi->pdata.hptv_sel_gpio)
gpio_set_value(hi->pdata.hptv_sel_gpio, 1);
if (mic == HEADSET_METRICO && !hi->metrico_status)
enable_metrico_headset(1);
state = switch_get_state(&hi->sdev_h2w);
state &= ~MASK_35MM_HEADSET;
state |= BIT_35MM_HEADSET;
switch (mic) {
case HEADSET_NO_MIC:
state |= BIT_HEADSET_NO_MIC;
HS_LOG_TIME("HEADSET_NO_MIC");
break;
case HEADSET_MIC:
state |= BIT_HEADSET;
HS_LOG_TIME("HEADSET_MIC");
break;
case HEADSET_METRICO:
mic = HEADSET_UNSTABLE;
HS_LOG_TIME("HEADSET_METRICO (UNSTABLE)");
break;
case HEADSET_UNKNOWN_MIC:
state |= BIT_HEADSET_NO_MIC;
HS_LOG_TIME("HEADSET_UNKNOWN_MIC");
break;
case HEADSET_TV_OUT:
state |= BIT_TV_OUT;
HS_LOG_TIME("HEADSET_TV_OUT");
#if defined(CONFIG_FB_MSM_TVOUT) && defined(CONFIG_ARCH_MSM8X60)
tvout_enable_detection(1);
#endif
break;
case HEADSET_BEATS:
state |= BIT_HEADSET;
HS_LOG_TIME("HEADSET_BEATS (UNSTABLE)");
break;
case HEADSET_BEATS_SOLO:
state |= BIT_HEADSET;
HS_LOG_TIME("HEADSET_BEATS_SOLO (UNSTABLE)");
break;
case HEADSET_INDICATOR:
HS_LOG_TIME("HEADSET_INDICATOR");
break;
}
hi->hs_35mm_type = mic;
switch_set_state(&hi->sdev_h2w, state);
mutex_unlock(&hi->mutex_lock);
#ifdef HTC_HEADSET_CONFIG_QUICK_BOOT
if (gpio_event_get_quickboot_status())
HS_LOG("quick_boot_status = 1");
#endif
if (mic == HEADSET_UNKNOWN_MIC)
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
else if (mic == HEADSET_UNSTABLE)
update_mic_status(0);
else if (mic == HEADSET_INDICATOR) {
if (headset_get_type_sync(3, HS_DELAY_SEC) == HEADSET_INDICATOR)
HS_LOG("Delay check: HEADSET_INDICATOR");
else
HS_LOG("Delay check: HEADSET_UNKNOWN_MIC");
}
}
int hs_notify_plug_event(int insert)
{
HS_DBG("Headset status %d", insert);
mutex_lock(&hi->mutex_lock);
hi->is_ext_insert = insert;
mutex_unlock(&hi->mutex_lock);
cancel_delayed_work_sync(&mic_detect_work);
cancel_delayed_work_sync(&insert_detect_work);
cancel_delayed_work_sync(&remove_detect_work);
if (hi->is_ext_insert)
queue_delayed_work(detect_wq, &insert_detect_work,
HS_JIFFIES_INSERT);
else
queue_delayed_work(detect_wq, &remove_detect_work,
HS_JIFFIES_REMOVE);
return 1;
}
int hs_notify_key_event(int key_code)
{
struct button_work *work;
HS_DBG();
if (hi->hs_35mm_type == HEADSET_INDICATOR) {
HS_LOG("Not support remote control");
return 1;
}
if (hi->hs_35mm_type == HEADSET_UNKNOWN_MIC ||
hi->hs_35mm_type == HEADSET_NO_MIC ||
hi->h2w_35mm_type == HEADSET_NO_MIC)
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
else if (hi->hs_35mm_type == HEADSET_UNSTABLE)
update_mic_status(0);
else if (!hs_hpin_stable()) {
HS_LOG("IGNORE key %d (Unstable HPIN)", key_code);
return 1;
} else {
work = kzalloc(sizeof(struct button_work), GFP_KERNEL);
if (!work) {
HS_ERR("Failed to allocate button memory");
return 1;
}
work->key_code = key_code;
INIT_DELAYED_WORK(&work->key_work, button_35mm_work_func);
queue_delayed_work(button_wq, &work->key_work,
HS_JIFFIES_BUTTON);
}
return 1;
}
int hs_notify_key_irq(void)
{
int adc = 0;
int key_code = HS_MGR_KEY_INVALID;
if (hi->hs_35mm_type == HEADSET_INDICATOR) {
HS_LOG("Not support remote control");
return 1;
}
if (!hs_mgr_notifier.remote_adc || !hs_mgr_notifier.remote_keycode) {
HS_LOG("Failed to get remote key code");
return 1;
}
if (hs_hpin_stable()) {
hs_mgr_notifier.remote_adc(&adc);
key_code = hs_mgr_notifier.remote_keycode(adc);
hs_notify_key_event(key_code);
} else if (hi->hs_35mm_type == HEADSET_NO_MIC ||
hi->hs_35mm_type == HEADSET_UNKNOWN_MIC) {
HS_LOG("IGNORE key IRQ (Unstable HPIN)");
update_mic_status(HS_DEF_MIC_DETECT_COUNT);
}
return 1;
}
static void usb_headset_detect(int type)
{
int state_h2w = 0;
int state_usb = 0;
HS_DBG();
mutex_lock(&hi->mutex_lock);
state_h2w = switch_get_state(&hi->sdev_h2w);
switch (type) {
case USB_NO_HEADSET:
hi->usb_headset.type = USB_NO_HEADSET;
hi->usb_headset.status = STATUS_DISCONNECTED;
state_h2w &= ~MASK_USB_HEADSET;
state_usb = GOOGLE_USB_AUDIO_UNPLUG;
HS_LOG_TIME("Remove USB_HEADSET (state %d, %d)",
state_h2w, state_usb);
break;
case USB_AUDIO_OUT:
hi->usb_headset.type = USB_AUDIO_OUT;
hi->usb_headset.status = STATUS_CONNECTED_ENABLED;
state_h2w |= BIT_USB_AUDIO_OUT;
state_usb = GOOGLE_USB_AUDIO_ANLG;
HS_LOG_TIME("Insert USB_AUDIO_OUT (state %d, %d)",
state_h2w, state_usb);
break;
default:
HS_LOG("Unknown headset type");
}
switch_set_state(&hi->sdev_h2w, state_h2w);
switch_set_state(&hi->sdev_usb_audio, state_usb);
mutex_unlock(&hi->mutex_lock);
}
void headset_ext_detect(int type)
{
HS_DBG();
switch (type) {
case H2W_NO_HEADSET:
/* Release Key */
case H2W_HEADSET:
case H2W_35MM_HEADSET:
case H2W_REMOTE_CONTROL:
case H2W_USB_CRADLE:
case H2W_UART_DEBUG:
case H2W_TVOUT:
break;
case USB_NO_HEADSET:
/* Release Key */
case USB_AUDIO_OUT:
usb_headset_detect(type);
break;
default:
HS_LOG("Unknown headset type");
}
}
void headset_ext_button(int headset_type, int key_code, int press)
{
HS_LOG("Headset %d, Key %d, Press %d", headset_type, key_code, press);
headset_button_event(press, key_code);
}
int switch_send_event(unsigned int bit, int on)
{
unsigned long state;
HS_DBG();
mutex_lock(&hi->mutex_lock);
state = switch_get_state(&hi->sdev_h2w);
state &= ~(bit);
if (on)
state |= bit;
switch_set_state(&hi->sdev_h2w, state);
mutex_unlock(&hi->mutex_lock);
return 0;
}
static ssize_t headset_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int length = 0;
char *state;
HS_DBG();
switch (hi->hs_35mm_type) {
case HEADSET_UNPLUG:
state = "headset_unplug";
break;
case HEADSET_NO_MIC:
state = "headset_no_mic";
break;
case HEADSET_MIC:
state = "headset_mic";
break;
case HEADSET_METRICO:
state = "headset_metrico";
break;
case HEADSET_UNKNOWN_MIC:
state = "headset_unknown_mic";
break;
case HEADSET_TV_OUT:
state = "headset_tv_out";
break;
case HEADSET_UNSTABLE:
state = "headset_unstable";
break;
case HEADSET_BEATS:
state = "headset_beats";
break;
case HEADSET_BEATS_SOLO:
state = "headset_beats_solo";
break;
case HEADSET_INDICATOR:
state = "headset_indicator";
break;
default:
state = "error_state";
}
length = sprintf(buf, "%s\n", state);
return length;
}
static ssize_t headset_state_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
HS_DBG();
return 0;
}
static DEVICE_HEADSET_ATTR(state, 0644, headset_state_show,
headset_state_store);
static ssize_t headset_simulate_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
HS_DBG();
return sprintf(buf, "Command is not supported\n");
}
static ssize_t headset_simulate_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned long state = 0;
HS_DBG();
state = MASK_35MM_HEADSET | MASK_USB_HEADSET;
switch_send_event(state, 0);
if (strncmp(buf, "headset_unplug", count - 1) == 0) {
HS_LOG("Headset simulation: headset_unplug");
set_35mm_hw_state(0);
hi->hs_35mm_type = HEADSET_UNPLUG;
return count;
}
set_35mm_hw_state(1);
state = BIT_35MM_HEADSET;
if (strncmp(buf, "headset_no_mic", count - 1) == 0) {
HS_LOG("Headset simulation: headset_no_mic");
hi->hs_35mm_type = HEADSET_NO_MIC;
state |= BIT_HEADSET_NO_MIC;
} else if (strncmp(buf, "headset_mic", count - 1) == 0) {
HS_LOG("Headset simulation: headset_mic");
hi->hs_35mm_type = HEADSET_MIC;
state |= BIT_HEADSET;
} else if (strncmp(buf, "headset_metrico", count - 1) == 0) {
HS_LOG("Headset simulation: headset_metrico");
hi->hs_35mm_type = HEADSET_METRICO;
state |= BIT_HEADSET;
} else if (strncmp(buf, "headset_unknown_mic", count - 1) == 0) {
HS_LOG("Headset simulation: headset_unknown_mic");
hi->hs_35mm_type = HEADSET_UNKNOWN_MIC;
state |= BIT_HEADSET_NO_MIC;
} else if (strncmp(buf, "headset_tv_out", count - 1) == 0) {
HS_LOG("Headset simulation: headset_tv_out");
hi->hs_35mm_type = HEADSET_TV_OUT;
state |= BIT_TV_OUT;
#if defined(CONFIG_FB_MSM_TVOUT) && defined(CONFIG_ARCH_MSM8X60)
tvout_enable_detection(1);
#endif
} else if (strncmp(buf, "headset_indicator", count - 1) == 0) {
HS_LOG("Headset simulation: headset_indicator");
hi->hs_35mm_type = HEADSET_INDICATOR;
} else if (strncmp(buf, "headset_beats", count - 1) == 0) {
HS_LOG("Headset simulation: headset_beats");
hi->hs_35mm_type = HEADSET_BEATS;
state |= BIT_HEADSET;
} else if (strncmp(buf, "headset_beats_solo", count - 1) == 0) {
HS_LOG("Headset simulation: headset_beats_solo");
hi->hs_35mm_type = HEADSET_BEATS_SOLO;
state |= BIT_HEADSET;
} else {
HS_LOG("Invalid parameter");
return count;
}
switch_send_event(state, 1);
return count;
}
static DEVICE_HEADSET_ATTR(simulate, 0644, headset_simulate_show,
headset_simulate_store);
static ssize_t tty_flag_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
char *s = buf;
HS_DBG();
mutex_lock(&hi->mutex_lock);
s += sprintf(s, "%d\n", hi->tty_enable_flag);
mutex_unlock(&hi->mutex_lock);
return (s - buf);
}
static ssize_t tty_flag_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int state;
HS_DBG();
mutex_lock(&hi->mutex_lock);
state = switch_get_state(&hi->sdev_h2w);
state &= ~(BIT_TTY_FULL | BIT_TTY_VCO | BIT_TTY_HCO);
if (count == (strlen("enable") + 1) &&
strncmp(buf, "enable", strlen("enable")) == 0) {
hi->tty_enable_flag = 1;
switch_set_state(&hi->sdev_h2w, state | BIT_TTY_FULL);
mutex_unlock(&hi->mutex_lock);
HS_LOG("Enable TTY FULL");
return count;
}
if (count == (strlen("vco_enable") + 1) &&
strncmp(buf, "vco_enable", strlen("vco_enable")) == 0) {
hi->tty_enable_flag = 2;
switch_set_state(&hi->sdev_h2w, state | BIT_TTY_VCO);
mutex_unlock(&hi->mutex_lock);
HS_LOG("Enable TTY VCO");
return count;
}
if (count == (strlen("hco_enable") + 1) &&
strncmp(buf, "hco_enable", strlen("hco_enable")) == 0) {
hi->tty_enable_flag = 3;
switch_set_state(&hi->sdev_h2w, state | BIT_TTY_HCO);
mutex_unlock(&hi->mutex_lock);
HS_LOG("Enable TTY HCO");
return count;
}
if (count == (strlen("disable") + 1) &&
strncmp(buf, "disable", strlen("disable")) == 0) {
hi->tty_enable_flag = 0;
switch_set_state(&hi->sdev_h2w, state);
mutex_unlock(&hi->mutex_lock);
HS_LOG("Disable TTY");
return count;
}
mutex_unlock(&hi->mutex_lock);
HS_LOG("Invalid TTY argument");
return -EINVAL;
}
static DEVICE_ACCESSORY_ATTR(tty, 0644, tty_flag_show, tty_flag_store);
static ssize_t fm_flag_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
char *s = buf;
char *state;
HS_DBG();
mutex_lock(&hi->mutex_lock);
switch (hi->fm_flag) {
case 0:
state = "disable";
break;
case 1:
state = "fm_headset";
break;
case 2:
state = "fm_speaker";
break;
default:
state = "unknown_fm_status";
}
s += sprintf(s, "%s\n", state);
mutex_unlock(&hi->mutex_lock);
return (s - buf);
}
static ssize_t fm_flag_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int state;
HS_DBG();
mutex_lock(&hi->mutex_lock);
state = switch_get_state(&hi->sdev_h2w);
state &= ~(BIT_FM_HEADSET | BIT_FM_SPEAKER);
if (count == (strlen("fm_headset") + 1) &&
strncmp(buf, "fm_headset", strlen("fm_headset")) == 0) {
hi->fm_flag = 1;
state |= BIT_FM_HEADSET;
HS_LOG("Enable FM HEADSET");
} else if (count == (strlen("fm_speaker") + 1) &&
strncmp(buf, "fm_speaker", strlen("fm_speaker")) == 0) {
hi->fm_flag = 2;
state |= BIT_FM_SPEAKER;
HS_LOG("Enable FM SPEAKER");
} else if (count == (strlen("disable") + 1) &&
strncmp(buf, "disable", strlen("disable")) == 0) {
hi->fm_flag = 0 ;
HS_LOG("Disable FM");
} else {
mutex_unlock(&hi->mutex_lock);
HS_LOG("Invalid FM argument");
return -EINVAL;
}
switch_set_state(&hi->sdev_h2w, state);
mutex_unlock(&hi->mutex_lock);
return count;
}
static DEVICE_ACCESSORY_ATTR(fm, 0644, fm_flag_show, fm_flag_store);
static ssize_t debug_flag_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int flag = hi->debug_flag;
int adc = -EINVAL;
int hpin_gpio = -EINVAL;
HS_DBG();
if (hs_mgr_notifier.hpin_gpio)
hpin_gpio = hs_mgr_notifier.hpin_gpio();
if (hs_mgr_notifier.remote_adc)
hs_mgr_notifier.remote_adc(&adc);
return sprintf(buf, "Debug Flag %d, HP_DET %d, ADC %d\n", flag,
hpin_gpio, adc);
}
static ssize_t debug_flag_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
unsigned long state = 0;
HS_DBG();
if (strncmp(buf, "enable", count - 1) == 0) {
if (hi->debug_flag & DEBUG_FLAG_ADC) {
HS_LOG("Debug work is already running");
return count;
}
if (!debug_wq) {
debug_wq = create_workqueue("debug");
if (!debug_wq) {
HS_LOG("Failed to create debug workqueue");
return count;
}
}
HS_LOG("Enable headset debug");
mutex_lock(&hi->mutex_lock);
hi->debug_flag |= DEBUG_FLAG_ADC;
mutex_unlock(&hi->mutex_lock);
queue_work(debug_wq, &debug_work);
} else if (strncmp(buf, "disable", count - 1) == 0) {
if (!(hi->debug_flag & DEBUG_FLAG_ADC)) {
HS_LOG("Debug work has been stopped");
return count;
}
HS_LOG("Disable headset debug");
mutex_lock(&hi->mutex_lock);
hi->debug_flag &= ~DEBUG_FLAG_ADC;
mutex_unlock(&hi->mutex_lock);
if (debug_wq) {
flush_workqueue(debug_wq);
destroy_workqueue(debug_wq);
debug_wq = NULL;
}
} else if (strncmp(buf, "debug_log_enable", count - 1) == 0) {
HS_LOG("Enable headset debug log");
hi->debug_flag |= DEBUG_FLAG_LOG;
} else if (strncmp(buf, "debug_log_disable", count - 1) == 0) {
HS_LOG("Disable headset debug log");
hi->debug_flag &= ~DEBUG_FLAG_LOG;
} else if (strncmp(buf, "no_headset", count - 1) == 0) {
HS_LOG("Headset simulation: no_headset");
state = BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_35MM_HEADSET |
BIT_TV_OUT | BIT_USB_AUDIO_OUT;
switch_send_event(state, 0);
} else if (strncmp(buf, "35mm_mic", count - 1) == 0) {
HS_LOG("Headset simulation: 35mm_mic");
state = BIT_HEADSET | BIT_35MM_HEADSET;
switch_send_event(state, 1);
} else if (strncmp(buf, "35mm_no_mic", count - 1) == 0) {
HS_LOG("Headset simulation: 35mm_no_mic");
state = BIT_HEADSET_NO_MIC | BIT_35MM_HEADSET;
switch_send_event(state, 1);
} else if (strncmp(buf, "35mm_tv_out", count - 1) == 0) {
HS_LOG("Headset simulation: 35mm_tv_out");
state = BIT_TV_OUT | BIT_35MM_HEADSET;
switch_send_event(state, 1);
} else if (strncmp(buf, "usb_audio", count - 1) == 0) {
HS_LOG("Headset simulation: usb_audio");
state = BIT_USB_AUDIO_OUT;
switch_send_event(state, 1);
} else {
HS_LOG("Invalid parameter");
return count;
}
return count;
}
static DEVICE_ACCESSORY_ATTR(debug, 0644, debug_flag_show, debug_flag_store);
static int register_attributes(void)
{
int ret = 0;
hi->htc_accessory_class = class_create(THIS_MODULE, "htc_accessory");
if (IS_ERR(hi->htc_accessory_class)) {
ret = PTR_ERR(hi->htc_accessory_class);
hi->htc_accessory_class = NULL;
goto err_create_class;
}
/* Register headset attributes */
hi->headset_dev = device_create(hi->htc_accessory_class,
NULL, 0, "%s", "headset");
if (unlikely(IS_ERR(hi->headset_dev))) {
ret = PTR_ERR(hi->headset_dev);
hi->headset_dev = NULL;
goto err_create_headset_device;
}
ret = device_create_file(hi->headset_dev, &dev_attr_headset_state);
if (ret)
goto err_create_headset_state_device_file;
ret = device_create_file(hi->headset_dev, &dev_attr_headset_simulate);
if (ret)
goto err_create_headset_simulate_device_file;
/* Register TTY attributes */
hi->tty_dev = device_create(hi->htc_accessory_class,
NULL, 0, "%s", "tty");
if (unlikely(IS_ERR(hi->tty_dev))) {
ret = PTR_ERR(hi->tty_dev);
hi->tty_dev = NULL;
goto err_create_tty_device;
}
ret = device_create_file(hi->tty_dev, &dev_attr_tty);
if (ret)
goto err_create_tty_device_file;
/* Register FM attributes */
hi->fm_dev = device_create(hi->htc_accessory_class,
NULL, 0, "%s", "fm");
if (unlikely(IS_ERR(hi->fm_dev))) {
ret = PTR_ERR(hi->fm_dev);
hi->fm_dev = NULL;
goto err_create_fm_device;
}
ret = device_create_file(hi->fm_dev, &dev_attr_fm);
if (ret)
goto err_create_fm_device_file;
/* Register debug attributes */
hi->debug_dev = device_create(hi->htc_accessory_class,
NULL, 0, "%s", "debug");
if (unlikely(IS_ERR(hi->debug_dev))) {
ret = PTR_ERR(hi->debug_dev);
hi->debug_dev = NULL;
goto err_create_debug_device;
}
/* register the attributes */
ret = device_create_file(hi->debug_dev, &dev_attr_debug);
if (ret)
goto err_create_debug_device_file;
return 0;
err_create_debug_device_file:
device_unregister(hi->debug_dev);
err_create_debug_device:
device_remove_file(hi->fm_dev, &dev_attr_fm);
err_create_fm_device_file:
device_unregister(hi->fm_dev);
err_create_fm_device:
device_remove_file(hi->tty_dev, &dev_attr_tty);
err_create_tty_device_file:
device_unregister(hi->tty_dev);
err_create_tty_device:
device_remove_file(hi->headset_dev, &dev_attr_headset_simulate);
err_create_headset_simulate_device_file:
device_remove_file(hi->headset_dev, &dev_attr_headset_state);
err_create_headset_state_device_file:
device_unregister(hi->headset_dev);
err_create_headset_device:
class_destroy(hi->htc_accessory_class);
err_create_class:
return ret;
}
static void unregister_attributes(void)
{
device_remove_file(hi->debug_dev, &dev_attr_debug);
device_unregister(hi->debug_dev);
device_remove_file(hi->fm_dev, &dev_attr_fm);
device_unregister(hi->fm_dev);
device_remove_file(hi->tty_dev, &dev_attr_tty);
device_unregister(hi->tty_dev);
device_remove_file(hi->headset_dev, &dev_attr_headset_simulate);
device_remove_file(hi->headset_dev, &dev_attr_headset_state);
device_unregister(hi->headset_dev);
class_destroy(hi->htc_accessory_class);
}
static void headset_mgr_init(void)
{
if (hi->pdata.hptv_det_hp_gpio)
gpio_set_value(hi->pdata.hptv_det_hp_gpio, 1);
if (hi->pdata.hptv_det_tv_gpio)
gpio_set_value(hi->pdata.hptv_det_tv_gpio, 0);
if (hi->pdata.hptv_sel_gpio)
gpio_set_value(hi->pdata.hptv_sel_gpio, 0);
}
static void htc_headset_mgr_early_suspend(struct early_suspend *h)
{
HS_DBG();
}
static void htc_headset_mgr_late_resume(struct early_suspend *h)
{
#ifdef HTC_HEADSET_CONFIG_QUICK_BOOT
int state = 0;
HS_DBG();
if (hi->quick_boot_status) {
mutex_lock(&hi->mutex_lock);
state = switch_get_state(&hi->sdev_h2w);
HS_LOG_TIME("Resend quick boot U-Event (state = %d)",
state | BIT_UNDEFINED);
switch_set_state(&hi->sdev_h2w, state | BIT_UNDEFINED);
HS_LOG_TIME("Resend quick boot U-Event (state = %d)", state);
switch_set_state(&hi->sdev_h2w, state);
hi->quick_boot_status = 0;
mutex_unlock(&hi->mutex_lock);
}
#else
HS_DBG();
#endif
}
static int htc_headset_mgr_suspend(struct platform_device *pdev,
pm_message_t mesg)
{
HS_DBG();
#ifdef HTC_HEADSET_CONFIG_QUICK_BOOT
if (gpio_event_get_quickboot_status())
hi->quick_boot_status = 1;
#endif
return 0;
}
static int htc_headset_mgr_resume(struct platform_device *pdev)
{
HS_DBG();
return 0;
}
static int htc_headset_mgr_probe(struct platform_device *pdev)
{
int ret;
struct htc_headset_mgr_platform_data *pdata = pdev->dev.platform_data;
HS_LOG("++++++++++++++++++++");
hi = kzalloc(sizeof(struct htc_headset_mgr_info), GFP_KERNEL);
if (!hi)
return -ENOMEM;
hi->pdata.driver_flag = pdata->driver_flag;
hi->pdata.headset_devices_num = pdata->headset_devices_num;
hi->pdata.headset_devices = pdata->headset_devices;
hi->pdata.headset_config_num = pdata->headset_config_num;
hi->pdata.headset_config = pdata->headset_config;
hi->pdata.hptv_det_hp_gpio = pdata->hptv_det_hp_gpio;
hi->pdata.hptv_det_tv_gpio = pdata->hptv_det_tv_gpio;
hi->pdata.hptv_sel_gpio = pdata->hptv_sel_gpio;
hi->pdata.headset_init = pdata->headset_init;
hi->pdata.headset_power = pdata->headset_power;
if (hi->pdata.headset_init)
hi->pdata.headset_init();
hi->driver_init_seq = 0;
hi->early_suspend.suspend = htc_headset_mgr_early_suspend;
hi->early_suspend.resume = htc_headset_mgr_late_resume;
register_early_suspend(&hi->early_suspend);
wake_lock_init(&hi->hs_wake_lock, WAKE_LOCK_SUSPEND, DRIVER_NAME);
hi->hpin_jiffies = jiffies;
hi->usb_headset.type = USB_NO_HEADSET;
hi->usb_headset.status = STATUS_DISCONNECTED;
hi->hs_35mm_type = HEADSET_UNPLUG;
hi->h2w_35mm_type = HEADSET_UNPLUG;
hi->is_ext_insert = 0;
hi->mic_bias_state = 0;
hi->mic_detect_counter = 0;
hi->key_level_flag = -1;
hi->quick_boot_status = 0;
atomic_set(&hi->btn_state, 0);
hi->tty_enable_flag = 0;
hi->fm_flag = 0;
hi->debug_flag = 0;
mutex_init(&hi->mutex_lock);
hi->sdev_h2w.name = "h2w";
hi->sdev_h2w.print_name = h2w_print_name;
ret = switch_dev_register(&hi->sdev_h2w);
if (ret < 0)
goto err_h2w_switch_dev_register;
hi->sdev_usb_audio.name = "usb_audio";
hi->sdev_usb_audio.print_name = usb_audio_print_name;
ret = switch_dev_register(&hi->sdev_usb_audio);
if (ret < 0)
goto err_usb_audio_switch_dev_register;
detect_wq = create_workqueue("detect");
if (detect_wq == NULL) {
ret = -ENOMEM;
HS_ERR("Failed to create detect workqueue");
goto err_create_detect_work_queue;
}
button_wq = create_workqueue("button");
if (button_wq == NULL) {
ret = -ENOMEM;
HS_ERR("Failed to create button workqueue");
goto err_create_button_work_queue;
}
hi->input = input_allocate_device();
if (!hi->input) {
ret = -ENOMEM;
goto err_request_input_dev;
}
hi->input->name = "h2w headset";
set_bit(EV_SYN, hi->input->evbit);
set_bit(EV_KEY, hi->input->evbit);
set_bit(KEY_END, hi->input->keybit);
set_bit(KEY_MUTE, hi->input->keybit);
set_bit(KEY_VOLUMEDOWN, hi->input->keybit);
set_bit(KEY_VOLUMEUP, hi->input->keybit);
set_bit(KEY_NEXTSONG, hi->input->keybit);
set_bit(KEY_PLAYPAUSE, hi->input->keybit);
set_bit(KEY_PREVIOUSSONG, hi->input->keybit);
set_bit(KEY_MEDIA, hi->input->keybit);
set_bit(KEY_SEND, hi->input->keybit);
ret = input_register_device(hi->input);
if (ret < 0)
goto err_register_input_dev;
ret = register_attributes();
if (ret)
goto err_register_attributes;
#ifdef HTC_HEADSET_CONFIG_MSM_RPC
if (hi->pdata.driver_flag & DRIVER_HS_MGR_RPC_SERVER) {
/* Create RPC server */
ret = msm_rpc_create_server(&hs_rpc_server);
if (ret < 0) {
HS_ERR("Failed to create RPC server");
goto err_create_rpc_server;
}
HS_LOG("Create RPC server successfully");
}
#else
HS_DBG("NOT support RPC (%du, %du)", hs_rpc_server.prog,
hs_rpc_server.vers);
#endif
headset_mgr_init();
hs_notify_driver_ready(DRIVER_NAME);
HS_LOG("--------------------");
return 0;
#ifdef HTC_HEADSET_CONFIG_MSM_RPC
err_create_rpc_server:
#endif
err_register_attributes:
input_unregister_device(hi->input);
err_register_input_dev:
input_free_device(hi->input);
err_request_input_dev:
destroy_workqueue(button_wq);
err_create_button_work_queue:
destroy_workqueue(detect_wq);
err_create_detect_work_queue:
switch_dev_unregister(&hi->sdev_usb_audio);
err_usb_audio_switch_dev_register:
switch_dev_unregister(&hi->sdev_h2w);
err_h2w_switch_dev_register:
mutex_destroy(&hi->mutex_lock);
wake_lock_destroy(&hi->hs_wake_lock);
kfree(hi);
HS_ERR("Failed to register %s driver", DRIVER_NAME);
return ret;
}
static int htc_headset_mgr_remove(struct platform_device *pdev)
{
#if 0
if ((switch_get_state(&hi->sdev_h2w) & MASK_HEADSET) != 0)
remove_headset();
#endif
unregister_attributes();
input_unregister_device(hi->input);
destroy_workqueue(button_wq);
destroy_workqueue(detect_wq);
switch_dev_unregister(&hi->sdev_usb_audio);
switch_dev_unregister(&hi->sdev_h2w);
mutex_destroy(&hi->mutex_lock);
wake_lock_destroy(&hi->hs_wake_lock);
kfree(hi);
return 0;
}
static struct platform_driver htc_headset_mgr_driver = {
.probe = htc_headset_mgr_probe,
.remove = htc_headset_mgr_remove,
.suspend = htc_headset_mgr_suspend,
.resume = htc_headset_mgr_resume,
.driver = {
.name = "HTC_HEADSET_MGR",
.owner = THIS_MODULE,
},
};
static int __init htc_headset_mgr_init(void)
{
return platform_driver_register(&htc_headset_mgr_driver);
}
static void __exit htc_headset_mgr_exit(void)
{
platform_driver_unregister(&htc_headset_mgr_driver);
}
module_init(htc_headset_mgr_init);
module_exit(htc_headset_mgr_exit);
MODULE_DESCRIPTION("HTC headset manager driver");
MODULE_LICENSE("GPL");
| mwoodward/Amaze-ics-sense | arch/arm/mach-msm/htc_headset_mgr.c | C | gpl-2.0 | 42,617 |
/*
* drivers/gpu/ion/ion_system_heap.c
*
* Copyright (C) 2011 Google, Inc.
* Copyright (c) 2011-2015, The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <asm/page.h>
#include <linux/dma-mapping.h>
#include <linux/err.h>
#include <linux/highmem.h>
#include <linux/mm.h>
#include <linux/scatterlist.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include "ion.h"
#include "ion_priv.h"
#include <linux/dma-mapping.h>
#include <trace/events/kmem.h>
static gfp_t high_order_gfp_flags = (GFP_HIGHUSER | __GFP_NOWARN |
__GFP_NO_KSWAPD | __GFP_NORETRY)
& ~__GFP_WAIT;
static gfp_t low_order_gfp_flags = (GFP_HIGHUSER | __GFP_NOWARN);
#ifndef CONFIG_ALLOC_BUFFERS_IN_4K_CHUNKS
static const unsigned int orders[] = {9, 8, 4, 0};
#else
static const unsigned int orders[] = {0};
#endif
static const int num_orders = ARRAY_SIZE(orders);
static int order_to_index(unsigned int order)
{
int i;
for (i = 0; i < num_orders; i++)
if (order == orders[i])
return i;
BUG();
return -1;
}
static unsigned int order_to_size(int order)
{
return PAGE_SIZE << order;
}
struct ion_system_heap {
struct ion_heap heap;
struct ion_page_pool **uncached_pools;
struct ion_page_pool **cached_pools;
};
struct page_info {
struct page *page;
bool from_pool;
unsigned int order;
struct list_head list;
};
static struct page *alloc_buffer_page(struct ion_system_heap *heap,
struct ion_buffer *buffer,
unsigned long order,
bool *from_pool)
{
bool cached = ion_buffer_cached(buffer);
struct page *page;
struct ion_page_pool *pool;
if (!cached)
pool = heap->uncached_pools[order_to_index(order)];
else
pool = heap->cached_pools[order_to_index(order)];
page = ion_page_pool_alloc(pool, from_pool);
if (!page)
return 0;
return page;
}
#ifdef CONFIG_ION_MSM_SYSTEM_HEAP_POOL_LIMIT
/* Calculate uncached and cached pool pages from system heap
*
* @param heap current system heap
* @return total total uncached and cached pool pages
*/
static unsigned long get_system_heap_pool_total(struct ion_system_heap *heap)
{
int i;
unsigned long total = 0;
for (i = 0; i < num_orders; i++) {
struct ion_page_pool *uncached_pool = heap->uncached_pools[i];
struct ion_page_pool *cached_pool = heap->cached_pools[i];
total += (1 << uncached_pool->order) * (uncached_pool->high_count + uncached_pool->low_count) +
(1 << cached_pool->order) * (cached_pool->high_count + cached_pool->low_count);
}
return total;
}
#endif
static void free_buffer_page(struct ion_system_heap *heap,
struct ion_buffer *buffer, struct page *page,
unsigned int order)
{
bool cached = ion_buffer_cached(buffer);
if (!(buffer->private_flags & ION_PRIV_FLAG_SHRINKER_FREE)) {
struct ion_page_pool *pool;
#ifdef CONFIG_ION_MSM_SYSTEM_HEAP_POOL_LIMIT
if (get_system_heap_pool_total(heap) > CONFIG_MAX_ION_MSM_SYSTEM_HEAP_POOL) {
__free_pages(page, order);
return;
}
#endif
if (cached)
pool = heap->cached_pools[order_to_index(order)];
else
pool = heap->uncached_pools[order_to_index(order)];
ion_page_pool_free(pool, page);
} else {
__free_pages(page, order);
}
}
static struct page_info *alloc_largest_available(struct ion_system_heap *heap,
struct ion_buffer *buffer,
unsigned long size,
unsigned int max_order)
{
struct page *page;
struct page_info *info;
int i;
bool from_pool;
info = kmalloc(sizeof(struct page_info), GFP_KERNEL);
if (!info)
return NULL;
for (i = 0; i < num_orders; i++) {
if (size < order_to_size(orders[i]))
continue;
if (max_order < orders[i])
continue;
page = alloc_buffer_page(heap, buffer, orders[i], &from_pool);
if (!page)
continue;
info->page = page;
info->order = orders[i];
info->from_pool = from_pool;
INIT_LIST_HEAD(&info->list);
return info;
}
kfree(info);
return NULL;
}
static unsigned int process_info(struct page_info *info,
struct scatterlist *sg,
struct scatterlist *sg_sync,
struct pages_mem *data, unsigned int i)
{
struct page *page = info->page;
unsigned int j;
if (sg_sync) {
sg_set_page(sg_sync, page, (1 << info->order) * PAGE_SIZE, 0);
sg_dma_address(sg_sync) = page_to_phys(page);
}
sg_set_page(sg, page, (1 << info->order) * PAGE_SIZE, 0);
/*
* This is not correct - sg_dma_address needs a dma_addr_t
* that is valid for the the targeted device, but this works
* on the currently targeted hardware.
*/
sg_dma_address(sg) = page_to_phys(page);
if (data) {
for (j = 0; j < (1 << info->order); ++j)
data->pages[i++] = nth_page(page, j);
}
list_del(&info->list);
kfree(info);
return i;
}
static int ion_system_heap_allocate(struct ion_heap *heap,
struct ion_buffer *buffer,
unsigned long size, unsigned long align,
unsigned long flags)
{
struct ion_system_heap *sys_heap = container_of(heap,
struct ion_system_heap,
heap);
struct sg_table *table;
struct sg_table table_sync;
struct scatterlist *sg;
struct scatterlist *sg_sync;
int ret;
struct list_head pages;
struct list_head pages_from_pool;
struct page_info *info, *tmp_info;
int i = 0;
unsigned int nents_sync = 0;
unsigned long size_remaining = PAGE_ALIGN(size);
unsigned int max_order = orders[0];
struct pages_mem data;
unsigned int sz;
if (align > PAGE_SIZE)
return -EINVAL;
if (size / PAGE_SIZE > totalram_pages / 2)
return -ENOMEM;
data.size = 0;
INIT_LIST_HEAD(&pages);
INIT_LIST_HEAD(&pages_from_pool);
while (size_remaining > 0) {
info = alloc_largest_available(sys_heap, buffer, size_remaining,
max_order);
if (!info)
goto err;
sz = (1 << info->order) * PAGE_SIZE;
if (info->from_pool) {
list_add_tail(&info->list, &pages_from_pool);
} else {
list_add_tail(&info->list, &pages);
data.size += sz;
++nents_sync;
}
size_remaining -= sz;
max_order = info->order;
i++;
}
ret = msm_ion_heap_alloc_pages_mem(&data);
if (ret)
goto err;
table = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
if (!table)
goto err_free_data_pages;
ret = sg_alloc_table(table, i, GFP_KERNEL);
if (ret)
goto err1;
if (nents_sync) {
ret = sg_alloc_table(&table_sync, nents_sync, GFP_KERNEL);
if (ret)
goto err_free_sg;
}
i = 0;
sg = table->sgl;
sg_sync = table_sync.sgl;
/*
* We now have two separate lists. One list contains pages from the
* pool and the other pages from buddy. We want to merge these
* together while preserving the ordering of the pages (higher order
* first).
*/
do {
info = list_first_entry_or_null(&pages, struct page_info, list);
tmp_info = list_first_entry_or_null(&pages_from_pool,
struct page_info, list);
if (info && tmp_info) {
if (info->order >= tmp_info->order) {
i = process_info(info, sg, sg_sync, &data, i);
sg_sync = sg_next(sg_sync);
} else {
i = process_info(tmp_info, sg, 0, 0, i);
}
} else if (info) {
i = process_info(info, sg, sg_sync, &data, i);
sg_sync = sg_next(sg_sync);
} else if (tmp_info) {
i = process_info(tmp_info, sg, 0, 0, i);
} else {
BUG();
}
sg = sg_next(sg);
} while (sg);
ret = msm_ion_heap_pages_zero(data.pages, data.size >> PAGE_SHIFT);
if (ret) {
pr_err("Unable to zero pages\n");
goto err_free_sg2;
}
if (nents_sync)
dma_sync_sg_for_device(NULL, table_sync.sgl, table_sync.nents,
DMA_BIDIRECTIONAL);
buffer->priv_virt = table;
if (nents_sync)
sg_free_table(&table_sync);
msm_ion_heap_free_pages_mem(&data);
return 0;
err_free_sg2:
/* We failed to zero buffers. Bypass pool */
buffer->flags |= ION_PRIV_FLAG_SHRINKER_FREE;
for_each_sg(table->sgl, sg, table->nents, i)
free_buffer_page(sys_heap, buffer, sg_page(sg),
get_order(sg->length));
if (nents_sync)
sg_free_table(&table_sync);
err_free_sg:
sg_free_table(table);
err1:
kfree(table);
err_free_data_pages:
msm_ion_heap_free_pages_mem(&data);
err:
list_for_each_entry_safe(info, tmp_info, &pages, list) {
free_buffer_page(sys_heap, buffer, info->page, info->order);
kfree(info);
}
list_for_each_entry_safe(info, tmp_info, &pages_from_pool, list) {
free_buffer_page(sys_heap, buffer, info->page, info->order);
kfree(info);
}
return -ENOMEM;
}
void ion_system_heap_free(struct ion_buffer *buffer)
{
struct ion_heap *heap = buffer->heap;
struct ion_system_heap *sys_heap = container_of(heap,
struct ion_system_heap,
heap);
struct sg_table *table = buffer->sg_table;
struct scatterlist *sg;
LIST_HEAD(pages);
int i;
if (!(buffer->private_flags & ION_PRIV_FLAG_SHRINKER_FREE))
msm_ion_heap_buffer_zero(buffer);
for_each_sg(table->sgl, sg, table->nents, i)
free_buffer_page(sys_heap, buffer, sg_page(sg),
get_order(sg->length));
sg_free_table(table);
kfree(table);
}
struct sg_table *ion_system_heap_map_dma(struct ion_heap *heap,
struct ion_buffer *buffer)
{
return buffer->priv_virt;
}
void ion_system_heap_unmap_dma(struct ion_heap *heap,
struct ion_buffer *buffer)
{
return;
}
static int ion_system_heap_shrink(struct ion_heap *heap, gfp_t gfp_mask,
int nr_to_scan)
{
struct ion_system_heap *sys_heap;
int nr_total = 0;
int i;
sys_heap = container_of(heap, struct ion_system_heap, heap);
for (i = 0; i < num_orders; i++) {
struct ion_page_pool *pool = sys_heap->uncached_pools[i];
nr_total += ion_page_pool_shrink(pool, gfp_mask, nr_to_scan);
pool = sys_heap->cached_pools[i];
nr_total += ion_page_pool_shrink(pool, gfp_mask, nr_to_scan);
}
return nr_total;
}
static struct ion_heap_ops system_heap_ops = {
.allocate = ion_system_heap_allocate,
.free = ion_system_heap_free,
.map_dma = ion_system_heap_map_dma,
.unmap_dma = ion_system_heap_unmap_dma,
.map_kernel = ion_heap_map_kernel,
.unmap_kernel = ion_heap_unmap_kernel,
.map_user = ion_heap_map_user,
.shrink = ion_system_heap_shrink,
};
static int ion_system_heap_debug_show(struct ion_heap *heap, struct seq_file *s,
void *unused)
{
struct ion_system_heap *sys_heap = container_of(heap,
struct ion_system_heap,
heap);
bool use_seq = s != NULL;
unsigned long uncached_total = 0;
unsigned long cached_total = 0;
int i;
for (i = 0; i < num_orders; i++) {
struct ion_page_pool *pool = sys_heap->uncached_pools[i];
if (use_seq) {
seq_printf(s,
"%d order %u highmem pages in uncached pool = %lu total\n",
pool->high_count, pool->order,
(1 << pool->order) * PAGE_SIZE *
pool->high_count);
seq_printf(s,
"%d order %u lowmem pages in uncached pool = %lu total\n",
pool->low_count, pool->order,
(1 << pool->order) * PAGE_SIZE *
pool->low_count);
}
uncached_total += (1 << pool->order) * PAGE_SIZE *
pool->high_count;
uncached_total += (1 << pool->order) * PAGE_SIZE *
pool->low_count;
}
for (i = 0; i < num_orders; i++) {
struct ion_page_pool *pool = sys_heap->cached_pools[i];
if (use_seq) {
seq_printf(s,
"%d order %u highmem pages in cached pool = %lu total\n",
pool->high_count, pool->order,
(1 << pool->order) * PAGE_SIZE * pool->high_count);
seq_printf(s,
"%d order %u lowmem pages in cached pool = %lu total\n",
pool->low_count, pool->order,
(1 << pool->order) * PAGE_SIZE *
pool->low_count);
}
cached_total += (1 << pool->order) * PAGE_SIZE *
pool->high_count;
cached_total += (1 << pool->order) * PAGE_SIZE *
pool->low_count;
}
if (use_seq) {
seq_puts(s, "--------------------------------------------\n");
seq_printf(s, "uncached pool = %lu cached pool = %lu\n",
uncached_total, cached_total);
seq_printf(s, "pool total (uncached + cached) = %lu\n",
uncached_total + cached_total);
seq_puts(s, "--------------------------------------------\n");
} else {
pr_info("-------------------------------------------------\n");
pr_info("uncached pool = %lu cached pool = %lu\n",
uncached_total, cached_total);
pr_info("pool total (uncached + cached) = %lu\n",
uncached_total + cached_total);
pr_info("-------------------------------------------------\n");
}
return 0;
}
static void ion_system_heap_destroy_pools(struct ion_page_pool **pools)
{
int i;
for (i = 0; i < num_orders; i++)
if (pools[i])
ion_page_pool_destroy(pools[i]);
}
/**
* ion_system_heap_create_pools - Creates pools for all orders
*
* If this fails you don't need to destroy any pools. It's all or
* nothing. If it succeeds you'll eventually need to use
* ion_system_heap_destroy_pools to destroy the pools.
*/
static int ion_system_heap_create_pools(struct ion_page_pool **pools)
{
int i;
for (i = 0; i < num_orders; i++) {
struct ion_page_pool *pool;
gfp_t gfp_flags = low_order_gfp_flags;
if (orders[i])
gfp_flags = high_order_gfp_flags;
pool = ion_page_pool_create(gfp_flags, orders[i]);
if (!pool)
goto err_create_pool;
pools[i] = pool;
}
return 0;
err_create_pool:
ion_system_heap_destroy_pools(pools);
return 1;
}
struct ion_heap *ion_system_heap_create(struct ion_platform_heap *unused)
{
struct ion_system_heap *heap;
int pools_size = sizeof(struct ion_page_pool *) * num_orders;
heap = kzalloc(sizeof(struct ion_system_heap), GFP_KERNEL);
if (!heap)
return ERR_PTR(-ENOMEM);
heap->heap.ops = &system_heap_ops;
heap->heap.type = ION_HEAP_TYPE_SYSTEM;
heap->heap.flags = ION_HEAP_FLAG_DEFER_FREE;
heap->uncached_pools = kzalloc(pools_size, GFP_KERNEL);
if (!heap->uncached_pools)
goto err_alloc_uncached_pools;
heap->cached_pools = kzalloc(pools_size, GFP_KERNEL);
if (!heap->cached_pools)
goto err_alloc_cached_pools;
if (ion_system_heap_create_pools(heap->uncached_pools))
goto err_create_uncached_pools;
if (ion_system_heap_create_pools(heap->cached_pools))
goto err_create_cached_pools;
heap->heap.debug_show = ion_system_heap_debug_show;
return &heap->heap;
err_create_cached_pools:
ion_system_heap_destroy_pools(heap->uncached_pools);
err_create_uncached_pools:
kfree(heap->cached_pools);
err_alloc_cached_pools:
kfree(heap->uncached_pools);
err_alloc_uncached_pools:
kfree(heap);
return ERR_PTR(-ENOMEM);
}
void ion_system_heap_destroy(struct ion_heap *heap)
{
struct ion_system_heap *sys_heap = container_of(heap,
struct ion_system_heap,
heap);
ion_system_heap_destroy_pools(sys_heap->uncached_pools);
ion_system_heap_destroy_pools(sys_heap->cached_pools);
kfree(sys_heap->uncached_pools);
kfree(sys_heap->cached_pools);
kfree(sys_heap);
}
static int ion_system_contig_heap_allocate(struct ion_heap *heap,
struct ion_buffer *buffer,
unsigned long len,
unsigned long align,
unsigned long flags)
{
int order = get_order(len);
struct page *page;
struct sg_table *table;
unsigned long i;
int ret;
if (align > (PAGE_SIZE << order))
return -EINVAL;
page = alloc_pages(low_order_gfp_flags | __GFP_ZERO, order);
if (!page)
return -ENOMEM;
split_page(page, order);
len = PAGE_ALIGN(len);
for (i = len >> PAGE_SHIFT; i < (1 << order); i++)
__free_page(page + i);
table = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
if (!table) {
ret = -ENOMEM;
goto out;
}
ret = sg_alloc_table(table, 1, GFP_KERNEL);
if (ret)
goto out;
sg_set_page(table->sgl, page, len, 0);
buffer->priv_virt = table;
ion_pages_sync_for_device(NULL, page, len, DMA_BIDIRECTIONAL);
return 0;
out:
for (i = 0; i < len >> PAGE_SHIFT; i++)
__free_page(page + i);
kfree(table);
return ret;
}
void ion_system_contig_heap_free(struct ion_buffer *buffer)
{
struct sg_table *table = buffer->priv_virt;
struct page *page = sg_page(table->sgl);
unsigned long pages = PAGE_ALIGN(buffer->size) >> PAGE_SHIFT;
unsigned long i;
for (i = 0; i < pages; i++)
__free_page(page + i);
sg_free_table(table);
kfree(table);
}
static int ion_system_contig_heap_phys(struct ion_heap *heap,
struct ion_buffer *buffer,
ion_phys_addr_t *addr, size_t *len)
{
struct sg_table *table = buffer->priv_virt;
struct page *page = sg_page(table->sgl);
*addr = page_to_phys(page);
*len = buffer->size;
return 0;
}
struct sg_table *ion_system_contig_heap_map_dma(struct ion_heap *heap,
struct ion_buffer *buffer)
{
return buffer->priv_virt;
}
void ion_system_contig_heap_unmap_dma(struct ion_heap *heap,
struct ion_buffer *buffer)
{
}
static struct ion_heap_ops kmalloc_ops = {
.allocate = ion_system_contig_heap_allocate,
.free = ion_system_contig_heap_free,
.phys = ion_system_contig_heap_phys,
.map_dma = ion_system_contig_heap_map_dma,
.unmap_dma = ion_system_contig_heap_unmap_dma,
.map_kernel = ion_heap_map_kernel,
.unmap_kernel = ion_heap_unmap_kernel,
.map_user = ion_heap_map_user,
};
struct ion_heap *ion_system_contig_heap_create(struct ion_platform_heap *unused)
{
struct ion_heap *heap;
heap = kzalloc(sizeof(struct ion_heap), GFP_KERNEL);
if (!heap)
return ERR_PTR(-ENOMEM);
heap->ops = &kmalloc_ops;
heap->type = ION_HEAP_TYPE_SYSTEM_CONTIG;
return heap;
}
void ion_system_contig_heap_destroy(struct ion_heap *heap)
{
kfree(heap);
}
| ashyx/Samsung_Galaxy_Tab_A_kernel | drivers/staging/android/ion/ion_system_heap.c | C | gpl-2.0 | 17,491 |
/***********************************************************************
* mt4j Copyright (c) 2008 - 2009, C.Ruff, Fraunhofer-Gesellschaft All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
***********************************************************************/
package org.mt4j.components.visibleComponents.widgets.progressBar;
import java.util.ArrayList;
import java.util.List;
import org.mt4j.input.IMTEventListener;
import org.mt4j.input.MTEvent;
/**
* The Class AbstractProgressThread.
*
* @author C.Ruff
*/
public abstract class AbstractProgressThread extends Thread implements IprogressInfoProvider {
/** The target. */
private float target;
/** The current. */
private float current;
/** The finished. */
private boolean finished;
/** The percentage finished. */
private float percentageFinished;
/** The sleep time. */
private long sleepTime;
/** The current action. */
private String currentAction;
/** The auto compute percentage. */
private boolean autoComputePercentage;
/** The loading finished listeners. */
private List<IMTEventListener> loadingFinishedListeners;
/**
* Instantiates a new abstract progress thread.
*
* @param sleepTime the sleep time
*/
public AbstractProgressThread(long sleepTime){
this.percentageFinished = 0.0f;
this.current = 0;
this.target = 1;
this.sleepTime = sleepTime;
this.finished = false;
this.currentAction = "Loading...";
this.autoComputePercentage = true;
this.loadingFinishedListeners = new ArrayList<IMTEventListener>();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
abstract public void run();
// abstract public boolean runConditionSatisfied();
/**
* Sets the value the current progress is at.
* <br>Fires a finished event if new current value is == target.
*
* @param current the current
*/
public void setCurrent(float current) {
this.current = current;
if (this.current == this.target){
this.setFinished(true);
}
}
/* (non-Javadoc)
* @see com.jMT.components.visibleComponents.progressBar.IprogressInfoProvider#getCurrent()
*/
public float getCurrent() {
return current;
}
/**
* Sets this progress to finished and fires finished event.
*
* @param finished the finished
*/
public void setFinished(boolean finished) {
this.fireEvent(new MTEvent(this));
this.finished = finished;
}
/* (non-Javadoc)
* @see com.jMT.components.visibleComponents.progressBar.IprogressInfoProvider#isFinished()
*/
public boolean isFinished() {
return finished;
}
/**
* Sets the percentage finished.
*
* @param percentageFinished the new percentage finished
*/
private void setPercentageFinished(float percentageFinished) {
this.percentageFinished = percentageFinished;
}
/* (non-Javadoc)
* @see com.jMT.components.visibleComponents.progressBar.IprogressInfoProvider#getPercentageFinished()
*/
public float getPercentageFinished() {
if (this.autoComputePercentage){
this.setPercentageFinished(100f/ this.getTarget() * this.getCurrent());
return this.percentageFinished;
}else{
return percentageFinished;
}
}
/**
* Sets the sleep time.
*
* @param sleepTime the new sleep time
*/
public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}
/**
* Sets the value, the progress has to reach.
*
* @param target the target
*/
public void setTarget(float target) {
this.target = target;
}
/* (non-Javadoc)
* @see com.jMT.components.visibleComponents.progressBar.IprogressInfoProvider#getTarget()
*/
public float getTarget() {
return target;
}
/**
* Checks if is auto compute percentage.
*
* @return true, if is auto compute percentage
*/
public boolean isAutoComputePercentage() {
return autoComputePercentage;
}
/**
* Sets the auto compute percentage.
*
* @param autoComputePercentage the new auto compute percentage
*/
public void setAutoComputePercentage(boolean autoComputePercentage) {
this.autoComputePercentage = autoComputePercentage;
}
/* (non-Javadoc)
* @see com.jMT.components.visibleComponents.progressBar.IprogressInfoProvider#getCurrentAction()
*/
public String getCurrentAction() {
return currentAction;
}
/**
* Sets a title or description of the action currently processed.
*
* @param currentAction the current action
*/
public void setCurrentAction(String currentAction) {
this.currentAction = currentAction;
}
/**
* Gets the sleep time.
*
* @return the sleep time
*/
public long getSleepTime() {
return sleepTime;
}
/////////////////////////////////////////////////////
/**
* Fire event.
*
* @param e the e
*/
protected void fireEvent(MTEvent e) {
synchronized(loadingFinishedListeners) {
for (int i = 0; i < loadingFinishedListeners.size(); i++) {
IMTEventListener listener = loadingFinishedListeners.get(i);
listener.processMTEvent(e);
}
}
}
/**
* Adds the progress finished listener.
*
* @param listener the listener
*/
public synchronized void addProgressFinishedListener(IMTEventListener listener){
if (!loadingFinishedListeners.contains(listener)){
loadingFinishedListeners.add(listener);
}
}
/**
* Removes the listener.
*
* @param listener the listener
*/
public synchronized void removeListener(IMTEventListener listener){
if (loadingFinishedListeners.contains(listener)){
loadingFinishedListeners.remove(listener);
}
}
/**
* Gets the listeners.
*
* @return the listeners
*/
public synchronized IMTEventListener[] getListeners(){
return loadingFinishedListeners.toArray(new IMTEventListener[this.loadingFinishedListeners.size()]);
}
/////////////////////////////////////////////////////
}
| Twelve-60/mt4j | src/org/mt4j/components/visibleComponents/widgets/progressBar/AbstractProgressThread.java | Java | gpl-2.0 | 6,687 |
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2009 Eric Lafortune ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.instruction;
/**
* This Instruction represents a simple instruction without variable arguments
* or constant pool references.
*
* @author Eric Lafortune
*/
public abstract class SwitchInstruction extends Instruction
{
public int defaultOffset;
public int[] jumpOffsets;
/**
* Creates an uninitialized SwitchInstruction.
*/
public SwitchInstruction() {}
/**
* Creates a new SwitchInstruction with the given arguments.
*/
public SwitchInstruction(byte opcode,
int defaultOffset,
int[] jumpOffsets)
{
this.opcode = opcode;
this.defaultOffset = defaultOffset;
this.jumpOffsets = jumpOffsets;
}
/**
* Copies the given instruction into this instruction.
* @param switchInstruction the instruction to be copied.
* @return this instruction.
*/
public SwitchInstruction copy(SwitchInstruction switchInstruction)
{
this.opcode = switchInstruction.opcode;
this.defaultOffset = switchInstruction.defaultOffset;
this.jumpOffsets = switchInstruction.jumpOffsets;
return this;
}
// Implementations for Instruction.
public String toString(int offset)
{
return "["+offset+"] "+toString()+" (target="+(offset+defaultOffset)+")";
}
// Implementations for Object.
public String toString()
{
return getName()+" ("+jumpOffsets.length+" offsets, default="+defaultOffset+")";
}
}
| qtekfun/htcDesire820Kernel | external/proguard/src/proguard/classfile/instruction/SwitchInstruction.java | Java | gpl-2.0 | 2,474 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "ultima/nuvie/core/nuvie_defs.h"
#include "ultima/nuvie/conf/configuration.h"
#include "ultima/nuvie/actors/actor_manager.h"
#include "ultima/nuvie/core/egg_manager.h"
#include "ultima/nuvie/core/tile_manager.h"
#include "ultima/nuvie/core/obj_manager.h"
#include "ultima/nuvie/usecode/usecode.h"
#include "ultima/nuvie/misc/u6_misc.h"
#include "ultima/nuvie/core/u6_objects.h"
#include "ultima/nuvie/misc/u6_llist.h"
#include "ultima/nuvie/files/nuvie_io_file.h"
#include "ultima/nuvie/core/game.h"
#include "ultima/nuvie/gui/widgets/map_window.h"
#include "ultima/nuvie/script/script.h"
#include "ultima/nuvie/gui/widgets/msg_scroll.h"
namespace Ultima {
namespace Nuvie {
static const int obj_egg_table[5] = {0, // NUVIE_GAME_NONE
335, // NUVIE_GAME_U6
466, // NUVIE_GAME_MD
0,
230
}; // NUVIE_GAME_SE
static iAVLKey get_iAVLKey(const void *item) {
return ((const ObjTreeNode *)item)->key;
}
ObjManager::ObjManager(Configuration *cfg, TileManager *tm, EggManager *em) {
uint8 i;
Std::string show_eggs_key;
config = cfg;
tile_manager = tm;
egg_manager = em;
usecode = NULL;
obj_save_count = 0;
load_basetile();
load_weight_table();
memset(actor_inventories, 0, sizeof(actor_inventories));
for (i = 0; i < 64; i++) {
surface[i] = iAVLAllocTree(get_iAVLKey);
}
for (i = 0; i < 5; i++) {
dungeon[i] = iAVLAllocTree(get_iAVLKey);
}
last_obj_blk_x = 0;
last_obj_blk_y = 0;
last_obj_blk_z = OBJ_TEMP_INIT;
config->value("config/GameType", game_type);
//save the egg tile_num incase we want to switch egg display on again.
egg_tile_num = get_obj_tile_num(obj_egg_table[game_type]);
show_eggs_key = config_get_game_key(config);
show_eggs_key.append("/show_eggs");
config->value(show_eggs_key, show_eggs);
//if(!show_eggs)
// show_egg_objs(false);
Std::string custom_tile_str;
config->value(config_get_game_key(config) + "/custom_actor_tiles", custom_tile_str, "default");
if (custom_tile_str == "default") {
if (Game::get_game()->is_new_style())
custom_actor_tiles = true;
else
custom_actor_tiles = false;
} else if (custom_tile_str == "yes")
custom_actor_tiles = true;
else
custom_actor_tiles = false;
}
ObjManager::~ObjManager() {
clean();
unsigned int i;
for (i = 0; i < 64; i++)
iAVLFreeTree(surface[i], clean_obj_tree_node);
for (i = 0; i < 5; i++)
iAVLFreeTree(dungeon[i], clean_obj_tree_node);
for (i = 0; i < 256; i++) {
if (actor_inventories[i]) {
delete actor_inventories[i];
}
}
}
bool ObjManager::load_basetile() {
Std::string filename;
NuvieIOFileRead basetile;
uint16 i;
config_get_path(config, "basetile", filename);
if (basetile.open(filename) == false)
return false;
for (i = 0; i < 1024; i++) {
obj_to_tile[i] = basetile.read2();
obj_stackable[i] = (uint8)tile_manager->tile_is_stackable(obj_to_tile[i]);
} // FIXME: tile_manager's tile_is_stackable is incorrect for (at least) Zu Ylem, silver snake venom.
return true;
}
bool ObjManager::load_weight_table() {
Std::string filename;
NuvieIOFileRead tileflag;
config_get_path(config, "tileflag", filename);
if (tileflag.open(filename) == false)
return false;
tileflag.seek(0x1000);
tileflag.readToBuf(obj_weight, 1024);
return true;
}
bool ObjManager::load_super_chunk(NuvieIO *chunk_buf, uint8 level, uint8 chunk_offset) {
NuvieIOFileRead file;
U6LList *list;
uint16 num_objs;
Obj *obj;
uint16 i;
U6LList *inventory_list;
iAVLTree *obj_tree;
if (level == 0)
obj_tree = surface[chunk_offset];
else
obj_tree = dungeon[level - 1];
list = new U6LList();
num_objs = chunk_buf->read2();
//DEBUG(0,LEVEL_DEBUGGING,"chunk %02d number of objects: %d\n", chunk_offset, num_objs);
for (i = 0; i < num_objs; i++) {
obj = loadObj(chunk_buf);
list->add(obj);
if (obj->obj_n == obj_egg_table[game_type]) {
egg_manager->add_egg(obj);
// set egg visibility
obj->set_invisible(Game::get_game()->are_cheats_enabled() ? !show_eggs : true);
}
if (usecode->is_container(obj)) { //object type is container, but may be empty
obj->make_container();
}
if (obj->get_engine_loc() == OBJ_LOC_INV || obj->get_engine_loc() == OBJ_LOC_READIED) { //triggered when object in actor's inventory OR equipped
//FIXME need to add to inventory properly!! eg set engine loc.
inventory_list = get_actor_inventory(obj->x);
inventory_list->add(obj);
} else {
if (obj->is_in_container()) { //object in container
addObjToContainer(list, obj);
} else {
add_obj(obj); // show remaining objects
/* if(show_eggs || obj->obj_n != obj_egg_table[game_type]) // show remaining objects, hiding eggs if neccecary.
{
add_obj(obj);
// print_obj(obj,false);
}*/
}
}
//print_obj(obj,false);
}
// Unused variable
(void)obj_tree;
delete list;
return true;
}
bool ObjManager::save_super_chunk(NuvieIO *save_buf, uint8 level, uint8 chunk_offset) {
iAVLTree *obj_tree;
ObjTreeNode *item;
U6Link *link;
iAVLCursor node;
uint32 start_pos;
uint32 finish_pos;
uint16 egg_type = obj_egg_table[game_type];
if (level == 0)
obj_tree = surface[chunk_offset];
else
obj_tree = dungeon[level - 1];
item = (ObjTreeNode *)iAVLFirst(&node, obj_tree);
start_pos = save_buf->position();
//skip the 2 bytes for number of objects.
save_buf->write2(0); // we'll fill this in later on.
obj_save_count = 0;
for (; item;) {
for (link = item->obj_list->end(); link != NULL; link = link->prev) {
if (((Obj *)link->data)->obj_n != egg_type) // we don't save eggs here. They are saved in save_eggs()
save_obj(save_buf, (Obj *)link->data, obj_save_count);
}
item = (ObjTreeNode *)iAVLNext(&node);
}
finish_pos = save_buf->position();
save_buf->seek(start_pos);
save_buf->write2(obj_save_count);
save_buf->seek(finish_pos);
return true;
}
bool ObjManager::save_eggs(NuvieIO *save_buf) {
uint32 start_pos;
uint32 finish_pos;
Std::list<Egg *> *egg_list;
Std::list<Egg *>::iterator egg;
start_pos = save_buf->position();
//skip number of objects we will fill that in at the end.
save_buf->write2(0);
egg_list = egg_manager->get_egg_list();
obj_save_count = 0;
for (egg = egg_list->begin(); egg != egg_list->end(); egg++)
save_obj(save_buf, (*egg)->obj, obj_save_count);
finish_pos = save_buf->position();
save_buf->seek(start_pos);
save_buf->write2(obj_save_count);
save_buf->seek(finish_pos);
DEBUG(0, LEVEL_DEBUGGING, "Eggs: %d\n", obj_save_count);
return true;
}
bool ObjManager::save_inventories(NuvieIO *save_buf) {
uint32 start_pos;
uint32 finish_pos;
U6Link *link;
uint16 i;
start_pos = save_buf->position();
save_buf->write2(0);
obj_save_count = 0;
for (i = 0; i < 256; i++) {
if (actor_inventories[i] != NULL) {
for (link = actor_inventories[i]->start(); link != NULL; link = link->next) {
save_obj(save_buf, (Obj *)link->data, obj_save_count);
}
}
}
DEBUG(0, LEVEL_DEBUGGING, "Actor Inventories: %d\n", obj_save_count);
finish_pos = save_buf->position();
save_buf->seek(start_pos);
save_buf->write2(obj_save_count);
save_buf->seek(finish_pos);
return true;
}
bool ObjManager::save_obj(NuvieIO *save_buf, Obj *obj, uint16 parent_objblk_n) {
uint8 b;
U6Link *link;
uint16 objblk_n;
if (obj->is_in_container()) { //obj is in a container
//obj->in_container(); // in container
obj->x = parent_objblk_n & 0x3ff; //save 10bits in x
obj->y &= 0xffc0; //clear lower 6 bits
obj->y |= (parent_objblk_n >> 10); //save top 6bits
} else {
if (!obj->is_readied()) {
obj->status &= (0xff ^ OBJ_STATUS_IN_CONTAINER);
}
}
if (obj->is_in_inventory(OBJ_DONT_CHECK_PARENT))
obj->x = obj->get_actor_holding_obj()->get_actor_num();
//set original status location bits.
obj->status &= OBJ_STATUS_MASK_SET;
switch (obj->get_engine_loc()) {
case OBJ_LOC_MAP :
obj->status |= OBJ_STATUS_ON_MAP;
break;
case OBJ_LOC_CONT :
obj->status |= OBJ_STATUS_IN_CONTAINER;
break;
case OBJ_LOC_INV :
obj->status |= OBJ_STATUS_IN_INVENTORY;
break;
case OBJ_LOC_READIED :
obj->status |= OBJ_STATUS_READIED;
break;
}
save_buf->write1(obj->status);
save_buf->write1(obj->x & 0xff);
b = obj->x >> 8;
b += obj->y << 2;
save_buf->write1(b);
b = obj->y >> 6;
b += obj->z << 4;
save_buf->write1(b);
save_buf->write1(obj->obj_n & 0xff);
b = obj->obj_n >> 8;
b += obj->frame_n << 2;
save_buf->write1(b);
save_buf->write1((uint8)(obj->qty & 0xff)); //only save the lower byte to disk.
if (is_stackable(obj))
save_buf->write1(obj->qty >> 8);
else
save_buf->write1(obj->quality);
objblk_n = obj_save_count;
obj_save_count += 1;
if (obj->container) {
for (link = obj->container->end(); link != NULL; link = link->prev)
save_obj(save_buf, (Obj *)link->data, objblk_n);
}
return true;
}
void ObjManager::clean() {
uint8 i;
egg_manager->clean(Game::get_game()->are_cheats_enabled() ? show_eggs : false); //show_eggs determines wether we delete the actual Objs from egg manager.
for (i = 0; i < 64; i++)
iAVLCleanTree(surface[i], clean_obj_tree_node);
for (i = 0; i < 5; i++)
iAVLCleanTree(dungeon[i], clean_obj_tree_node);
clean_actor_inventories();
// remove the temporary object list. The objects were deleted from the surface and dungeon trees.
temp_obj_list.clear();
for (Std::list<Obj *>::iterator it = tile_obj_list.begin(); it != tile_obj_list.end(); ++it) {
delete *it;
}
tile_obj_list.clear();
return;
}
void ObjManager::clean_actor_inventories() {
U6Link *link;
uint16 i;
for (i = 0; i < 256; i++) {
if (actor_inventories[i]) {
for (link = actor_inventories[i]->start(); link != NULL;) {
Obj *obj = (Obj *)link->data;
link = link->next;
delete_obj(obj);
}
actor_inventories[i]->removeAll();
}
}
return;
}
/*
U6LList *ObjManager::get_obj_superchunk(uint16 x, uint16 y, uint8 level)
{
uint16 i;
if(level == 0)
{
i = y * 8 + x;
return surface[i];
}
return dungeon[level-1];
}
*/
bool ObjManager::is_boundary(uint16 x, uint16 y, uint8 level, uint8 boundary_type, Obj *excluded_obj) {
U6Link *link;
U6LList *obj_list;
Obj *obj;
Tile *tile, *tile1;
uint16 tile_num;
bool check_tile;
uint16 i, j;
uint16 next_x, next_y;
next_x = WRAPPED_COORD(x + 1, level);
next_y = WRAPPED_COORD(y + 1, level);
for (j = y; j <= y + 1; j++) {
for (i = x; i <= x + 1; i++) {
obj_list = get_obj_list(WRAPPED_COORD(i, level), WRAPPED_COORD(j, level), level);
if (obj_list != NULL) {
link = obj_list->end();
for (check_tile = false; link != NULL; link = link->prev) {
obj = (Obj *)link->data;
if (obj == excluded_obj)
continue;
tile_num = get_obj_tile_num(obj->obj_n) + obj->frame_n;
tile = tile_manager->get_original_tile(tile_num);
if (obj->x == x && obj->y == y) {
check_tile = true;
}
if (tile->dbl_width && obj->x == next_x && obj->y == y) {
tile_num--;
check_tile = true;
}
if (tile->dbl_height && obj->x == x && obj->y == next_y) {
tile_num--;
check_tile = true;
}
if (obj->x == next_x && obj->y == next_y && tile->dbl_width && tile->dbl_height) {
tile_num -= 2;
check_tile = true;
}
if (check_tile) {
tile1 = tile_manager->get_tile(tile_num);
if (tile1->flags2 & boundary_type) //either TILEFLAG_BOUNDARY or TILEFLAG_MISSILE_BOUNDARY
return true;
check_tile = false;
}
}
}
}
}
return false;
}
/* no longer needed.
//FIX this needs to be moved magicnumbers :(
bool ObjManager::is_door(Obj * obj)
{
//for U6
if((obj->obj_n >= 297 && obj->obj_n <= 300) || obj->obj_n == 334 || obj->obj_n == 213) //OBJ_U6_MOUSEHOLE)
return true;
return false;
}
*/
uint8 ObjManager::is_passable(uint16 x, uint16 y, uint8 level) {
U6Link *link;
U6LList *obj_list;
Obj *obj;
Tile *tile, *tile1;
uint16 tile_num;
bool check_tile;
bool object_at_location = false;
uint16 i, j;
uint16 x2 = WRAPPED_COORD((x + 1), level); // wrap on map edge
uint16 y2 = WRAPPED_COORD((y + 1), level);
for (i = x;; i = x2) { // only checks x and x2
for (j = y;; j = y2) { // only checks y and y2
obj_list = get_obj_list(i, j, level);
if (i == x && j == y && obj_list) {
if (obj_list->end() != NULL)
object_at_location = true;
}
if (obj_list != NULL) {
link = obj_list->end();
for (check_tile = false; link != NULL; link = link->prev) {
obj = (Obj *)link->data;
tile_num = get_obj_tile_num(obj->obj_n) + obj->frame_n;
tile = tile_manager->get_original_tile(tile_num);
if (obj->x == x && obj->y == y) {
check_tile = true;
}
if (tile->dbl_width && obj->x == x2 && obj->y == y) {
tile_num--;
check_tile = true;
}
if (tile->dbl_height && obj->x == x && obj->y == y2) {
tile_num--;
check_tile = true;
}
if (obj->x == x2 && obj->y == y2 && tile->dbl_width && tile->dbl_height) {
tile_num -= 3;
check_tile = true;
}
if (check_tile) {
tile1 = tile_manager->get_original_tile(tile_num);
if (tile1->passable == false)
return OBJ_NOT_PASSABLE;
check_tile = false;
}
}
}
if (j == y) j = y2;
else break;
}
if (i == x) i = x2;
else break;
}
if (object_at_location)
return OBJ_PASSABLE;
return OBJ_NO_OBJ;
}
bool ObjManager::is_forced_passable(uint16 x, uint16 y, uint8 level) {
U6LList *obj_list;
U6Link *link;
Obj *obj;
Tile *tile;
obj_list = get_obj_list(x, y, level);
if (obj_list) {
for (link = obj_list->start(); link != NULL; link = link->next) {
obj = (Obj *)link->data;
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->flags3 & TILEFLAG_FORCED_PASSABLE)
return true;
}
}
return false;
}
bool ObjManager::is_door(uint16 x, uint16 y, uint8 level) {
U6LList *obj_list = get_obj_list(x, y, level);
U6Link *link;
Obj *obj;
if (obj_list) {
for (link = obj_list->start(); link != NULL; link = link->next) {
obj = (Obj *)link->data;
if (usecode->is_door(obj))
return true;
}
}
return false;
}
bool ObjManager::is_damaging(uint16 x, uint16 y, uint8 level) {
U6LList *obj_list;
U6Link *link;
Obj *obj;
Tile *tile;
obj_list = get_obj_list(x, y, level);
if (obj_list) {
for (link = obj_list->start(); link != NULL; link = link->next) {
obj = (Obj *)link->data;
tile = tile_manager->get_original_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n); //get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n);
if (tile->flags1 & TILEFLAG_DAMAGING)
return true;
}
}
return false;
}
bool ObjManager::is_stackable(Obj *obj) {
// Tile *tile;
if (obj == NULL)
return false;
if (obj->is_readied()) // readied objects cannot be stacked --SB-X
return false;
/*
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n);
if(tile_manager->tile_is_stackable(tile->tile_num))
return true;
return false;
*/
if (game_type == NUVIE_GAME_U6) {
switch (obj->obj_n) {
case OBJ_U6_TORCH: // 0x5A, // torch
if (obj->frame_n == 1) {
return false;
} else {
return true;
}
case OBJ_U6_LOCK_PICK: // 0x3F, // lock pick
case OBJ_U6_GEM: // 0x4D, // gem
case OBJ_U6_ARROW: // 0x37, // arrow
case OBJ_U6_BOLT: // 0x38, // bolt
case OBJ_U6_BLACK_PEARL: // 0x41, // black pearl
case OBJ_U6_BLOOD_MOSS: // 0x42, // bit of blood moss
case OBJ_U6_GARLIC: // 0x43, // bulb of garlic
case OBJ_U6_GINSENG: // 0x44, // ginseng root
case OBJ_U6_MANDRAKE_ROOT: // 0x45, // mandrake root
case OBJ_U6_NIGHTSHADE: // 0x46, // nightshade mushroom
case OBJ_U6_SPIDER_SILK: // 0x47, // strand of spidersilk
case OBJ_U6_SULFUROUS_ASH: // 0x48, // bit of sulfurous ash
case OBJ_U6_EFFECT: // 0x151, // effect
case OBJ_U6_BREAD: // 0x80, // loaf of bread
case OBJ_U6_MEAT_PORTION: // 0x81, // portion of meat
case OBJ_U6_FLASK_OF_OIL: // 0x53, // flask of oil
case OBJ_U6_EGG: // 0x14F, // egg
case OBJ_U6_GOLD_NUGGET: // 0x59, // gold nugget
case OBJ_U6_ZU_YLEM: // 0x5B, // Zu Ylem
case OBJ_U6_SNAKE_VENOM: // 0x5C, // silver snake venom
case OBJ_U6_GOLD: // 0x58 // Gold coin
return true;
default:
return false;
}
}
if (game_type == NUVIE_GAME_SE) {
switch (obj->obj_n) {
case OBJ_SE_MAGNESIUM_RIBBON:
case OBJ_SE_SPEAR:
case OBJ_SE_THROWING_AXE:
case OBJ_SE_POISONED_DART:
case OBJ_SE_RIFLE_BULLET:
case OBJ_SE_KNIFE:
case OBJ_SE_ARROW:
case OBJ_SE_TURTLE_BAIT:
case OBJ_SE_FEATHER:
case OBJ_SE_CHOCOLATL:
case OBJ_SE_PINDE:
case OBJ_SE_YOPO:
case OBJ_SE_GOLD:
case OBJ_SE_GOLD_NUGGET:
case OBJ_SE_DIAMOND:
case OBJ_SE_EMERALD:
case OBJ_SE_RUBY:
case OBJ_SE_CORN_MEAL:
case OBJ_SE_TORTILLA:
case OBJ_SE_MEAT_103:
case OBJ_SE_BERRY:
case OBJ_SE_CAKE:
case OBJ_SE_CORN:
case OBJ_SE_BEAN:
case OBJ_SE_MEAT_110:
case OBJ_SE_ORCHID:
case OBJ_SE_PEPPER:
case OBJ_SE_SULFUR:
case OBJ_SE_CHARCOAL:
case OBJ_SE_POTASSIUM_NITRATE:
case OBJ_SE_SOFT_CLAY_POT:
case OBJ_SE_FIRED_CLAY_POT:
case OBJ_SE_CLOTH_STRIP:
case OBJ_SE_GRENADE:
case OBJ_SE_TAR:
case OBJ_SE_WATER:
case OBJ_SE_CLOTH:
case OBJ_SE_TARRED_CLOTH_STRIP:
case OBJ_SE_CLAY:
case OBJ_SE_GUNPOWDER:
case OBJ_SE_BRANCH:
case OBJ_SE_TORCH:
case OBJ_SE_FLAX:
case OBJ_SE_RIB_BONE:
case OBJ_SE_CHOP:
case OBJ_SE_DEVICE:
return true;
default:
return false;
}
}
if (game_type == NUVIE_GAME_MD) {
switch (obj->obj_n) {
case OBJ_MD_PISTOL_ROUND:
case OBJ_MD_SHOTGUN_SHELL:
case OBJ_MD_RIFLE_ROUND:
case OBJ_MD_ELEPHANT_GUN_ROUND:
case OBJ_MD_SLING_STONE:
case OBJ_MD_ARROW:
case OBJ_MD_CAN_OF_LAMP_OIL:
case OBJ_MD_MATCH:
case OBJ_MD_TORCH:
case OBJ_MD_BLOB_OF_OXIUM:
case OBJ_MD_BERRY:
case OBJ_MD_BERRY1:
case OBJ_MD_BERRY2:
case OBJ_MD_BERRY4:
case OBJ_MD_CHIP_OF_RADIUM:
case OBJ_MD_DOLLAR:
case OBJ_MD_RUBLE:
case OBJ_MD_WORMSBANE_SEED:
case OBJ_MD_PAGE:
case OBJ_MD_BERRY3:
case OBJ_MD_OXYGENATED_AIR_BOTTLE:
return true;
default:
return false;
}
}
return (bool)obj_stackable[obj->obj_n];
}
bool ObjManager::is_breakable(Obj *obj) {
if (game_type == NUVIE_GAME_U6) {
switch (obj->obj_n) {
case OBJ_U6_FLASK_OF_OIL:
case OBJ_U6_SNAKE_VENOM:
case OBJ_U6_CRYSTAL_BALL:
case OBJ_U6_MIRROR:
case OBJ_U6_WINE:
case OBJ_U6_MEAD:
case OBJ_U6_ALE:
case OBJ_U6_WINE_GLASS:
case OBJ_U6_PLATE:
case OBJ_U6_MUG:
case OBJ_U6_HONEY_JAR:
case OBJ_U6_JAR_OF_HONEY:
case OBJ_U6_POTION:
case OBJ_U6_WATER_VASE:
case OBJ_U6_DRAGON_EGG:
return true;
default:
break;
}
} else if (game_type == NUVIE_GAME_SE) {
switch (obj->obj_n) {
case OBJ_SE_MORTAR:
case OBJ_SE_GRINDING_STONE:
case OBJ_SE_JUG_OF_PLACHTA:
case OBJ_SE_BOTTLE_OF_LIQUOR:
case OBJ_SE_JAR:
case OBJ_SE_FIRED_CLAY_POT:
case OBJ_SE_GRENADE:
case OBJ_SE_JUG:
case OBJ_SE_POT:
return true;
default:
break;
}
}
return false;
}
bool ObjManager::can_store_obj(Obj *target, Obj *src) {
if (target == src || !can_get_obj(src) || target == NULL)
return false;
if (game_type == NUVIE_GAME_U6) {
if (src->obj_n == OBJ_U6_TRAP)
return false;
if (target->obj_n == OBJ_U6_BAG
|| target->obj_n == OBJ_U6_BACKPACK
|| target->obj_n == OBJ_U6_BASKET
|| (target->obj_n == OBJ_U6_CRATE && target->frame_n == 0)
|| (target->obj_n == OBJ_U6_BARREL && target->frame_n == 0)
|| (target->obj_n == OBJ_U6_CHEST && target->frame_n == 0)
|| (target->obj_n == OBJ_U6_SPELLBOOK && src->obj_n == OBJ_U6_SPELL
&& !target->find_in_container(OBJ_U6_SPELL, src->quality)
&& !target->find_in_container(OBJ_U6_SPELL, 255)) // this quality contains all spells
|| (target->obj_n == OBJ_U6_VORTEX_CUBE && src->obj_n == OBJ_U6_MOONSTONE))
return true;
if ((target->is_in_inventory() || Game::get_game()->doubleclick_opens_containers())
&& ((target->obj_n == OBJ_U6_CHEST && target->frame_n == 1)
|| target->obj_n == OBJ_U6_DEAD_BODY
|| target->obj_n == OBJ_U6_MOUSE
|| target->obj_n == OBJ_U6_REMAINS
|| target->obj_n == OBJ_U6_DRAKE
|| target->obj_n == OBJ_U6_MONGBAT))
return true;
if (Game::get_game()->doubleclick_opens_containers()
&& (target->obj_n == OBJ_U6_DESK
|| target->obj_n == OBJ_U6_DRAWER
|| target->obj_n == OBJ_U6_GRAVE
|| target->obj_n == OBJ_U6_REAPER
|| target->obj_n == OBJ_U6_DEAD_GARGOYLE
|| target->obj_n == OBJ_U6_DEAD_CYCLOPS))
return true;
} else if (game_type == NUVIE_GAME_SE) {
if (src->has_container() || usecode->is_container(src))
return false;
if (target->obj_n == OBJ_SE_JUG || target->obj_n == OBJ_SE_POUCH
|| target->obj_n == OBJ_SE_BASKET || target->obj_n == OBJ_SE_POT)
return true;
if (target->obj_n == OBJ_SE_MORTAR || target->obj_n == OBJ_SE_GRINDING_STONE
|| target->obj_n == OBJ_SE_JAR) {
switch (src->obj_n) {
case OBJ_SE_MAGNESIUM_RIBBON:
case OBJ_SE_CHOCOLATL:
case OBJ_SE_PINDE:
case OBJ_SE_YOPO:
case OBJ_SE_CORN_MEAL:
case OBJ_SE_CORN:
case OBJ_SE_SULFUR:
case OBJ_SE_CHARCOAL:
case OBJ_SE_POTASSIUM_NITRATE:
case OBJ_SE_GUNPOWDER:
if (target->obj_n == OBJ_SE_JAR) {
if (target->container_count_objects() == 0 || // only allow one object
target->find_in_container(src->obj_n, src->quality))
return true;
else
return false;
}
return true;
default:
return false;
}
}
} else { // MD
if (src->has_container() || usecode->is_container(src))
return false;
switch (target->obj_n) {
case OBJ_MD_BRASS_CHEST:
case OBJ_MD_OBSIDIAN_BOX:
case OBJ_MD_WOODEN_CRATE:
case OBJ_MD_STEAMER_TRUNK:
case OBJ_MD_BARREL:
case OBJ_MD_CRATE:
case OBJ_MD_BRASS_TRUNK:
if (target->frame_n == 0) {
return true;
} else
return false;
case OBJ_MD_BACKPACK:
case OBJ_MD_LARGE_SACK:
case OBJ_MD_SMALL_POUCH:
case OBJ_MD_CARPET_BAG:
case OBJ_MD_BAG:
case OBJ_MD_LEAD_BOX:
return true;
default:
return false;
}
}
return false;
}
bool ObjManager::can_get_obj(Obj *obj) {
// objects with 0 weight aren't gettable.
//255 is the max weight and means an object is movable but not getable.
//we can't get object that contains toptiles either. This makes dragon bits ungettable etc.
// excluding container items here, we just want the object itself to
// check if it weighs 0 or 255. no need to scale as we don't compare
// with other weights
if (obj == NULL)
return false;
if (Game::get_game()->get_script()->call_can_get_obj_override(obj))
return true;
float weight = get_obj_weight(obj, OBJ_WEIGHT_EXCLUDE_CONTAINER_ITEMS, OBJ_WEIGHT_DONT_SCALE, OBJ_WEIGHT_EXCLUDE_QTY);
if ((weight != 0 && weight != 255 && has_toptile(obj) == false
&& (!obj->is_on_map() || !Game::get_game()->get_map_window()->tile_is_black(obj->x, obj->y, obj)))
|| Game::get_game()->using_hackmove())
return true;
return false;
}
bool ObjManager::has_reduced_weight(uint16 obj_n) {
// FIXME: HERE BE HARDCODED VALUES! FIXME: not sure if this list is complete!
if (game_type == NUVIE_GAME_U6) { // luteijn: I only know about U6...
if ((obj_n == OBJ_U6_GOLD)
|| (obj_n == OBJ_U6_BLACK_PEARL) // not using range because don't want to depend on underlying magic numbers relations
|| (obj_n == OBJ_U6_BLOOD_MOSS)
|| (obj_n == OBJ_U6_GARLIC)
|| (obj_n == OBJ_U6_GINSENG)
|| (obj_n == OBJ_U6_MANDRAKE_ROOT)
|| (obj_n == OBJ_U6_NIGHTSHADE)
|| (obj_n == OBJ_U6_SPIDER_SILK)
|| (obj_n == OBJ_U6_SULFUROUS_ASH)
) {
return true;
}
} else if (game_type == NUVIE_GAME_SE) {
switch (obj_n) {
case OBJ_SE_RIFLE_BULLET:
case OBJ_SE_FEATHER:
case OBJ_SE_CHOCOLATL:
case OBJ_SE_PINDE:
case OBJ_SE_YOPO:
case OBJ_SE_GOLD:
case OBJ_SE_DIAMOND:
case OBJ_SE_EMERALD:
case OBJ_SE_RUBY:
case OBJ_SE_PEPPER:
case OBJ_SE_SULFUR:
case OBJ_SE_CHARCOAL:
case OBJ_SE_POTASSIUM_NITRATE:
case OBJ_SE_CLOTH_STRIP:
return true;
default:
return false;
}
} else if (game_type == NUVIE_GAME_MD) {
switch (obj_n) {
case OBJ_MD_PISTOL_ROUND:
case OBJ_MD_SHOTGUN_SHELL:
case OBJ_MD_RIFLE_ROUND:
case OBJ_MD_ELEPHANT_GUN_ROUND:
case OBJ_MD_SLING_STONE:
case OBJ_MD_ARROW:
case OBJ_MD_POCKETWATCH:
case OBJ_MD_SPECTACLES:
case OBJ_MD_MASONIC_SYMBOL:
case OBJ_MD_MATCH:
case OBJ_MD_BLOB_OF_OXIUM:
case OBJ_MD_BERRY:
case OBJ_MD_BERRY1:
case OBJ_MD_BERRY2:
case OBJ_MD_BERRY4:
case OBJ_MD_DREAMSTUFF:
case OBJ_MD_DOLLAR:
case OBJ_MD_RUBLE:
return true;
default:
return false;
}
}
return false;
}
bool ObjManager::has_toptile(Obj *obj) {
Tile *tile;
uint8 i = 1;
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_width)
i++;
if (tile->dbl_height)
i++;
if (tile->dbl_width && tile->dbl_height)
i++;
for (; i > 0; i--) {
if (tile->toptile)
return true;
if (i != 1)
tile = tile_manager->get_tile(tile->tile_num - 1);
}
return false;
}
//gets the linked list of objects at a particular location.
U6LList *ObjManager::get_obj_list(uint16 x, uint16 y, uint8 level) {
iAVLTree *obj_tree;
iAVLKey key;
ObjTreeNode *item;
WRAP_COORD(x, level); // wrap on map edge
WRAP_COORD(y, level);
obj_tree = get_obj_tree(x, y, level);
key = get_obj_tree_key(x, y, level);
item = (ObjTreeNode *)iAVLSearch(obj_tree, key);
if (item)
return item->obj_list;
return NULL;
}
Tile *ObjManager::get_obj_tile(uint16 obj_n, uint8 frame_n) {
return tile_manager->get_tile(get_obj_tile_num(obj_n) + frame_n);
}
Tile *ObjManager::get_obj_tile(uint16 x, uint16 y, uint8 level, bool top_obj) {
Obj *obj;
Tile *tile;
uint16 tile_num;
obj = get_obj(x, y, level, top_obj);
if (obj == NULL)
return NULL;
tile_num = get_obj_tile_num(obj->obj_n) + obj->frame_n;
tile = tile_manager->get_tile(tile_num);
if (tile->dbl_width && obj->x == x + 1 && obj->y == y)
tile_num--;
if (tile->dbl_height && obj->x == x && obj->y == y + 1)
tile_num--;
if (obj->x == x + 1 && obj->y == y + 1 && tile->dbl_width && tile->dbl_height)
tile_num -= 2;
return tile_manager->get_original_tile(tile_num);
}
Tile *ObjManager::get_obj_dmg_tile(uint16 x, uint16 y, uint8 level) {
Tile *tile;
U6LList *obj_list;
U6Link *link;
Obj *obj = NULL;
obj_list = get_obj_list(x, y, level);
if (obj_list != NULL) {
for (link = obj_list->end(); link != NULL; link = link->prev) {
obj = (Obj *)link->data;
tile = tile_manager->get_original_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->damages == true)
return tile;
}
}
return NULL;
}
bool ObjManager::obj_is_damaging(Obj *obj, Actor *actor) {
if (!obj)
return false;
Tile *tile = tile_manager->get_original_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile && tile->damages == true) {
if (actor) {
MsgScroll *scroll = Game::get_game()->get_scroll();
scroll->display_string("\n\nNot possible\n");
Game::get_game()->get_script()->call_actor_tile_dmg(actor, tile->tile_num);
actor->display_condition(); // indicate that object hurt the player
scroll->display_string("\n");
scroll->display_prompt();
}
return true;
} else
return false;
}
Obj *ObjManager::get_obj(uint16 x, uint16 y, uint8 level, bool top_obj, bool include_ignored_objects, Obj *excluded_obj) {
Obj *obj;
Tile *tile;
obj = get_objBasedAt(x, y, level, top_obj, include_ignored_objects, excluded_obj);
if (obj != NULL)
return obj;
obj = get_objBasedAt(x + 1, y + 1, level, top_obj, include_ignored_objects, excluded_obj);
if (obj != NULL) {
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_width && tile->dbl_height)
return obj;
}
obj = get_objBasedAt(x, y + 1, level, top_obj, include_ignored_objects, excluded_obj);
if (obj != NULL) {
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_height)
return obj;
}
obj = get_objBasedAt(x + 1, y, level, top_obj, include_ignored_objects, excluded_obj);
if (obj != NULL) {
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_width)
return obj;
}
return NULL;
}
Obj *ObjManager::get_obj_of_type_from_location_inc_multi_tile(uint16 obj_n, uint16 x, uint16 y, uint8 z) {
return get_obj_of_type_from_location_inc_multi_tile(obj_n, -1, -1, x, y, z);
}
Obj *ObjManager::get_obj_of_type_from_location_inc_multi_tile(uint16 obj_n, sint16 quality, sint32 qty, uint16 x, uint16 y, uint8 z) {
Obj *obj;
Tile *tile;
obj = get_obj_of_type_from_location(obj_n, quality, qty, x, y, z);
if (obj != NULL)
return obj;
obj = get_obj_of_type_from_location(obj_n, quality, qty, x + 1, y + 1, z);
if (obj != NULL) {
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_width && tile->dbl_height)
return obj;
}
obj = get_obj_of_type_from_location(obj_n, quality, qty, x, y + 1, z);
if (obj != NULL) {
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_height)
return obj;
}
obj = get_obj_of_type_from_location(obj_n, quality, qty, x + 1, y, z);
if (obj != NULL) {
tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n) + obj->frame_n);
if (tile->dbl_width)
return obj;
}
return NULL;
}
Obj *ObjManager::get_obj_of_type_from_location(uint16 obj_n, uint16 x, uint16 y, uint8 z) {
return get_obj_of_type_from_location(obj_n, -1, -1, x, y, z);
}
Obj *ObjManager::get_obj_of_type_from_location(uint16 obj_n, sint16 quality, sint32 qty, uint16 x, uint16 y, uint8 z) {
U6LList *obj_list;
U6Link *link;
Obj *obj;
obj_list = get_obj_list(x, y, z);
if (obj_list == NULL)
return NULL;
// start from the top of the stack
for (link = obj_list->end(); link != NULL; link = link->prev) {
obj = (Obj *)link->data;
if (obj->obj_n == obj_n) {
if (quality != -1 && obj->quality != (uint8)quality)
continue;
if (qty != -1 && obj->qty != (uint16)qty)
continue;
return obj;
}
}
return NULL;
}
// x, y in world coords
Obj *ObjManager::get_objBasedAt(uint16 x, uint16 y, uint8 level, bool top_obj, bool include_ignored_objects, Obj *excluded_obj) {
U6Link *link;
U6LList *obj_list;
Obj *obj;
obj_list = get_obj_list(x, y, level);
if (obj_list != NULL) {
if (top_obj)
link = obj_list->end();
else
link = obj_list->start();
while (link != NULL) {
obj = (Obj *)link->data;
if (obj != excluded_obj) {
if (include_ignored_objects)
return obj;
Tile *tile = get_obj_tile(obj->obj_n, obj->frame_n);
if ((tile->flags3 & TILEFLAG_IGNORE) != TILEFLAG_IGNORE)
return obj;
}
if (top_obj)
link = link->prev;
else
link = link->next;
}
}
return NULL;
}
// ObjManager keeps one instance of tile_obj per object.
// SE has 3 tile objects (Trees, Yucca Plants, and Oven Fires)
Obj *ObjManager::get_tile_obj(uint16 obj_n) {
for (Std::list<Obj *>::iterator it = tile_obj_list.begin(); it != tile_obj_list.end(); ++it) {
if ((*it)->obj_n == obj_n) {
return *it;
}
}
Obj *obj = new Obj();
obj->obj_n = obj_n;
obj->set_on_map(NULL);
tile_obj_list.push_back(obj);
return obj;
}
/*
bool ObjManager::add_obj(Obj *obj, bool addOnTop)
{
return add_obj(get_obj_tree(obj->x,obj->y,obj->z), obj, addOnTop);
}
*/
bool ObjManager::remove_obj_from_map(Obj *obj) {
U6LList *obj_list;
if (obj->get_engine_loc() != OBJ_LOC_MAP)
return false;
obj_list = (U6LList *)obj->parent;
if (obj_list == NULL)
return false;
obj_list->remove(obj);
remove_obj(obj);
return true;
}
void ObjManager::remove_obj(Obj *obj) {
if (obj->status & OBJ_STATUS_TEMPORARY)
temp_obj_list_remove(obj);
if (obj->obj_n == obj_egg_table[game_type]) {
egg_manager->remove_egg(obj);
}
obj->set_noloc();
return;
}
// remove all objects of type obj_n from location (x,y,z)
bool ObjManager::remove_obj_type_from_location(uint16 obj_n, uint16 x, uint16 y, uint8 z) {
U6LList *obj_list;
U6Link *link;
Obj *obj;
bool objects_deleted = false;
obj_list = get_obj_list(x, y, z);
if (obj_list != NULL) {
for (link = obj_list->start(); link != NULL;) {
obj = (Obj *)link->data;
link = link->next;
if (obj->obj_n == obj_n) {
remove_obj_from_map(obj);
delete_obj(obj);
objects_deleted = true;
}
}
}
return objects_deleted;
}
Obj *ObjManager::copy_obj(Obj *obj) {
Obj *new_obj;
if (obj == NULL)
return NULL;
new_obj = new Obj(*obj);
/* changed to direct copy in case we add new members to Obj --SB-X
new_obj->obj_n = obj->obj_n;
new_obj->frame_n = obj->frame_n;
new_obj->status = obj->status;
new_obj->qty = obj->qty;
new_obj->quality = obj->quality;
new_obj->x = obj->x;
new_obj->y = obj->y;
new_obj->z = obj->z;*/
// should we copy container???
new_obj->container = 0;
return new_obj;
}
bool ObjManager::move(Obj *obj, uint16 x, uint16 y, uint8 level) {
if (remove_obj_from_map(obj) == false)
return false;
obj->x = x;
obj->y = y;
obj->z = level;
add_obj(obj, true); // add the object on top of the stack
return true;
}
/* Returns an objects look-string, its general description.
*/
const char *ObjManager::look_obj(Obj *obj, bool show_prefix) {
const char *desc;
if (obj == NULL)
return NULL;
desc = tile_manager->lookAtTile(get_obj_tile_num(obj) + obj->frame_n, obj->qty, show_prefix);
return desc;
}
const char *ObjManager::get_obj_name(Obj *obj) {
return tile_manager->lookAtTile(get_obj_tile_num(obj->obj_n), 0, false);
}
const char *ObjManager::get_obj_name(uint16 obj_n) {
return tile_manager->lookAtTile(get_obj_tile_num(obj_n), 0, false);
}
const char *ObjManager::get_obj_name(uint16 obj_n, uint8 frame_n) {
return tile_manager->lookAtTile(get_obj_tile_num(obj_n) + frame_n, 0, false);
}
float ObjManager::get_obj_weight(uint16 obj_n) {
float weight = (float)get_obj_weight_unscaled(obj_n);
if (has_reduced_weight(obj_n)) {
weight /= 10;
}
return weight / 10;
}
float ObjManager::get_obj_weight(Obj *obj, bool include_container_items, bool scale, bool include_qty) {
float weight;
U6Link *link;
weight = obj_weight[obj->obj_n];
if (is_stackable(obj)) {
if (include_qty) {
if (obj->qty == 0)
obj->qty = 1;
weight *= obj->qty;
}
/* luteijn: only some need to be divided by an extra 10 for a total of 100.
* unfortunately can't seem to find a tileflag that controls this so would have to be hardcoded!
*/
if (has_reduced_weight(obj)) {
weight /= 10; // luteijn: regardless of the scaling flag!
}
}
if (obj->container != NULL && include_container_items == OBJ_WEIGHT_INCLUDE_CONTAINER_ITEMS) {
for (link = obj->container->start(); link != NULL; link = link->next)
/* weight += get_obj_weight(reinterpret_cast<Obj*>(link->data), false);*/ //don't scale container objects yet.
weight += get_obj_weight(reinterpret_cast<Obj *>(link->data), OBJ_WEIGHT_INCLUDE_CONTAINER_ITEMS, OBJ_WEIGHT_DONT_SCALE); //don't scale container objects yet. luteijn: and use the right flag to do so!
}
if (scale == OBJ_WEIGHT_DO_SCALE) {
weight /= 10;
}
return weight;
}
uint16 ObjManager::get_obj_tile_num(uint16 obj_num) { //assume obj_num is < 1024 :)
return obj_to_tile[obj_num];
}
inline bool ObjManager::is_corpse(Obj *obj) {
if (game_type == NUVIE_GAME_U6) {
switch (obj->obj_n) {
case OBJ_U6_DEAD_BODY:
case OBJ_U6_DEAD_CYCLOPS:
case OBJ_U6_DEAD_GARGOYLE:
case OBJ_U6_DOG: // Kador id_n 135
case OBJ_U6_MOUSE: // Sherry id_n 9
case OBJ_U6_HORSE_CARCASS: // Pushme Pullyu id 130, Smith id 132
return true;
default:
break;
}
} else if (game_type == NUVIE_GAME_SE) {
/* TODO - add SE body obj numbers
switch (obj->obj_n) {
default:
break;
}
*/
} else { // MD
/* TODO - add MD body obj numbers
switch (obj->obj_n) {
default:
break;
}
*/
}
return false;
}
uint16 ObjManager::get_obj_tile_num(Obj *obj) { //assume obj_num is < 1024 :)
if (custom_actor_tiles && is_corpse(obj)) {
return Game::get_game()->get_actor_manager()->get_actor(obj->quality)->get_custom_tile_num(obj->obj_n);
}
uint16 obj_num = obj->obj_n;
// Savage Empire Tile Object (Get Tile from Map Location)
if (game_type == NUVIE_GAME_SE &&
Game::get_game()->get_script()->call_is_tile_object(obj_num)) {
return (Game::get_game()->get_game_map()->get_tile(obj->x, obj->y, obj->z)->tile_num);
}
return get_obj_tile_num(obj_num);
}
void ObjManager::set_obj_tile_num(uint16 obj_num, uint16 tile_num) {
obj_to_tile[obj_num] = tile_num;
return;
}
/* Animate all visible tiles of an object `loop_count' times. */
void ObjManager::animate_forwards(Obj *obj, uint32 loop_count) {
// In U6 there is no place where one object must animate and nearby objects
// of the same type don't also animate, so just forward to TileManager.
tile_manager->set_anim_loop(get_obj_tile_num(obj->obj_n), loop_count, 0);
}
/* Animate in reverse all visible tiles of an object `loop_count' times. */
void ObjManager::animate_backwards(Obj *obj, uint32 loop_count) {
tile_manager->set_anim_loop(get_obj_tile_num(obj->obj_n), loop_count, 1);
}
U6LList *ObjManager::get_actor_inventory(uint16 actor_num) {
if (actor_num >= 256)
return NULL;
if (actor_inventories[actor_num] == NULL) {
actor_inventories[actor_num] = new U6LList();
}
return actor_inventories[actor_num];
}
bool ObjManager::actor_has_inventory(uint16 actor_num) {
if (actor_inventories[actor_num] != NULL) {
if (actor_inventories[actor_num]->start() != NULL)
return true;
}
return false;
}
Obj *ObjManager::find_next_obj(uint8 level, Obj *prev_obj, bool match_frame_n, bool match_quality) {
if (prev_obj == NULL)
return NULL;
Obj **p = &prev_obj;
return find_obj(level, prev_obj->obj_n, prev_obj->quality, match_quality, prev_obj->frame_n, match_frame_n, p);
}
Obj *ObjManager::find_obj(uint8 level, uint16 obj_n, uint8 quality, bool match_quality, uint16 frame_n, bool match_frame_n, Obj **prev_obj) {
uint8 i;
Obj *new_obj;
if (level == 0) {
for (i = 0; i < 64; i++) {
new_obj = find_obj_in_tree(obj_n, quality, match_quality, frame_n, match_frame_n, prev_obj, surface[i]);
if (new_obj != NULL)
return new_obj;
}
} else {
new_obj = find_obj_in_tree(obj_n, quality, match_quality, frame_n, match_frame_n, prev_obj, dungeon[level - 1]);
if (new_obj != NULL)
return new_obj;
}
return NULL;
}
inline Obj *ObjManager::find_obj_in_tree(uint16 obj_n, uint8 quality, bool match_quality, uint8 frame_n, bool match_frame_n, Obj **prev_obj, iAVLTree *obj_tree) {
iAVLCursor cursor;
ObjTreeNode *node;
U6Link *link;
Obj *new_obj;
node = (ObjTreeNode *)iAVLFirst(&cursor, obj_tree);
for (; node != NULL;) {
link = ((U6LList *)(node->obj_list))->start();
for (; link != NULL; link = link->next) {
new_obj = (Obj *)link->data;
if (new_obj->obj_n == obj_n && (match_quality == false || new_obj->quality == quality) && (match_frame_n == false || new_obj->frame_n == frame_n)) {
if (prev_obj != NULL && new_obj == *prev_obj)
*prev_obj = NULL;
else {
if (prev_obj == NULL || *prev_obj == NULL)
return new_obj;
}
}
/* Don't search containers.
if(prev_obj == NULL)
{
new_obj = new_obj->find_in_container(obj_n, quality, match_quality, frame_n, match_frame_n, prev_obj);
if(new_obj)
return new_obj;
}
*/
}
node = (ObjTreeNode *)iAVLNext(&cursor);
}
return NULL;
}
bool ObjManager::add_obj(Obj *obj, bool addOnTop) {
iAVLTree *obj_tree;
ObjTreeNode *node;
U6LList *obj_list;
iAVLKey key;
obj_tree = get_obj_tree(obj->x, obj->y, obj->z);
key = get_obj_tree_key(obj);
node = (ObjTreeNode *)iAVLSearch(obj_tree, key);
if (node == NULL) {
obj_list = new U6LList();
node = new ObjTreeNode;
node->key = key;
node->obj_list = obj_list;
iAVLInsert(obj_tree, node);
} else {
obj_list = node->obj_list;
}
if (addOnTop)
obj_list->add(obj);
else
obj_list->addAtPos(0, obj);
if (obj->status & OBJ_STATUS_TEMPORARY)
temp_obj_list_add(obj);
obj->set_on_map(obj_list); //mark object as on map.
return true;
}
bool ObjManager::addObjToContainer(U6LList *llist, Obj *obj) {
U6Link *link;
Obj *c_obj = NULL; //container object
uint16 index;
index = ((obj->y & 0x3f) << 10) + obj->x; //10 bits from x and 6 bits from y
link = llist->gotoPos(index);
if (link != NULL)
c_obj = (Obj *)link->data;
if (c_obj) { // we've found our container.
c_obj->add(obj);
//DEBUG(0,LEVEL_DEBUGGING,"Cont: %s\n", tile_manager->lookAtTile(get_obj_tile_num(c_obj->obj_n)+c_obj->frame_n,0,false));
//DEBUG(0,LEVEL_DEBUGGING,"Add to container %s", tile_manager->lookAtTile(get_obj_tile_num(obj->obj_n)+obj->frame_n,0,false));
//DEBUG(1,LEVEL_DEBUGGING," -> %s (%x,%x,%x)\n", tile_manager->lookAtTile(get_obj_tile_num(c_obj->obj_n)+c_obj->frame_n,0,false),c_obj->x,c_obj->y,c_obj->z);
return true;
}
return false;
}
Obj *ObjManager::loadObj(NuvieIO *buf) {
uint8 b1, b2;
Obj *obj;
obj = new Obj();
//obj->objblk_n = objblk_n;
obj->status = buf->read1();
//set new nuvie location bits.
switch (obj->status & OBJ_STATUS_MASK_GET) {
case OBJ_STATUS_ON_MAP :
obj->set_on_map(NULL);
break;//obj->nuvie_status |= OBJ_LOC_MAP; break;
case OBJ_STATUS_IN_CONTAINER :
obj->set_in_container(NULL);
break;//obj->nuvie_status |= OBJ_LOC_CONT; break;
case OBJ_STATUS_IN_INVENTORY :
obj->set_in_inventory();
break;//obj->nuvie_status |= OBJ_LOC_INV; break;
case OBJ_STATUS_READIED :
obj->readied();
break;//obj->nuvie_status |= OBJ_LOC_READIED; break;
}
obj->x = buf->read1(); // h
b1 = buf->read1();
obj->x += (b1 & 0x3) << 8;
obj->y = (b1 & 0xfc) >> 2;
b2 = buf->read1();
obj->y += (b2 & 0xf) << 6;
obj->z = (b2 & 0xf0) >> 4;
b1 = buf->read1();
b2 = buf->read1();
obj->obj_n = b1;
obj->obj_n += (b2 & 0x3) << 8;
obj->frame_n = (b2 & 0xfc) >> 2;
obj->qty = buf->read1();
obj->quality = buf->read1();
if (is_stackable(obj))
obj->qty = (uint16)(obj->quality << 8) + obj->qty;
//if(obj->qty == 0)
// obj->qty = 1;
return obj;
}
iAVLTree *ObjManager::get_obj_tree(uint16 x, uint16 y, uint8 level) {
if (level == 0) {
x >>= 7; // x = floor(x / 128) 128 = superchunk width
y >>= 7; // y = floor(y / 128) 128 = superchunk height
return surface[x + y * 8];
}
if (level > 5)
return NULL;
return dungeon[level - 1];
}
inline iAVLKey ObjManager::get_obj_tree_key(Obj *obj) {
return get_obj_tree_key(obj->x, obj->y, obj->z);
}
iAVLKey ObjManager::get_obj_tree_key(uint16 x, uint16 y, uint8 level) {
iAVLKey key;
if (level == 0)
key._int = y * 1024 + x;
else
key._int = y * 256 + x;
return key;
}
void ObjManager::update(uint16 x, uint16 y, uint8 z, bool teleport) {
uint16 cur_blk_x, cur_blk_y;
cur_blk_x = x >> 3; // x / 8;
cur_blk_y = y >> 3; // y / 8;
// We're changing levels so clean out all temp objects on the current level.
if (last_obj_blk_z != z) {
if (last_obj_blk_z != OBJ_TEMP_INIT)
temp_obj_list_clean_level(last_obj_blk_z);
egg_manager->spawn_eggs(x, y, z, teleport);
last_obj_blk_x = cur_blk_x;
last_obj_blk_y = cur_blk_y;
last_obj_blk_z = z;
return;
}
//FIX for level change. we want to remove all temps on level change.
if (cur_blk_x != last_obj_blk_x || cur_blk_y != last_obj_blk_y) {
last_obj_blk_x = cur_blk_x;
last_obj_blk_y = cur_blk_y;
temp_obj_list_clean_area(x, y);
egg_manager->spawn_eggs(x, y, z, teleport);
}
return;
}
bool ObjManager::temp_obj_list_add(Obj *obj) {
if (obj == NULL)
return false;
temp_obj_list.push_back(obj);
return true;
}
bool ObjManager::temp_obj_list_remove(Obj *obj) {
temp_obj_list.remove(obj);
return true;
}
void ObjManager::remove_temp_obj(Obj *tmp_obj) {
//FIXME MD has special temp object flag override logic. This should be implemented in lua script.
if (game_type != NUVIE_GAME_MD || (tmp_obj->obj_n != OBJ_MD_DREAM_TELEPORTER && tmp_obj->frame_n != 0)) {
DEBUG(0,
LEVEL_DEBUGGING,
"Removing obj %s.\n",
tile_manager->lookAtTile(get_obj_tile_num((tmp_obj)->obj_n) + (tmp_obj)->frame_n, 0, false));
remove_obj_from_map(tmp_obj);
delete_obj(tmp_obj);
}
}
// clean objects from a whole level.
void ObjManager::temp_obj_list_clean_level(uint8 z) {
Std::list<Obj *>::iterator obj;
Obj *tmp_obj;
for (obj = temp_obj_list.begin(); obj != temp_obj_list.end();) {
if ((*obj)->z == z) {
tmp_obj = *obj++;
remove_temp_obj(tmp_obj);
} else
obj++;
}
return;
}
// Clean objects more than 19 tiles from position
void ObjManager::temp_obj_list_clean_area(uint16 x, uint16 y) {
Std::list<Obj *>::iterator obj;
Obj *tmp_obj;
sint16 dist_x, dist_y;
for (obj = temp_obj_list.begin(); obj != temp_obj_list.end();) {
dist_x = abs((sint16)(*obj)->x - x);
dist_y = abs((sint16)(*obj)->y - y);
if (dist_x > 19 || dist_y > 19) {
tmp_obj = *obj++;
remove_temp_obj(tmp_obj);
} else
obj++;
}
return;
}
/*
inline U6LList *ObjManager::get_schunk_list(uint16 x, uint16 y, uint8 level)
{
uint16 sx, sy;
if(level == 0)
{
sx = x / 128;
sy = y / 128;
return surface[sy * 8 + sx];
}
return dungeon[level-1];
}
*/
//prints a human readable list of object number / names.
void ObjManager::print_object_list() {
uint16 i;
DEBUG(0, LEVEL_INFORMATIONAL, "print_object_list:\n");
for (i = 0; i < 1024; i++) {
DEBUG(1, LEVEL_INFORMATIONAL, "%04d: %s\n", i, tile_manager->lookAtTile(get_obj_tile_num(i), 0, false));
}
return;
}
void ObjManager::print_egg_list() {
uint8 i;
for (i = 0; i < 64; i++)
print_egg_tree(surface[i]);
for (i = 0; i < 5; i++)
print_egg_tree(dungeon[i]);
return;
}
inline void ObjManager::print_egg_tree(iAVLTree *obj_tree) {
ObjTreeNode *tree_node;
iAVLCursor cursor;
U6LList *obj_list;
U6Link *link;
Obj *obj;
tree_node = (ObjTreeNode *)iAVLFirst(&cursor, obj_tree);
for (; tree_node != NULL; tree_node = (ObjTreeNode *)iAVLNext(&cursor)) {
obj_list = (U6LList *)tree_node->obj_list;
for (link = obj_list->start(); link != NULL; link = link->next) {
obj = (Obj *)link->data;
if (obj->obj_n == 335) {
print_obj(obj, false);
}
}
}
return;
}
void ObjManager::print_obj(Obj *obj, bool in_container, uint8 indent) {
U6Link *link;
Obj *container_obj;
const CombatType *c_type = NULL;
Actor *a = Game::get_game()->get_player()->get_actor();
if (a != NULL)
c_type = a->get_object_combat_type(obj->obj_n);
DEBUG(1, LEVEL_INFORMATIONAL, "\n");
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "%s ", tile_manager->lookAtTile(get_obj_tile_num(obj->obj_n) + obj->frame_n, 0, false));
if (in_container == false)
DEBUG(1, LEVEL_INFORMATIONAL, "at %x, %x, %x (%d,%d,%d)", obj->x, obj->y, obj->z, obj->x, obj->y, obj->z);
DEBUG(1, LEVEL_INFORMATIONAL, "\n");
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "object (Obj *) %p\n", obj);
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "engine loc: ");
switch (obj->get_engine_loc()) {
case OBJ_LOC_MAP :
DEBUG(1, LEVEL_INFORMATIONAL, "MAP");
break;
case OBJ_LOC_CONT :
DEBUG(1, LEVEL_INFORMATIONAL, "CONTAINER");
break;
case OBJ_LOC_INV :
DEBUG(1, LEVEL_INFORMATIONAL, "INVENTORY");
break;
case OBJ_LOC_READIED :
DEBUG(1, LEVEL_INFORMATIONAL, "INVENTORY READIED");
break;
case OBJ_LOC_NONE :
DEBUG(1, LEVEL_INFORMATIONAL, "NONE");
break;
default :
DEBUG(1, LEVEL_INFORMATIONAL, "**UNKNOWN**");
break;
}
if (obj->is_actor_obj())
DEBUG(1, LEVEL_INFORMATIONAL, " (ACTOR_OBJ)");
DEBUG(1, LEVEL_INFORMATIONAL, "\n");
DEBUG(1, LEVEL_INFORMATIONAL, "parent (");
switch (obj->get_engine_loc()) {
case OBJ_LOC_MAP :
DEBUG(1, LEVEL_INFORMATIONAL, "U6LList");
break;
case OBJ_LOC_CONT :
DEBUG(1, LEVEL_INFORMATIONAL, "Obj");
break;
case OBJ_LOC_INV :
case OBJ_LOC_READIED :
DEBUG(1, LEVEL_INFORMATIONAL, "Actor");
break;
default :
DEBUG(1, LEVEL_INFORMATIONAL, "void");
break;
}
DEBUG(1, LEVEL_INFORMATIONAL, " *) %p\n", obj->parent);
print_indent(LEVEL_INFORMATIONAL, indent);
// DEBUG(1,LEVEL_DEBUGGING,"objblk_n: %d\n", obj->objblk_n);
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "obj_n: %d\n", obj->obj_n);
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "frame_n: %d\n", obj->frame_n);
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "Tile: %d\n", get_obj_tile_num(obj->obj_n));
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "Status: ");
print_b(LEVEL_INFORMATIONAL, obj->status);
if (obj->status != 0) {
DEBUG(1, LEVEL_INFORMATIONAL, " ( ");
if (obj->is_readied())
DEBUG(1, LEVEL_INFORMATIONAL, "POS:Ready ");
else if (obj->is_in_container())
DEBUG(1, LEVEL_INFORMATIONAL, "POS:Cont ");
else if (obj->is_in_inventory())
DEBUG(1, LEVEL_INFORMATIONAL, "POS:Inv ");
if (obj->is_ok_to_take())
DEBUG(1, LEVEL_INFORMATIONAL, "OK ");
if (obj->is_temporary())
DEBUG(1, LEVEL_INFORMATIONAL, "TEMP ");
if (obj->is_invisible())
DEBUG(1, LEVEL_INFORMATIONAL, "INVIS ");
if (obj->is_egg_active()) {
if (obj->obj_n < 256)
DEBUG(1, LEVEL_INFORMATIONAL, "MUTANT ");
else
DEBUG(1, LEVEL_INFORMATIONAL, "BROKEN ");
}
DEBUG(1, LEVEL_INFORMATIONAL, ")");
}
DEBUG(1, LEVEL_INFORMATIONAL, "\n");
if (in_container) {
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "parent_id = %d, y = %d, z = %d\n", obj->x, obj->y, obj->z);
}
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "Quantity: %d\n", obj->qty);
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "Quality: %d\n", obj->quality);
if (c_type != NULL) {
DEBUG(1, LEVEL_INFORMATIONAL, "attack/damage = %d, defence/defense = %d\n", c_type->damage, c_type->defense); // FIXME add the rest of the combat values
}
if (obj->container) {
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "Container\n");
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "---------");
for (link = obj->container->start(); link != NULL; link = link->next) {
container_obj = (Obj *)link->data;
print_obj(container_obj, true, indent + 2);
}
print_indent(LEVEL_INFORMATIONAL, indent);
DEBUG(1, LEVEL_INFORMATIONAL, "---------\n");
}
if (in_container == false)
DEBUG(1, LEVEL_INFORMATIONAL, "\n");
return;
}
Obj *new_obj(uint16 obj_n, uint8 frame_n, uint16 x, uint16 y, uint16 z) {
Obj *obj;
obj = new Obj();
obj->obj_n = obj_n;
obj->frame_n = frame_n;
obj->x = x;
obj->y = y;
obj->z = z;
return obj;
}
void delete_obj(Obj *obj) {
U6Link *link;
if (obj->is_script_obj() == false) {
if (obj->container) {
for (link = obj->container->start(); link != NULL;) {
Obj *cont_obj = (Obj *)link->data;
link = link->next;
delete_obj(cont_obj);
}
}
if (obj->container)
delete obj->container;
delete obj;
}
return;
}
// add object to list, stacking with existing objects if possible
// This is used for adding objects to inventory OR a container.
// *It will stack onto the new object and delete the existing object!*
//FIXME!!!!! We need to set on_map() etc if going to the map.
bool ObjManager::list_add_obj(U6LList *llist, Obj *obj, bool stack_objects, uint32 pos) {
Obj *stack_with;
uint16 new_qty;
U6Link *link;
if (!llist || !obj)
return false;
assert(pos == 0 || pos < llist->count());
if (stack_objects && is_stackable(obj)) {
for (link = llist->start(); link != NULL;) {
stack_with = (Obj *)link->data;
link = link->next;
if (stack_with->obj_n == obj->obj_n && stack_with->frame_n == obj->frame_n
&& stack_with->quality == obj->quality && is_stackable(stack_with)) {
new_qty = obj->qty + stack_with->qty;
obj->qty = new_qty;
llist->addAtPos(llist->findPos(stack_with), obj);
llist->remove(stack_with);
delete_obj(stack_with);
return true;
}
}
}
llist->addAtPos(pos, obj);
return true;
}
/* Call load usecode for all objects (after loading them). This should be in
* loadObj() but that was crashing when usecode tried to use timers.
*/
void ObjManager::startObjs() {
uint8 i;
//iterate through surface chunks.
for (i = 0; i < 64; i++)
start_obj_usecode(surface[i]);
//iterate through dungeon chunks.
for (i = 0; i < 5; i++)
start_obj_usecode(dungeon[i]);
}
inline void ObjManager::start_obj_usecode(iAVLTree *obj_tree) {
ObjTreeNode *tree_node;
iAVLCursor cursor;
U6LList *obj_list;
U6Link *link;
Obj *obj;
tree_node = (ObjTreeNode *)iAVLFirst(&cursor, obj_tree);
for (; tree_node != NULL; tree_node = (ObjTreeNode *)iAVLNext(&cursor)) {
obj_list = (U6LList *)tree_node->obj_list;
for (link = obj_list->start(); link != NULL; link = link->next) {
obj = (Obj *)link->data;
if (usecode->has_loadcode(obj))
usecode->load_obj(obj);
}
}
}
/* Subtract an object stack with quantity set to `count' from original object
* stack `obj'.
* Returns a new object if a stack could be subtracted from the original,
* leaving the original intact.
* Returns the original if its quantity was smaller than the requested count or
* it is not stackable.
*/
Obj *ObjManager::get_obj_from_stack(Obj *obj, uint32 count) {
if (count == 0 || obj->qty <= count || !is_stackable(obj))
return (obj);
// requested is over 0, original quantity is greater than requested, object
// is stackable
Obj *new_obj = copy_obj(obj);
new_obj->qty = count;
obj->qty -= count; // remove requested from original
return (new_obj);
}
void clean_obj_tree_node(void *node) {
U6Link *link;
ObjTreeNode *obj_node = (ObjTreeNode *)node;
for (link = obj_node->obj_list->start(); link != NULL;) {
Obj *obj = (Obj *)link->data;
link = link->next;
delete_obj(obj);
}
delete obj_node->obj_list;
delete obj_node;
return;
}
bool ObjManager::unlink_from_engine(Obj *obj, bool run_usecode) {
Actor *a;
Obj *cont_obj;
switch (obj->get_engine_loc()) {
case OBJ_LOC_NONE :
break;
case OBJ_LOC_MAP :
remove_obj_from_map(obj);
break;
// inventory_remove_obj unreadies
case OBJ_LOC_READIED :/* a = (Actor *)obj->parent;
a->remove_readied_object(obj, run_usecode);
a->inventory_remove_obj(obj, run_usecode);
break;
*/
case OBJ_LOC_INV :
a = (Actor *)obj->parent;
a->inventory_remove_obj(obj, run_usecode);
break;
case OBJ_LOC_CONT :
cont_obj = obj->get_container_obj();
if (cont_obj)
cont_obj->remove(obj); //remove from parent container.
break;
break;
}
return true;
}
bool ObjManager::moveto_map(Obj *obj, MapCoord location) {
unlink_from_engine(obj);
obj->x = location.x;
obj->y = location.y;
obj->z = location.z;
add_obj(obj, OBJ_ADD_TOP);
return true;
}
bool ObjManager::moveto_inventory(Obj *obj, uint16 actor_num) {
ActorManager *am = Game::get_game()->get_actor_manager();
if (!am)
return false;
return moveto_inventory(obj, am->get_actor(actor_num));
}
bool ObjManager::moveto_inventory(Obj *obj, Actor *actor) {
unlink_from_engine(obj);
actor->inventory_add_object(obj);
return true;
}
bool ObjManager::moveto_container(Obj *obj, Obj *container_obj, bool stack) {
if (obj == container_obj)
return false;
unlink_from_engine(obj);
container_obj->add(obj, stack);
if (game_type == NUVIE_GAME_SE) {
if (container_obj->obj_n == OBJ_SE_JAR) { // frame changes depending on contents
switch (obj->obj_n) {
case OBJ_SE_CORN_MEAL:
case OBJ_SE_CORN:
case OBJ_SE_SULFUR:
container_obj->frame_n = 1; // yellow jar
break;
case OBJ_SE_MAGNESIUM_RIBBON:
case OBJ_SE_POTASSIUM_NITRATE:
container_obj->frame_n = 2; // white jar
break;
default:
container_obj->frame_n = 3; // black jar
break;
}
}
}
return true;
}
} // End of namespace Nuvie
} // End of namespace Ultima
| somaen/scummvm | engines/ultima/nuvie/core/obj_manager.cpp | C++ | gpl-2.0 | 57,348 |
/*
(See Documentation/git-fast-import.txt for maintained documentation.)
Format of STDIN stream:
stream ::= cmd*;
cmd ::= new_blob
| new_commit
| new_tag
| reset_branch
| checkpoint
| progress
;
new_blob ::= 'blob' lf
mark?
file_content;
file_content ::= data;
new_commit ::= 'commit' sp ref_str lf
mark?
('author' (sp name)? sp '<' email '>' sp when lf)?
'committer' (sp name)? sp '<' email '>' sp when lf
commit_msg
('from' sp commit-ish lf)?
('merge' sp commit-ish lf)*
(file_change | ls)*
lf?;
commit_msg ::= data;
ls ::= 'ls' sp '"' quoted(path) '"' lf;
file_change ::= file_clr
| file_del
| file_rnm
| file_cpy
| file_obm
| file_inm;
file_clr ::= 'deleteall' lf;
file_del ::= 'D' sp path_str lf;
file_rnm ::= 'R' sp path_str sp path_str lf;
file_cpy ::= 'C' sp path_str sp path_str lf;
file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
data;
note_obm ::= 'N' sp (hexsha1 | idnum) sp commit-ish lf;
note_inm ::= 'N' sp 'inline' sp commit-ish lf
data;
new_tag ::= 'tag' sp tag_str lf
'from' sp commit-ish lf
('tagger' (sp name)? sp '<' email '>' sp when lf)?
tag_msg;
tag_msg ::= data;
reset_branch ::= 'reset' sp ref_str lf
('from' sp commit-ish lf)?
lf?;
checkpoint ::= 'checkpoint' lf
lf?;
progress ::= 'progress' sp not_lf* lf
lf?;
# note: the first idnum in a stream should be 1 and subsequent
# idnums should not have gaps between values as this will cause
# the stream parser to reserve space for the gapped values. An
# idnum can be updated in the future to a new object by issuing
# a new mark directive with the old idnum.
#
mark ::= 'mark' sp idnum lf;
data ::= (delimited_data | exact_data)
lf?;
# note: delim may be any string but must not contain lf.
# data_line may contain any data but must not be exactly
# delim.
delimited_data ::= 'data' sp '<<' delim lf
(data_line lf)*
delim lf;
# note: declen indicates the length of binary_data in bytes.
# declen does not include the lf preceding the binary data.
#
exact_data ::= 'data' sp declen lf
binary_data;
# note: quoted strings are C-style quoting supporting \c for
# common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
# is the signed byte value in octal. Note that the only
# characters which must actually be escaped to protect the
# stream formatting is: \, " and LF. Otherwise these values
# are UTF8.
#
commit-ish ::= (ref_str | hexsha1 | sha1exp_str | idnum);
ref_str ::= ref;
sha1exp_str ::= sha1exp;
tag_str ::= tag;
path_str ::= path | '"' quoted(path) '"' ;
mode ::= '100644' | '644'
| '100755' | '755'
| '120000'
;
declen ::= # unsigned 32 bit value, ascii base10 notation;
bigint ::= # unsigned integer value, ascii base10 notation;
binary_data ::= # file content, not interpreted;
when ::= raw_when | rfc2822_when;
raw_when ::= ts sp tz;
rfc2822_when ::= # Valid RFC 2822 date and time;
sp ::= # ASCII space character;
lf ::= # ASCII newline (LF) character;
# note: a colon (':') must precede the numerical value assigned to
# an idnum. This is to distinguish it from a ref or tag name as
# GIT does not permit ':' in ref or tag strings.
#
idnum ::= ':' bigint;
path ::= # GIT style file path, e.g. "a/b/c";
ref ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
tag ::= # GIT tag name, e.g. "FIREFOX_1_5";
sha1exp ::= # Any valid GIT SHA1 expression;
hexsha1 ::= # SHA1 in hexadecimal format;
# note: name and email are UTF8 strings, however name must not
# contain '<' or lf and email must not contain any of the
# following: '<', '>', lf.
#
name ::= # valid GIT author/committer name;
email ::= # valid GIT author/committer email;
ts ::= # time since the epoch in seconds, ascii base10 notation;
tz ::= # GIT style timezone;
# note: comments, get-mark, ls-tree, and cat-blob requests may
# appear anywhere in the input, except within a data command. Any
# form of the data command always escapes the related input from
# comment processing.
#
# In case it is not clear, the '#' that starts the comment
# must be the first character on that line (an lf
# preceded it).
#
get_mark ::= 'get-mark' sp idnum lf;
cat_blob ::= 'cat-blob' sp (hexsha1 | idnum) lf;
ls_tree ::= 'ls' sp (hexsha1 | idnum) sp path_str lf;
comment ::= '#' not_lf* lf;
not_lf ::= # Any byte that is not ASCII newline (LF);
*/
#include "builtin.h"
#include "cache.h"
#include "lockfile.h"
#include "object.h"
#include "blob.h"
#include "tree.h"
#include "commit.h"
#include "delta.h"
#include "pack.h"
#include "refs.h"
#include "csum-file.h"
#include "quote.h"
#include "exec_cmd.h"
#include "dir.h"
#define PACK_ID_BITS 16
#define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
#define DEPTH_BITS 13
#define MAX_DEPTH ((1<<DEPTH_BITS)-1)
/*
* We abuse the setuid bit on directories to mean "do not delta".
*/
#define NO_DELTA S_ISUID
struct object_entry {
struct pack_idx_entry idx;
struct object_entry *next;
uint32_t type : TYPE_BITS,
pack_id : PACK_ID_BITS,
depth : DEPTH_BITS;
};
struct object_entry_pool {
struct object_entry_pool *next_pool;
struct object_entry *next_free;
struct object_entry *end;
struct object_entry entries[FLEX_ARRAY]; /* more */
};
struct mark_set {
union {
struct object_entry *marked[1024];
struct mark_set *sets[1024];
} data;
unsigned int shift;
};
struct last_object {
struct strbuf data;
off_t offset;
unsigned int depth;
unsigned no_swap : 1;
};
struct mem_pool {
struct mem_pool *next_pool;
char *next_free;
char *end;
uintmax_t space[FLEX_ARRAY]; /* more */
};
struct atom_str {
struct atom_str *next_atom;
unsigned short str_len;
char str_dat[FLEX_ARRAY]; /* more */
};
struct tree_content;
struct tree_entry {
struct tree_content *tree;
struct atom_str *name;
struct tree_entry_ms {
uint16_t mode;
unsigned char sha1[20];
} versions[2];
};
struct tree_content {
unsigned int entry_capacity; /* must match avail_tree_content */
unsigned int entry_count;
unsigned int delta_depth;
struct tree_entry *entries[FLEX_ARRAY]; /* more */
};
struct avail_tree_content {
unsigned int entry_capacity; /* must match tree_content */
struct avail_tree_content *next_avail;
};
struct branch {
struct branch *table_next_branch;
struct branch *active_next_branch;
const char *name;
struct tree_entry branch_tree;
uintmax_t last_commit;
uintmax_t num_notes;
unsigned active : 1;
unsigned delete : 1;
unsigned pack_id : PACK_ID_BITS;
unsigned char sha1[20];
};
struct tag {
struct tag *next_tag;
const char *name;
unsigned int pack_id;
unsigned char sha1[20];
};
struct hash_list {
struct hash_list *next;
unsigned char sha1[20];
};
typedef enum {
WHENSPEC_RAW = 1,
WHENSPEC_RFC2822,
WHENSPEC_NOW
} whenspec_type;
struct recent_command {
struct recent_command *prev;
struct recent_command *next;
char *buf;
};
/* Configured limits on output */
static unsigned long max_depth = 10;
static off_t max_packsize;
static int force_update;
static int pack_compression_level = Z_DEFAULT_COMPRESSION;
static int pack_compression_seen;
/* Stats and misc. counters */
static uintmax_t alloc_count;
static uintmax_t marks_set_count;
static uintmax_t object_count_by_type[1 << TYPE_BITS];
static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
static uintmax_t delta_count_by_type[1 << TYPE_BITS];
static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
static unsigned long object_count;
static unsigned long branch_count;
static unsigned long branch_load_count;
static int failure;
static FILE *pack_edges;
static unsigned int show_stats = 1;
static int global_argc;
static char **global_argv;
/* Memory pools */
static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
static size_t total_allocd;
static struct mem_pool *mem_pool;
/* Atom management */
static unsigned int atom_table_sz = 4451;
static unsigned int atom_cnt;
static struct atom_str **atom_table;
/* The .pack file being generated */
static struct pack_idx_option pack_idx_opts;
static unsigned int pack_id;
static struct sha1file *pack_file;
static struct packed_git *pack_data;
static struct packed_git **all_packs;
static off_t pack_size;
/* Table of objects we've written. */
static unsigned int object_entry_alloc = 5000;
static struct object_entry_pool *blocks;
static struct object_entry *object_table[1 << 16];
static struct mark_set *marks;
static const char *export_marks_file;
static const char *import_marks_file;
static int import_marks_file_from_stream;
static int import_marks_file_ignore_missing;
static int relative_marks_paths;
/* Our last blob */
static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
/* Tree management */
static unsigned int tree_entry_alloc = 1000;
static void *avail_tree_entry;
static unsigned int avail_tree_table_sz = 100;
static struct avail_tree_content **avail_tree_table;
static struct strbuf old_tree = STRBUF_INIT;
static struct strbuf new_tree = STRBUF_INIT;
/* Branch data */
static unsigned long max_active_branches = 5;
static unsigned long cur_active_branches;
static unsigned long branch_table_sz = 1039;
static struct branch **branch_table;
static struct branch *active_branches;
/* Tag data */
static struct tag *first_tag;
static struct tag *last_tag;
/* Input stream parsing */
static whenspec_type whenspec = WHENSPEC_RAW;
static struct strbuf command_buf = STRBUF_INIT;
static int unread_command_buf;
static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
static struct recent_command *cmd_tail = &cmd_hist;
static struct recent_command *rc_free;
static unsigned int cmd_save = 100;
static uintmax_t next_mark;
static struct strbuf new_data = STRBUF_INIT;
static int seen_data_command;
static int require_explicit_termination;
/* Signal handling */
static volatile sig_atomic_t checkpoint_requested;
/* Where to write output of cat-blob commands */
static int cat_blob_fd = STDOUT_FILENO;
static void parse_argv(void);
static void parse_get_mark(const char *p);
static void parse_cat_blob(const char *p);
static void parse_ls(const char *p, struct branch *b);
static void write_branch_report(FILE *rpt, struct branch *b)
{
fprintf(rpt, "%s:\n", b->name);
fprintf(rpt, " status :");
if (b->active)
fputs(" active", rpt);
if (b->branch_tree.tree)
fputs(" loaded", rpt);
if (is_null_sha1(b->branch_tree.versions[1].sha1))
fputs(" dirty", rpt);
fputc('\n', rpt);
fprintf(rpt, " tip commit : %s\n", sha1_to_hex(b->sha1));
fprintf(rpt, " old tree : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
fprintf(rpt, " cur tree : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit);
fputs(" last pack : ", rpt);
if (b->pack_id < MAX_PACK_ID)
fprintf(rpt, "%u", b->pack_id);
fputc('\n', rpt);
fputc('\n', rpt);
}
static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
static void write_crash_report(const char *err)
{
char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
FILE *rpt = fopen(loc, "w");
struct branch *b;
unsigned long lu;
struct recent_command *rc;
if (!rpt) {
error("can't write crash report %s: %s", loc, strerror(errno));
free(loc);
return;
}
fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
fprintf(rpt, "fast-import crash report:\n");
fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid());
fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
fputc('\n', rpt);
fputs("fatal: ", rpt);
fputs(err, rpt);
fputc('\n', rpt);
fputc('\n', rpt);
fputs("Most Recent Commands Before Crash\n", rpt);
fputs("---------------------------------\n", rpt);
for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
if (rc->next == &cmd_hist)
fputs("* ", rpt);
else
fputs(" ", rpt);
fputs(rc->buf, rpt);
fputc('\n', rpt);
}
fputc('\n', rpt);
fputs("Active Branch LRU\n", rpt);
fputs("-----------------\n", rpt);
fprintf(rpt, " active_branches = %lu cur, %lu max\n",
cur_active_branches,
max_active_branches);
fputc('\n', rpt);
fputs(" pos clock name\n", rpt);
fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
for (b = active_branches, lu = 0; b; b = b->active_next_branch)
fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n",
++lu, b->last_commit, b->name);
fputc('\n', rpt);
fputs("Inactive Branches\n", rpt);
fputs("-----------------\n", rpt);
for (lu = 0; lu < branch_table_sz; lu++) {
for (b = branch_table[lu]; b; b = b->table_next_branch)
write_branch_report(rpt, b);
}
if (first_tag) {
struct tag *tg;
fputc('\n', rpt);
fputs("Annotated Tags\n", rpt);
fputs("--------------\n", rpt);
for (tg = first_tag; tg; tg = tg->next_tag) {
fputs(sha1_to_hex(tg->sha1), rpt);
fputc(' ', rpt);
fputs(tg->name, rpt);
fputc('\n', rpt);
}
}
fputc('\n', rpt);
fputs("Marks\n", rpt);
fputs("-----\n", rpt);
if (export_marks_file)
fprintf(rpt, " exported to %s\n", export_marks_file);
else
dump_marks_helper(rpt, 0, marks);
fputc('\n', rpt);
fputs("-------------------\n", rpt);
fputs("END OF CRASH REPORT\n", rpt);
fclose(rpt);
free(loc);
}
static void end_packfile(void);
static void unkeep_all_packs(void);
static void dump_marks(void);
static NORETURN void die_nicely(const char *err, va_list params)
{
static int zombie;
char message[2 * PATH_MAX];
vsnprintf(message, sizeof(message), err, params);
fputs("fatal: ", stderr);
fputs(message, stderr);
fputc('\n', stderr);
if (!zombie) {
zombie = 1;
write_crash_report(message);
end_packfile();
unkeep_all_packs();
dump_marks();
}
exit(128);
}
#ifndef SIGUSR1 /* Windows, for example */
static void set_checkpoint_signal(void)
{
}
#else
static void checkpoint_signal(int signo)
{
checkpoint_requested = 1;
}
static void set_checkpoint_signal(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = checkpoint_signal;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &sa, NULL);
}
#endif
static void alloc_objects(unsigned int cnt)
{
struct object_entry_pool *b;
b = xmalloc(sizeof(struct object_entry_pool)
+ cnt * sizeof(struct object_entry));
b->next_pool = blocks;
b->next_free = b->entries;
b->end = b->entries + cnt;
blocks = b;
alloc_count += cnt;
}
static struct object_entry *new_object(unsigned char *sha1)
{
struct object_entry *e;
if (blocks->next_free == blocks->end)
alloc_objects(object_entry_alloc);
e = blocks->next_free++;
hashcpy(e->idx.sha1, sha1);
return e;
}
static struct object_entry *find_object(unsigned char *sha1)
{
unsigned int h = sha1[0] << 8 | sha1[1];
struct object_entry *e;
for (e = object_table[h]; e; e = e->next)
if (!hashcmp(sha1, e->idx.sha1))
return e;
return NULL;
}
static struct object_entry *insert_object(unsigned char *sha1)
{
unsigned int h = sha1[0] << 8 | sha1[1];
struct object_entry *e = object_table[h];
while (e) {
if (!hashcmp(sha1, e->idx.sha1))
return e;
e = e->next;
}
e = new_object(sha1);
e->next = object_table[h];
e->idx.offset = 0;
object_table[h] = e;
return e;
}
static unsigned int hc_str(const char *s, size_t len)
{
unsigned int r = 0;
while (len-- > 0)
r = r * 31 + *s++;
return r;
}
static void *pool_alloc(size_t len)
{
struct mem_pool *p;
void *r;
/* round up to a 'uintmax_t' alignment */
if (len & (sizeof(uintmax_t) - 1))
len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
for (p = mem_pool; p; p = p->next_pool)
if ((p->end - p->next_free >= len))
break;
if (!p) {
if (len >= (mem_pool_alloc/2)) {
total_allocd += len;
return xmalloc(len);
}
total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
p->next_pool = mem_pool;
p->next_free = (char *) p->space;
p->end = p->next_free + mem_pool_alloc;
mem_pool = p;
}
r = p->next_free;
p->next_free += len;
return r;
}
static void *pool_calloc(size_t count, size_t size)
{
size_t len = count * size;
void *r = pool_alloc(len);
memset(r, 0, len);
return r;
}
static char *pool_strdup(const char *s)
{
size_t len = strlen(s) + 1;
char *r = pool_alloc(len);
memcpy(r, s, len);
return r;
}
static void insert_mark(uintmax_t idnum, struct object_entry *oe)
{
struct mark_set *s = marks;
while ((idnum >> s->shift) >= 1024) {
s = pool_calloc(1, sizeof(struct mark_set));
s->shift = marks->shift + 10;
s->data.sets[0] = marks;
marks = s;
}
while (s->shift) {
uintmax_t i = idnum >> s->shift;
idnum -= i << s->shift;
if (!s->data.sets[i]) {
s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
s->data.sets[i]->shift = s->shift - 10;
}
s = s->data.sets[i];
}
if (!s->data.marked[idnum])
marks_set_count++;
s->data.marked[idnum] = oe;
}
static struct object_entry *find_mark(uintmax_t idnum)
{
uintmax_t orig_idnum = idnum;
struct mark_set *s = marks;
struct object_entry *oe = NULL;
if ((idnum >> s->shift) < 1024) {
while (s && s->shift) {
uintmax_t i = idnum >> s->shift;
idnum -= i << s->shift;
s = s->data.sets[i];
}
if (s)
oe = s->data.marked[idnum];
}
if (!oe)
die("mark :%" PRIuMAX " not declared", orig_idnum);
return oe;
}
static struct atom_str *to_atom(const char *s, unsigned short len)
{
unsigned int hc = hc_str(s, len) % atom_table_sz;
struct atom_str *c;
for (c = atom_table[hc]; c; c = c->next_atom)
if (c->str_len == len && !strncmp(s, c->str_dat, len))
return c;
c = pool_alloc(sizeof(struct atom_str) + len + 1);
c->str_len = len;
memcpy(c->str_dat, s, len);
c->str_dat[len] = 0;
c->next_atom = atom_table[hc];
atom_table[hc] = c;
atom_cnt++;
return c;
}
static struct branch *lookup_branch(const char *name)
{
unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
struct branch *b;
for (b = branch_table[hc]; b; b = b->table_next_branch)
if (!strcmp(name, b->name))
return b;
return NULL;
}
static struct branch *new_branch(const char *name)
{
unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
struct branch *b = lookup_branch(name);
if (b)
die("Invalid attempt to create duplicate branch: %s", name);
if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
die("Branch name doesn't conform to GIT standards: %s", name);
b = pool_calloc(1, sizeof(struct branch));
b->name = pool_strdup(name);
b->table_next_branch = branch_table[hc];
b->branch_tree.versions[0].mode = S_IFDIR;
b->branch_tree.versions[1].mode = S_IFDIR;
b->num_notes = 0;
b->active = 0;
b->pack_id = MAX_PACK_ID;
branch_table[hc] = b;
branch_count++;
return b;
}
static unsigned int hc_entries(unsigned int cnt)
{
cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
}
static struct tree_content *new_tree_content(unsigned int cnt)
{
struct avail_tree_content *f, *l = NULL;
struct tree_content *t;
unsigned int hc = hc_entries(cnt);
for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
if (f->entry_capacity >= cnt)
break;
if (f) {
if (l)
l->next_avail = f->next_avail;
else
avail_tree_table[hc] = f->next_avail;
} else {
cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
f->entry_capacity = cnt;
}
t = (struct tree_content*)f;
t->entry_count = 0;
t->delta_depth = 0;
return t;
}
static void release_tree_entry(struct tree_entry *e);
static void release_tree_content(struct tree_content *t)
{
struct avail_tree_content *f = (struct avail_tree_content*)t;
unsigned int hc = hc_entries(f->entry_capacity);
f->next_avail = avail_tree_table[hc];
avail_tree_table[hc] = f;
}
static void release_tree_content_recursive(struct tree_content *t)
{
unsigned int i;
for (i = 0; i < t->entry_count; i++)
release_tree_entry(t->entries[i]);
release_tree_content(t);
}
static struct tree_content *grow_tree_content(
struct tree_content *t,
int amt)
{
struct tree_content *r = new_tree_content(t->entry_count + amt);
r->entry_count = t->entry_count;
r->delta_depth = t->delta_depth;
memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
release_tree_content(t);
return r;
}
static struct tree_entry *new_tree_entry(void)
{
struct tree_entry *e;
if (!avail_tree_entry) {
unsigned int n = tree_entry_alloc;
total_allocd += n * sizeof(struct tree_entry);
avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
while (n-- > 1) {
*((void**)e) = e + 1;
e++;
}
*((void**)e) = NULL;
}
e = avail_tree_entry;
avail_tree_entry = *((void**)e);
return e;
}
static void release_tree_entry(struct tree_entry *e)
{
if (e->tree)
release_tree_content_recursive(e->tree);
*((void**)e) = avail_tree_entry;
avail_tree_entry = e;
}
static struct tree_content *dup_tree_content(struct tree_content *s)
{
struct tree_content *d;
struct tree_entry *a, *b;
unsigned int i;
if (!s)
return NULL;
d = new_tree_content(s->entry_count);
for (i = 0; i < s->entry_count; i++) {
a = s->entries[i];
b = new_tree_entry();
memcpy(b, a, sizeof(*a));
if (a->tree && is_null_sha1(b->versions[1].sha1))
b->tree = dup_tree_content(a->tree);
else
b->tree = NULL;
d->entries[i] = b;
}
d->entry_count = s->entry_count;
d->delta_depth = s->delta_depth;
return d;
}
static void start_packfile(void)
{
static char tmp_file[PATH_MAX];
struct packed_git *p;
int namelen;
struct pack_header hdr;
int pack_fd;
pack_fd = odb_mkstemp(tmp_file, sizeof(tmp_file),
"pack/tmp_pack_XXXXXX");
namelen = strlen(tmp_file) + 2;
p = xcalloc(1, sizeof(*p) + namelen);
xsnprintf(p->pack_name, namelen, "%s", tmp_file);
p->pack_fd = pack_fd;
p->do_not_close = 1;
pack_file = sha1fd(pack_fd, p->pack_name);
hdr.hdr_signature = htonl(PACK_SIGNATURE);
hdr.hdr_version = htonl(2);
hdr.hdr_entries = 0;
sha1write(pack_file, &hdr, sizeof(hdr));
pack_data = p;
pack_size = sizeof(hdr);
object_count = 0;
REALLOC_ARRAY(all_packs, pack_id + 1);
all_packs[pack_id] = p;
}
static const char *create_index(void)
{
const char *tmpfile;
struct pack_idx_entry **idx, **c, **last;
struct object_entry *e;
struct object_entry_pool *o;
/* Build the table of object IDs. */
idx = xmalloc(object_count * sizeof(*idx));
c = idx;
for (o = blocks; o; o = o->next_pool)
for (e = o->next_free; e-- != o->entries;)
if (pack_id == e->pack_id)
*c++ = &e->idx;
last = idx + object_count;
if (c != last)
die("internal consistency error creating the index");
tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1);
free(idx);
return tmpfile;
}
static char *keep_pack(const char *curr_index_name)
{
static char name[PATH_MAX];
static const char *keep_msg = "fast-import";
int keep_fd;
keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1);
if (keep_fd < 0)
die_errno("cannot create keep file");
write_or_die(keep_fd, keep_msg, strlen(keep_msg));
if (close(keep_fd))
die_errno("failed to write keep file");
snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
get_object_directory(), sha1_to_hex(pack_data->sha1));
if (finalize_object_file(pack_data->pack_name, name))
die("cannot store pack file");
snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
get_object_directory(), sha1_to_hex(pack_data->sha1));
if (finalize_object_file(curr_index_name, name))
die("cannot store index file");
free((void *)curr_index_name);
return name;
}
static void unkeep_all_packs(void)
{
static char name[PATH_MAX];
int k;
for (k = 0; k < pack_id; k++) {
struct packed_git *p = all_packs[k];
snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
get_object_directory(), sha1_to_hex(p->sha1));
unlink_or_warn(name);
}
}
static void end_packfile(void)
{
static int running;
if (running || !pack_data)
return;
running = 1;
clear_delta_base_cache();
if (object_count) {
struct packed_git *new_p;
unsigned char cur_pack_sha1[20];
char *idx_name;
int i;
struct branch *b;
struct tag *t;
close_pack_windows(pack_data);
sha1close(pack_file, cur_pack_sha1, 0);
fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
pack_data->pack_name, object_count,
cur_pack_sha1, pack_size);
close(pack_data->pack_fd);
idx_name = keep_pack(create_index());
/* Register the packfile with core git's machinery. */
new_p = add_packed_git(idx_name, strlen(idx_name), 1);
if (!new_p)
die("core git rejected index %s", idx_name);
all_packs[pack_id] = new_p;
install_packed_git(new_p);
/* Print the boundary */
if (pack_edges) {
fprintf(pack_edges, "%s:", new_p->pack_name);
for (i = 0; i < branch_table_sz; i++) {
for (b = branch_table[i]; b; b = b->table_next_branch) {
if (b->pack_id == pack_id)
fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
}
}
for (t = first_tag; t; t = t->next_tag) {
if (t->pack_id == pack_id)
fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
}
fputc('\n', pack_edges);
fflush(pack_edges);
}
pack_id++;
}
else {
close(pack_data->pack_fd);
unlink_or_warn(pack_data->pack_name);
}
free(pack_data);
pack_data = NULL;
running = 0;
/* We can't carry a delta across packfiles. */
strbuf_release(&last_blob.data);
last_blob.offset = 0;
last_blob.depth = 0;
}
static void cycle_packfile(void)
{
end_packfile();
start_packfile();
}
static int store_object(
enum object_type type,
struct strbuf *dat,
struct last_object *last,
unsigned char *sha1out,
uintmax_t mark)
{
void *out, *delta;
struct object_entry *e;
unsigned char hdr[96];
unsigned char sha1[20];
unsigned long hdrlen, deltalen;
git_SHA_CTX c;
git_zstream s;
hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu",
typename(type), (unsigned long)dat->len) + 1;
git_SHA1_Init(&c);
git_SHA1_Update(&c, hdr, hdrlen);
git_SHA1_Update(&c, dat->buf, dat->len);
git_SHA1_Final(sha1, &c);
if (sha1out)
hashcpy(sha1out, sha1);
e = insert_object(sha1);
if (mark)
insert_mark(mark, e);
if (e->idx.offset) {
duplicate_count_by_type[type]++;
return 1;
} else if (find_sha1_pack(sha1, packed_git)) {
e->type = type;
e->pack_id = MAX_PACK_ID;
e->idx.offset = 1; /* just not zero! */
duplicate_count_by_type[type]++;
return 1;
}
if (last && last->data.buf && last->depth < max_depth && dat->len > 20) {
delta_count_attempts_by_type[type]++;
delta = diff_delta(last->data.buf, last->data.len,
dat->buf, dat->len,
&deltalen, dat->len - 20);
} else
delta = NULL;
git_deflate_init(&s, pack_compression_level);
if (delta) {
s.next_in = delta;
s.avail_in = deltalen;
} else {
s.next_in = (void *)dat->buf;
s.avail_in = dat->len;
}
s.avail_out = git_deflate_bound(&s, s.avail_in);
s.next_out = out = xmalloc(s.avail_out);
while (git_deflate(&s, Z_FINISH) == Z_OK)
; /* nothing */
git_deflate_end(&s);
/* Determine if we should auto-checkpoint. */
if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize)
|| (pack_size + 60 + s.total_out) < pack_size) {
/* This new object needs to *not* have the current pack_id. */
e->pack_id = pack_id + 1;
cycle_packfile();
/* We cannot carry a delta into the new pack. */
if (delta) {
free(delta);
delta = NULL;
git_deflate_init(&s, pack_compression_level);
s.next_in = (void *)dat->buf;
s.avail_in = dat->len;
s.avail_out = git_deflate_bound(&s, s.avail_in);
s.next_out = out = xrealloc(out, s.avail_out);
while (git_deflate(&s, Z_FINISH) == Z_OK)
; /* nothing */
git_deflate_end(&s);
}
}
e->type = type;
e->pack_id = pack_id;
e->idx.offset = pack_size;
object_count++;
object_count_by_type[type]++;
crc32_begin(pack_file);
if (delta) {
off_t ofs = e->idx.offset - last->offset;
unsigned pos = sizeof(hdr) - 1;
delta_count_by_type[type]++;
e->depth = last->depth + 1;
hdrlen = encode_in_pack_object_header(OBJ_OFS_DELTA, deltalen, hdr);
sha1write(pack_file, hdr, hdrlen);
pack_size += hdrlen;
hdr[pos] = ofs & 127;
while (ofs >>= 7)
hdr[--pos] = 128 | (--ofs & 127);
sha1write(pack_file, hdr + pos, sizeof(hdr) - pos);
pack_size += sizeof(hdr) - pos;
} else {
e->depth = 0;
hdrlen = encode_in_pack_object_header(type, dat->len, hdr);
sha1write(pack_file, hdr, hdrlen);
pack_size += hdrlen;
}
sha1write(pack_file, out, s.total_out);
pack_size += s.total_out;
e->idx.crc32 = crc32_end(pack_file);
free(out);
free(delta);
if (last) {
if (last->no_swap) {
last->data = *dat;
} else {
strbuf_swap(&last->data, dat);
}
last->offset = e->idx.offset;
last->depth = e->depth;
}
return 0;
}
static void truncate_pack(struct sha1file_checkpoint *checkpoint)
{
if (sha1file_truncate(pack_file, checkpoint))
die_errno("cannot truncate pack to skip duplicate");
pack_size = checkpoint->offset;
}
static void stream_blob(uintmax_t len, unsigned char *sha1out, uintmax_t mark)
{
size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
unsigned char *in_buf = xmalloc(in_sz);
unsigned char *out_buf = xmalloc(out_sz);
struct object_entry *e;
unsigned char sha1[20];
unsigned long hdrlen;
off_t offset;
git_SHA_CTX c;
git_zstream s;
struct sha1file_checkpoint checkpoint;
int status = Z_OK;
/* Determine if we should auto-checkpoint. */
if ((max_packsize && (pack_size + 60 + len) > max_packsize)
|| (pack_size + 60 + len) < pack_size)
cycle_packfile();
sha1file_checkpoint(pack_file, &checkpoint);
offset = checkpoint.offset;
hdrlen = snprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
if (out_sz <= hdrlen)
die("impossibly large object header");
git_SHA1_Init(&c);
git_SHA1_Update(&c, out_buf, hdrlen);
crc32_begin(pack_file);
git_deflate_init(&s, pack_compression_level);
hdrlen = encode_in_pack_object_header(OBJ_BLOB, len, out_buf);
if (out_sz <= hdrlen)
die("impossibly large object header");
s.next_out = out_buf + hdrlen;
s.avail_out = out_sz - hdrlen;
while (status != Z_STREAM_END) {
if (0 < len && !s.avail_in) {
size_t cnt = in_sz < len ? in_sz : (size_t)len;
size_t n = fread(in_buf, 1, cnt, stdin);
if (!n && feof(stdin))
die("EOF in data (%" PRIuMAX " bytes remaining)", len);
git_SHA1_Update(&c, in_buf, n);
s.next_in = in_buf;
s.avail_in = n;
len -= n;
}
status = git_deflate(&s, len ? 0 : Z_FINISH);
if (!s.avail_out || status == Z_STREAM_END) {
size_t n = s.next_out - out_buf;
sha1write(pack_file, out_buf, n);
pack_size += n;
s.next_out = out_buf;
s.avail_out = out_sz;
}
switch (status) {
case Z_OK:
case Z_BUF_ERROR:
case Z_STREAM_END:
continue;
default:
die("unexpected deflate failure: %d", status);
}
}
git_deflate_end(&s);
git_SHA1_Final(sha1, &c);
if (sha1out)
hashcpy(sha1out, sha1);
e = insert_object(sha1);
if (mark)
insert_mark(mark, e);
if (e->idx.offset) {
duplicate_count_by_type[OBJ_BLOB]++;
truncate_pack(&checkpoint);
} else if (find_sha1_pack(sha1, packed_git)) {
e->type = OBJ_BLOB;
e->pack_id = MAX_PACK_ID;
e->idx.offset = 1; /* just not zero! */
duplicate_count_by_type[OBJ_BLOB]++;
truncate_pack(&checkpoint);
} else {
e->depth = 0;
e->type = OBJ_BLOB;
e->pack_id = pack_id;
e->idx.offset = offset;
e->idx.crc32 = crc32_end(pack_file);
object_count++;
object_count_by_type[OBJ_BLOB]++;
}
free(in_buf);
free(out_buf);
}
/* All calls must be guarded by find_object() or find_mark() to
* ensure the 'struct object_entry' passed was written by this
* process instance. We unpack the entry by the offset, avoiding
* the need for the corresponding .idx file. This unpacking rule
* works because we only use OBJ_REF_DELTA within the packfiles
* created by fast-import.
*
* oe must not be NULL. Such an oe usually comes from giving
* an unknown SHA-1 to find_object() or an undefined mark to
* find_mark(). Callers must test for this condition and use
* the standard read_sha1_file() when it happens.
*
* oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from
* find_mark(), where the mark was reloaded from an existing marks
* file and is referencing an object that this fast-import process
* instance did not write out to a packfile. Callers must test for
* this condition and use read_sha1_file() instead.
*/
static void *gfi_unpack_entry(
struct object_entry *oe,
unsigned long *sizep)
{
enum object_type type;
struct packed_git *p = all_packs[oe->pack_id];
if (p == pack_data && p->pack_size < (pack_size + 20)) {
/* The object is stored in the packfile we are writing to
* and we have modified it since the last time we scanned
* back to read a previously written object. If an old
* window covered [p->pack_size, p->pack_size + 20) its
* data is stale and is not valid. Closing all windows
* and updating the packfile length ensures we can read
* the newly written data.
*/
close_pack_windows(p);
sha1flush(pack_file);
/* We have to offer 20 bytes additional on the end of
* the packfile as the core unpacker code assumes the
* footer is present at the file end and must promise
* at least 20 bytes within any window it maps. But
* we don't actually create the footer here.
*/
p->pack_size = pack_size + 20;
}
return unpack_entry(p, oe->idx.offset, &type, sizep);
}
static const char *get_mode(const char *str, uint16_t *modep)
{
unsigned char c;
uint16_t mode = 0;
while ((c = *str++) != ' ') {
if (c < '0' || c > '7')
return NULL;
mode = (mode << 3) + (c - '0');
}
*modep = mode;
return str;
}
static void load_tree(struct tree_entry *root)
{
unsigned char *sha1 = root->versions[1].sha1;
struct object_entry *myoe;
struct tree_content *t;
unsigned long size;
char *buf;
const char *c;
root->tree = t = new_tree_content(8);
if (is_null_sha1(sha1))
return;
myoe = find_object(sha1);
if (myoe && myoe->pack_id != MAX_PACK_ID) {
if (myoe->type != OBJ_TREE)
die("Not a tree: %s", sha1_to_hex(sha1));
t->delta_depth = myoe->depth;
buf = gfi_unpack_entry(myoe, &size);
if (!buf)
die("Can't load tree %s", sha1_to_hex(sha1));
} else {
enum object_type type;
buf = read_sha1_file(sha1, &type, &size);
if (!buf || type != OBJ_TREE)
die("Can't load tree %s", sha1_to_hex(sha1));
}
c = buf;
while (c != (buf + size)) {
struct tree_entry *e = new_tree_entry();
if (t->entry_count == t->entry_capacity)
root->tree = t = grow_tree_content(t, t->entry_count);
t->entries[t->entry_count++] = e;
e->tree = NULL;
c = get_mode(c, &e->versions[1].mode);
if (!c)
die("Corrupt mode in %s", sha1_to_hex(sha1));
e->versions[0].mode = e->versions[1].mode;
e->name = to_atom(c, strlen(c));
c += e->name->str_len + 1;
hashcpy(e->versions[0].sha1, (unsigned char *)c);
hashcpy(e->versions[1].sha1, (unsigned char *)c);
c += 20;
}
free(buf);
}
static int tecmp0 (const void *_a, const void *_b)
{
struct tree_entry *a = *((struct tree_entry**)_a);
struct tree_entry *b = *((struct tree_entry**)_b);
return base_name_compare(
a->name->str_dat, a->name->str_len, a->versions[0].mode,
b->name->str_dat, b->name->str_len, b->versions[0].mode);
}
static int tecmp1 (const void *_a, const void *_b)
{
struct tree_entry *a = *((struct tree_entry**)_a);
struct tree_entry *b = *((struct tree_entry**)_b);
return base_name_compare(
a->name->str_dat, a->name->str_len, a->versions[1].mode,
b->name->str_dat, b->name->str_len, b->versions[1].mode);
}
static void mktree(struct tree_content *t, int v, struct strbuf *b)
{
size_t maxlen = 0;
unsigned int i;
if (!v)
qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
else
qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
for (i = 0; i < t->entry_count; i++) {
if (t->entries[i]->versions[v].mode)
maxlen += t->entries[i]->name->str_len + 34;
}
strbuf_reset(b);
strbuf_grow(b, maxlen);
for (i = 0; i < t->entry_count; i++) {
struct tree_entry *e = t->entries[i];
if (!e->versions[v].mode)
continue;
strbuf_addf(b, "%o %s%c",
(unsigned int)(e->versions[v].mode & ~NO_DELTA),
e->name->str_dat, '\0');
strbuf_add(b, e->versions[v].sha1, 20);
}
}
static void store_tree(struct tree_entry *root)
{
struct tree_content *t;
unsigned int i, j, del;
struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
struct object_entry *le = NULL;
if (!is_null_sha1(root->versions[1].sha1))
return;
if (!root->tree)
load_tree(root);
t = root->tree;
for (i = 0; i < t->entry_count; i++) {
if (t->entries[i]->tree)
store_tree(t->entries[i]);
}
if (!(root->versions[0].mode & NO_DELTA))
le = find_object(root->versions[0].sha1);
if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
mktree(t, 0, &old_tree);
lo.data = old_tree;
lo.offset = le->idx.offset;
lo.depth = t->delta_depth;
}
mktree(t, 1, &new_tree);
store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0);
t->delta_depth = lo.depth;
for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
struct tree_entry *e = t->entries[i];
if (e->versions[1].mode) {
e->versions[0].mode = e->versions[1].mode;
hashcpy(e->versions[0].sha1, e->versions[1].sha1);
t->entries[j++] = e;
} else {
release_tree_entry(e);
del++;
}
}
t->entry_count -= del;
}
static void tree_content_replace(
struct tree_entry *root,
const unsigned char *sha1,
const uint16_t mode,
struct tree_content *newtree)
{
if (!S_ISDIR(mode))
die("Root cannot be a non-directory");
hashclr(root->versions[0].sha1);
hashcpy(root->versions[1].sha1, sha1);
if (root->tree)
release_tree_content_recursive(root->tree);
root->tree = newtree;
}
static int tree_content_set(
struct tree_entry *root,
const char *p,
const unsigned char *sha1,
const uint16_t mode,
struct tree_content *subtree)
{
struct tree_content *t;
const char *slash1;
unsigned int i, n;
struct tree_entry *e;
slash1 = strchrnul(p, '/');
n = slash1 - p;
if (!n)
die("Empty path component found in input");
if (!*slash1 && !S_ISDIR(mode) && subtree)
die("Non-directories cannot have subtrees");
if (!root->tree)
load_tree(root);
t = root->tree;
for (i = 0; i < t->entry_count; i++) {
e = t->entries[i];
if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) {
if (!*slash1) {
if (!S_ISDIR(mode)
&& e->versions[1].mode == mode
&& !hashcmp(e->versions[1].sha1, sha1))
return 0;
e->versions[1].mode = mode;
hashcpy(e->versions[1].sha1, sha1);
if (e->tree)
release_tree_content_recursive(e->tree);
e->tree = subtree;
/*
* We need to leave e->versions[0].sha1 alone
* to avoid modifying the preimage tree used
* when writing out the parent directory.
* But after replacing the subdir with a
* completely different one, it's not a good
* delta base any more, and besides, we've
* thrown away the tree entries needed to
* make a delta against it.
*
* So let's just explicitly disable deltas
* for the subtree.
*/
if (S_ISDIR(e->versions[0].mode))
e->versions[0].mode |= NO_DELTA;
hashclr(root->versions[1].sha1);
return 1;
}
if (!S_ISDIR(e->versions[1].mode)) {
e->tree = new_tree_content(8);
e->versions[1].mode = S_IFDIR;
}
if (!e->tree)
load_tree(e);
if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
hashclr(root->versions[1].sha1);
return 1;
}
return 0;
}
}
if (t->entry_count == t->entry_capacity)
root->tree = t = grow_tree_content(t, t->entry_count);
e = new_tree_entry();
e->name = to_atom(p, n);
e->versions[0].mode = 0;
hashclr(e->versions[0].sha1);
t->entries[t->entry_count++] = e;
if (*slash1) {
e->tree = new_tree_content(8);
e->versions[1].mode = S_IFDIR;
tree_content_set(e, slash1 + 1, sha1, mode, subtree);
} else {
e->tree = subtree;
e->versions[1].mode = mode;
hashcpy(e->versions[1].sha1, sha1);
}
hashclr(root->versions[1].sha1);
return 1;
}
static int tree_content_remove(
struct tree_entry *root,
const char *p,
struct tree_entry *backup_leaf,
int allow_root)
{
struct tree_content *t;
const char *slash1;
unsigned int i, n;
struct tree_entry *e;
slash1 = strchrnul(p, '/');
n = slash1 - p;
if (!root->tree)
load_tree(root);
if (!*p && allow_root) {
e = root;
goto del_entry;
}
t = root->tree;
for (i = 0; i < t->entry_count; i++) {
e = t->entries[i];
if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) {
if (*slash1 && !S_ISDIR(e->versions[1].mode))
/*
* If p names a file in some subdirectory, and a
* file or symlink matching the name of the
* parent directory of p exists, then p cannot
* exist and need not be deleted.
*/
return 1;
if (!*slash1 || !S_ISDIR(e->versions[1].mode))
goto del_entry;
if (!e->tree)
load_tree(e);
if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
for (n = 0; n < e->tree->entry_count; n++) {
if (e->tree->entries[n]->versions[1].mode) {
hashclr(root->versions[1].sha1);
return 1;
}
}
backup_leaf = NULL;
goto del_entry;
}
return 0;
}
}
return 0;
del_entry:
if (backup_leaf)
memcpy(backup_leaf, e, sizeof(*backup_leaf));
else if (e->tree)
release_tree_content_recursive(e->tree);
e->tree = NULL;
e->versions[1].mode = 0;
hashclr(e->versions[1].sha1);
hashclr(root->versions[1].sha1);
return 1;
}
static int tree_content_get(
struct tree_entry *root,
const char *p,
struct tree_entry *leaf,
int allow_root)
{
struct tree_content *t;
const char *slash1;
unsigned int i, n;
struct tree_entry *e;
slash1 = strchrnul(p, '/');
n = slash1 - p;
if (!n && !allow_root)
die("Empty path component found in input");
if (!root->tree)
load_tree(root);
if (!n) {
e = root;
goto found_entry;
}
t = root->tree;
for (i = 0; i < t->entry_count; i++) {
e = t->entries[i];
if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) {
if (!*slash1)
goto found_entry;
if (!S_ISDIR(e->versions[1].mode))
return 0;
if (!e->tree)
load_tree(e);
return tree_content_get(e, slash1 + 1, leaf, 0);
}
}
return 0;
found_entry:
memcpy(leaf, e, sizeof(*leaf));
if (e->tree && is_null_sha1(e->versions[1].sha1))
leaf->tree = dup_tree_content(e->tree);
else
leaf->tree = NULL;
return 1;
}
static int update_branch(struct branch *b)
{
static const char *msg = "fast-import";
struct ref_transaction *transaction;
unsigned char old_sha1[20];
struct strbuf err = STRBUF_INIT;
if (is_null_sha1(b->sha1)) {
if (b->delete)
delete_ref(b->name, NULL, 0);
return 0;
}
if (read_ref(b->name, old_sha1))
hashclr(old_sha1);
if (!force_update && !is_null_sha1(old_sha1)) {
struct commit *old_cmit, *new_cmit;
old_cmit = lookup_commit_reference_gently(old_sha1, 0);
new_cmit = lookup_commit_reference_gently(b->sha1, 0);
if (!old_cmit || !new_cmit)
return error("Branch %s is missing commits.", b->name);
if (!in_merge_bases(old_cmit, new_cmit)) {
warning("Not updating %s"
" (new tip %s does not contain %s)",
b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
return -1;
}
}
transaction = ref_transaction_begin(&err);
if (!transaction ||
ref_transaction_update(transaction, b->name, b->sha1, old_sha1,
0, msg, &err) ||
ref_transaction_commit(transaction, &err)) {
ref_transaction_free(transaction);
error("%s", err.buf);
strbuf_release(&err);
return -1;
}
ref_transaction_free(transaction);
strbuf_release(&err);
return 0;
}
static void dump_branches(void)
{
unsigned int i;
struct branch *b;
for (i = 0; i < branch_table_sz; i++) {
for (b = branch_table[i]; b; b = b->table_next_branch)
failure |= update_branch(b);
}
}
static void dump_tags(void)
{
static const char *msg = "fast-import";
struct tag *t;
struct strbuf ref_name = STRBUF_INIT;
struct strbuf err = STRBUF_INIT;
struct ref_transaction *transaction;
transaction = ref_transaction_begin(&err);
if (!transaction) {
failure |= error("%s", err.buf);
goto cleanup;
}
for (t = first_tag; t; t = t->next_tag) {
strbuf_reset(&ref_name);
strbuf_addf(&ref_name, "refs/tags/%s", t->name);
if (ref_transaction_update(transaction, ref_name.buf,
t->sha1, NULL, 0, msg, &err)) {
failure |= error("%s", err.buf);
goto cleanup;
}
}
if (ref_transaction_commit(transaction, &err))
failure |= error("%s", err.buf);
cleanup:
ref_transaction_free(transaction);
strbuf_release(&ref_name);
strbuf_release(&err);
}
static void dump_marks_helper(FILE *f,
uintmax_t base,
struct mark_set *m)
{
uintmax_t k;
if (m->shift) {
for (k = 0; k < 1024; k++) {
if (m->data.sets[k])
dump_marks_helper(f, base + (k << m->shift),
m->data.sets[k]);
}
} else {
for (k = 0; k < 1024; k++) {
if (m->data.marked[k])
fprintf(f, ":%" PRIuMAX " %s\n", base + k,
sha1_to_hex(m->data.marked[k]->idx.sha1));
}
}
}
static void dump_marks(void)
{
static struct lock_file mark_lock;
FILE *f;
if (!export_marks_file)
return;
if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
failure |= error("Unable to write marks file %s: %s",
export_marks_file, strerror(errno));
return;
}
f = fdopen_lock_file(&mark_lock, "w");
if (!f) {
int saved_errno = errno;
rollback_lock_file(&mark_lock);
failure |= error("Unable to write marks file %s: %s",
export_marks_file, strerror(saved_errno));
return;
}
dump_marks_helper(f, 0, marks);
if (commit_lock_file(&mark_lock)) {
failure |= error("Unable to commit marks file %s: %s",
export_marks_file, strerror(errno));
return;
}
}
static void read_marks(void)
{
char line[512];
FILE *f = fopen(import_marks_file, "r");
if (f)
;
else if (import_marks_file_ignore_missing && errno == ENOENT)
return; /* Marks file does not exist */
else
die_errno("cannot read '%s'", import_marks_file);
while (fgets(line, sizeof(line), f)) {
uintmax_t mark;
char *end;
unsigned char sha1[20];
struct object_entry *e;
end = strchr(line, '\n');
if (line[0] != ':' || !end)
die("corrupt mark line: %s", line);
*end = 0;
mark = strtoumax(line + 1, &end, 10);
if (!mark || end == line + 1
|| *end != ' ' || get_sha1_hex(end + 1, sha1))
die("corrupt mark line: %s", line);
e = find_object(sha1);
if (!e) {
enum object_type type = sha1_object_info(sha1, NULL);
if (type < 0)
die("object not found: %s", sha1_to_hex(sha1));
e = insert_object(sha1);
e->type = type;
e->pack_id = MAX_PACK_ID;
e->idx.offset = 1; /* just not zero! */
}
insert_mark(mark, e);
}
fclose(f);
}
static int read_next_command(void)
{
static int stdin_eof = 0;
if (stdin_eof) {
unread_command_buf = 0;
return EOF;
}
for (;;) {
const char *p;
if (unread_command_buf) {
unread_command_buf = 0;
} else {
struct recent_command *rc;
strbuf_detach(&command_buf, NULL);
stdin_eof = strbuf_getline(&command_buf, stdin, '\n');
if (stdin_eof)
return EOF;
if (!seen_data_command
&& !starts_with(command_buf.buf, "feature ")
&& !starts_with(command_buf.buf, "option ")) {
parse_argv();
}
rc = rc_free;
if (rc)
rc_free = rc->next;
else {
rc = cmd_hist.next;
cmd_hist.next = rc->next;
cmd_hist.next->prev = &cmd_hist;
free(rc->buf);
}
rc->buf = command_buf.buf;
rc->prev = cmd_tail;
rc->next = cmd_hist.prev;
rc->prev->next = rc;
cmd_tail = rc;
}
if (skip_prefix(command_buf.buf, "get-mark ", &p)) {
parse_get_mark(p);
continue;
}
if (skip_prefix(command_buf.buf, "cat-blob ", &p)) {
parse_cat_blob(p);
continue;
}
if (command_buf.buf[0] == '#')
continue;
return 0;
}
}
static void skip_optional_lf(void)
{
int term_char = fgetc(stdin);
if (term_char != '\n' && term_char != EOF)
ungetc(term_char, stdin);
}
static void parse_mark(void)
{
const char *v;
if (skip_prefix(command_buf.buf, "mark :", &v)) {
next_mark = strtoumax(v, NULL, 10);
read_next_command();
}
else
next_mark = 0;
}
static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
{
const char *data;
strbuf_reset(sb);
if (!skip_prefix(command_buf.buf, "data ", &data))
die("Expected 'data n' command, found: %s", command_buf.buf);
if (skip_prefix(data, "<<", &data)) {
char *term = xstrdup(data);
size_t term_len = command_buf.len - (data - command_buf.buf);
strbuf_detach(&command_buf, NULL);
for (;;) {
if (strbuf_getline(&command_buf, stdin, '\n') == EOF)
die("EOF in data (terminator '%s' not found)", term);
if (term_len == command_buf.len
&& !strcmp(term, command_buf.buf))
break;
strbuf_addbuf(sb, &command_buf);
strbuf_addch(sb, '\n');
}
free(term);
}
else {
uintmax_t len = strtoumax(data, NULL, 10);
size_t n = 0, length = (size_t)len;
if (limit && limit < len) {
*len_res = len;
return 0;
}
if (length < len)
die("data is too large to use in this context");
while (n < length) {
size_t s = strbuf_fread(sb, length - n, stdin);
if (!s && feof(stdin))
die("EOF in data (%lu bytes remaining)",
(unsigned long)(length - n));
n += s;
}
}
skip_optional_lf();
return 1;
}
static int validate_raw_date(const char *src, struct strbuf *result)
{
const char *orig_src = src;
char *endp;
unsigned long num;
errno = 0;
num = strtoul(src, &endp, 10);
/* NEEDSWORK: perhaps check for reasonable values? */
if (errno || endp == src || *endp != ' ')
return -1;
src = endp + 1;
if (*src != '-' && *src != '+')
return -1;
num = strtoul(src + 1, &endp, 10);
if (errno || endp == src + 1 || *endp || 1400 < num)
return -1;
strbuf_addstr(result, orig_src);
return 0;
}
static char *parse_ident(const char *buf)
{
const char *ltgt;
size_t name_len;
struct strbuf ident = STRBUF_INIT;
/* ensure there is a space delimiter even if there is no name */
if (*buf == '<')
--buf;
ltgt = buf + strcspn(buf, "<>");
if (*ltgt != '<')
die("Missing < in ident string: %s", buf);
if (ltgt != buf && ltgt[-1] != ' ')
die("Missing space before < in ident string: %s", buf);
ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
if (*ltgt != '>')
die("Missing > in ident string: %s", buf);
ltgt++;
if (*ltgt != ' ')
die("Missing space after > in ident string: %s", buf);
ltgt++;
name_len = ltgt - buf;
strbuf_add(&ident, buf, name_len);
switch (whenspec) {
case WHENSPEC_RAW:
if (validate_raw_date(ltgt, &ident) < 0)
die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
break;
case WHENSPEC_RFC2822:
if (parse_date(ltgt, &ident) < 0)
die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
break;
case WHENSPEC_NOW:
if (strcmp("now", ltgt))
die("Date in ident must be 'now': %s", buf);
datestamp(&ident);
break;
}
return strbuf_detach(&ident, NULL);
}
static void parse_and_store_blob(
struct last_object *last,
unsigned char *sha1out,
uintmax_t mark)
{
static struct strbuf buf = STRBUF_INIT;
uintmax_t len;
if (parse_data(&buf, big_file_threshold, &len))
store_object(OBJ_BLOB, &buf, last, sha1out, mark);
else {
if (last) {
strbuf_release(&last->data);
last->offset = 0;
last->depth = 0;
}
stream_blob(len, sha1out, mark);
skip_optional_lf();
}
}
static void parse_new_blob(void)
{
read_next_command();
parse_mark();
parse_and_store_blob(&last_blob, NULL, next_mark);
}
static void unload_one_branch(void)
{
while (cur_active_branches
&& cur_active_branches >= max_active_branches) {
uintmax_t min_commit = ULONG_MAX;
struct branch *e, *l = NULL, *p = NULL;
for (e = active_branches; e; e = e->active_next_branch) {
if (e->last_commit < min_commit) {
p = l;
min_commit = e->last_commit;
}
l = e;
}
if (p) {
e = p->active_next_branch;
p->active_next_branch = e->active_next_branch;
} else {
e = active_branches;
active_branches = e->active_next_branch;
}
e->active = 0;
e->active_next_branch = NULL;
if (e->branch_tree.tree) {
release_tree_content_recursive(e->branch_tree.tree);
e->branch_tree.tree = NULL;
}
cur_active_branches--;
}
}
static void load_branch(struct branch *b)
{
load_tree(&b->branch_tree);
if (!b->active) {
b->active = 1;
b->active_next_branch = active_branches;
active_branches = b;
cur_active_branches++;
branch_load_count++;
}
}
static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
{
unsigned char fanout = 0;
while ((num_notes >>= 8))
fanout++;
return fanout;
}
static void construct_path_with_fanout(const char *hex_sha1,
unsigned char fanout, char *path)
{
unsigned int i = 0, j = 0;
if (fanout >= 20)
die("Too large fanout (%u)", fanout);
while (fanout) {
path[i++] = hex_sha1[j++];
path[i++] = hex_sha1[j++];
path[i++] = '/';
fanout--;
}
memcpy(path + i, hex_sha1 + j, 40 - j);
path[i + 40 - j] = '\0';
}
static uintmax_t do_change_note_fanout(
struct tree_entry *orig_root, struct tree_entry *root,
char *hex_sha1, unsigned int hex_sha1_len,
char *fullpath, unsigned int fullpath_len,
unsigned char fanout)
{
struct tree_content *t = root->tree;
struct tree_entry *e, leaf;
unsigned int i, tmp_hex_sha1_len, tmp_fullpath_len;
uintmax_t num_notes = 0;
unsigned char sha1[20];
char realpath[60];
for (i = 0; t && i < t->entry_count; i++) {
e = t->entries[i];
tmp_hex_sha1_len = hex_sha1_len + e->name->str_len;
tmp_fullpath_len = fullpath_len;
/*
* We're interested in EITHER existing note entries (entries
* with exactly 40 hex chars in path, not including directory
* separators), OR directory entries that may contain note
* entries (with < 40 hex chars in path).
* Also, each path component in a note entry must be a multiple
* of 2 chars.
*/
if (!e->versions[1].mode ||
tmp_hex_sha1_len > 40 ||
e->name->str_len % 2)
continue;
/* This _may_ be a note entry, or a subdir containing notes */
memcpy(hex_sha1 + hex_sha1_len, e->name->str_dat,
e->name->str_len);
if (tmp_fullpath_len)
fullpath[tmp_fullpath_len++] = '/';
memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
e->name->str_len);
tmp_fullpath_len += e->name->str_len;
fullpath[tmp_fullpath_len] = '\0';
if (tmp_hex_sha1_len == 40 && !get_sha1_hex(hex_sha1, sha1)) {
/* This is a note entry */
if (fanout == 0xff) {
/* Counting mode, no rename */
num_notes++;
continue;
}
construct_path_with_fanout(hex_sha1, fanout, realpath);
if (!strcmp(fullpath, realpath)) {
/* Note entry is in correct location */
num_notes++;
continue;
}
/* Rename fullpath to realpath */
if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
die("Failed to remove path %s", fullpath);
tree_content_set(orig_root, realpath,
leaf.versions[1].sha1,
leaf.versions[1].mode,
leaf.tree);
} else if (S_ISDIR(e->versions[1].mode)) {
/* This is a subdir that may contain note entries */
if (!e->tree)
load_tree(e);
num_notes += do_change_note_fanout(orig_root, e,
hex_sha1, tmp_hex_sha1_len,
fullpath, tmp_fullpath_len, fanout);
}
/* The above may have reallocated the current tree_content */
t = root->tree;
}
return num_notes;
}
static uintmax_t change_note_fanout(struct tree_entry *root,
unsigned char fanout)
{
char hex_sha1[40], path[60];
return do_change_note_fanout(root, root, hex_sha1, 0, path, 0, fanout);
}
/*
* Given a pointer into a string, parse a mark reference:
*
* idnum ::= ':' bigint;
*
* Return the first character after the value in *endptr.
*
* Complain if the following character is not what is expected,
* either a space or end of the string.
*/
static uintmax_t parse_mark_ref(const char *p, char **endptr)
{
uintmax_t mark;
assert(*p == ':');
p++;
mark = strtoumax(p, endptr, 10);
if (*endptr == p)
die("No value after ':' in mark: %s", command_buf.buf);
return mark;
}
/*
* Parse the mark reference, and complain if this is not the end of
* the string.
*/
static uintmax_t parse_mark_ref_eol(const char *p)
{
char *end;
uintmax_t mark;
mark = parse_mark_ref(p, &end);
if (*end != '\0')
die("Garbage after mark: %s", command_buf.buf);
return mark;
}
/*
* Parse the mark reference, demanding a trailing space. Return a
* pointer to the space.
*/
static uintmax_t parse_mark_ref_space(const char **p)
{
uintmax_t mark;
char *end;
mark = parse_mark_ref(*p, &end);
if (*end++ != ' ')
die("Missing space after mark: %s", command_buf.buf);
*p = end;
return mark;
}
static void file_change_m(const char *p, struct branch *b)
{
static struct strbuf uq = STRBUF_INIT;
const char *endp;
struct object_entry *oe;
unsigned char sha1[20];
uint16_t mode, inline_data = 0;
p = get_mode(p, &mode);
if (!p)
die("Corrupt mode: %s", command_buf.buf);
switch (mode) {
case 0644:
case 0755:
mode |= S_IFREG;
case S_IFREG | 0644:
case S_IFREG | 0755:
case S_IFLNK:
case S_IFDIR:
case S_IFGITLINK:
/* ok */
break;
default:
die("Corrupt mode: %s", command_buf.buf);
}
if (*p == ':') {
oe = find_mark(parse_mark_ref_space(&p));
hashcpy(sha1, oe->idx.sha1);
} else if (skip_prefix(p, "inline ", &p)) {
inline_data = 1;
oe = NULL; /* not used with inline_data, but makes gcc happy */
} else {
if (get_sha1_hex(p, sha1))
die("Invalid dataref: %s", command_buf.buf);
oe = find_object(sha1);
p += 40;
if (*p++ != ' ')
die("Missing space after SHA1: %s", command_buf.buf);
}
strbuf_reset(&uq);
if (!unquote_c_style(&uq, p, &endp)) {
if (*endp)
die("Garbage after path in: %s", command_buf.buf);
p = uq.buf;
}
/* Git does not track empty, non-toplevel directories. */
if (S_ISDIR(mode) && !hashcmp(sha1, EMPTY_TREE_SHA1_BIN) && *p) {
tree_content_remove(&b->branch_tree, p, NULL, 0);
return;
}
if (S_ISGITLINK(mode)) {
if (inline_data)
die("Git links cannot be specified 'inline': %s",
command_buf.buf);
else if (oe) {
if (oe->type != OBJ_COMMIT)
die("Not a commit (actually a %s): %s",
typename(oe->type), command_buf.buf);
}
/*
* Accept the sha1 without checking; it expected to be in
* another repository.
*/
} else if (inline_data) {
if (S_ISDIR(mode))
die("Directories cannot be specified 'inline': %s",
command_buf.buf);
if (p != uq.buf) {
strbuf_addstr(&uq, p);
p = uq.buf;
}
read_next_command();
parse_and_store_blob(&last_blob, sha1, 0);
} else {
enum object_type expected = S_ISDIR(mode) ?
OBJ_TREE: OBJ_BLOB;
enum object_type type = oe ? oe->type :
sha1_object_info(sha1, NULL);
if (type < 0)
die("%s not found: %s",
S_ISDIR(mode) ? "Tree" : "Blob",
command_buf.buf);
if (type != expected)
die("Not a %s (actually a %s): %s",
typename(expected), typename(type),
command_buf.buf);
}
if (!*p) {
tree_content_replace(&b->branch_tree, sha1, mode, NULL);
return;
}
tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
}
static void file_change_d(const char *p, struct branch *b)
{
static struct strbuf uq = STRBUF_INIT;
const char *endp;
strbuf_reset(&uq);
if (!unquote_c_style(&uq, p, &endp)) {
if (*endp)
die("Garbage after path in: %s", command_buf.buf);
p = uq.buf;
}
tree_content_remove(&b->branch_tree, p, NULL, 1);
}
static void file_change_cr(const char *s, struct branch *b, int rename)
{
const char *d;
static struct strbuf s_uq = STRBUF_INIT;
static struct strbuf d_uq = STRBUF_INIT;
const char *endp;
struct tree_entry leaf;
strbuf_reset(&s_uq);
if (!unquote_c_style(&s_uq, s, &endp)) {
if (*endp != ' ')
die("Missing space after source: %s", command_buf.buf);
} else {
endp = strchr(s, ' ');
if (!endp)
die("Missing space after source: %s", command_buf.buf);
strbuf_add(&s_uq, s, endp - s);
}
s = s_uq.buf;
endp++;
if (!*endp)
die("Missing dest: %s", command_buf.buf);
d = endp;
strbuf_reset(&d_uq);
if (!unquote_c_style(&d_uq, d, &endp)) {
if (*endp)
die("Garbage after dest in: %s", command_buf.buf);
d = d_uq.buf;
}
memset(&leaf, 0, sizeof(leaf));
if (rename)
tree_content_remove(&b->branch_tree, s, &leaf, 1);
else
tree_content_get(&b->branch_tree, s, &leaf, 1);
if (!leaf.versions[1].mode)
die("Path %s not in branch", s);
if (!*d) { /* C "path/to/subdir" "" */
tree_content_replace(&b->branch_tree,
leaf.versions[1].sha1,
leaf.versions[1].mode,
leaf.tree);
return;
}
tree_content_set(&b->branch_tree, d,
leaf.versions[1].sha1,
leaf.versions[1].mode,
leaf.tree);
}
static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
{
static struct strbuf uq = STRBUF_INIT;
struct object_entry *oe;
struct branch *s;
unsigned char sha1[20], commit_sha1[20];
char path[60];
uint16_t inline_data = 0;
unsigned char new_fanout;
/*
* When loading a branch, we don't traverse its tree to count the real
* number of notes (too expensive to do this for all non-note refs).
* This means that recently loaded notes refs might incorrectly have
* b->num_notes == 0, and consequently, old_fanout might be wrong.
*
* Fix this by traversing the tree and counting the number of notes
* when b->num_notes == 0. If the notes tree is truly empty, the
* calculation should not take long.
*/
if (b->num_notes == 0 && *old_fanout == 0) {
/* Invoke change_note_fanout() in "counting mode". */
b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
*old_fanout = convert_num_notes_to_fanout(b->num_notes);
}
/* Now parse the notemodify command. */
/* <dataref> or 'inline' */
if (*p == ':') {
oe = find_mark(parse_mark_ref_space(&p));
hashcpy(sha1, oe->idx.sha1);
} else if (skip_prefix(p, "inline ", &p)) {
inline_data = 1;
oe = NULL; /* not used with inline_data, but makes gcc happy */
} else {
if (get_sha1_hex(p, sha1))
die("Invalid dataref: %s", command_buf.buf);
oe = find_object(sha1);
p += 40;
if (*p++ != ' ')
die("Missing space after SHA1: %s", command_buf.buf);
}
/* <commit-ish> */
s = lookup_branch(p);
if (s) {
if (is_null_sha1(s->sha1))
die("Can't add a note on empty branch.");
hashcpy(commit_sha1, s->sha1);
} else if (*p == ':') {
uintmax_t commit_mark = parse_mark_ref_eol(p);
struct object_entry *commit_oe = find_mark(commit_mark);
if (commit_oe->type != OBJ_COMMIT)
die("Mark :%" PRIuMAX " not a commit", commit_mark);
hashcpy(commit_sha1, commit_oe->idx.sha1);
} else if (!get_sha1(p, commit_sha1)) {
unsigned long size;
char *buf = read_object_with_reference(commit_sha1,
commit_type, &size, commit_sha1);
if (!buf || size < 46)
die("Not a valid commit: %s", p);
free(buf);
} else
die("Invalid ref name or SHA1 expression: %s", p);
if (inline_data) {
if (p != uq.buf) {
strbuf_addstr(&uq, p);
p = uq.buf;
}
read_next_command();
parse_and_store_blob(&last_blob, sha1, 0);
} else if (oe) {
if (oe->type != OBJ_BLOB)
die("Not a blob (actually a %s): %s",
typename(oe->type), command_buf.buf);
} else if (!is_null_sha1(sha1)) {
enum object_type type = sha1_object_info(sha1, NULL);
if (type < 0)
die("Blob not found: %s", command_buf.buf);
if (type != OBJ_BLOB)
die("Not a blob (actually a %s): %s",
typename(type), command_buf.buf);
}
construct_path_with_fanout(sha1_to_hex(commit_sha1), *old_fanout, path);
if (tree_content_remove(&b->branch_tree, path, NULL, 0))
b->num_notes--;
if (is_null_sha1(sha1))
return; /* nothing to insert */
b->num_notes++;
new_fanout = convert_num_notes_to_fanout(b->num_notes);
construct_path_with_fanout(sha1_to_hex(commit_sha1), new_fanout, path);
tree_content_set(&b->branch_tree, path, sha1, S_IFREG | 0644, NULL);
}
static void file_change_deleteall(struct branch *b)
{
release_tree_content_recursive(b->branch_tree.tree);
hashclr(b->branch_tree.versions[0].sha1);
hashclr(b->branch_tree.versions[1].sha1);
load_tree(&b->branch_tree);
b->num_notes = 0;
}
static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
{
if (!buf || size < 46)
die("Not a valid commit: %s", sha1_to_hex(b->sha1));
if (memcmp("tree ", buf, 5)
|| get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
die("The commit %s is corrupt", sha1_to_hex(b->sha1));
hashcpy(b->branch_tree.versions[0].sha1,
b->branch_tree.versions[1].sha1);
}
static void parse_from_existing(struct branch *b)
{
if (is_null_sha1(b->sha1)) {
hashclr(b->branch_tree.versions[0].sha1);
hashclr(b->branch_tree.versions[1].sha1);
} else {
unsigned long size;
char *buf;
buf = read_object_with_reference(b->sha1,
commit_type, &size, b->sha1);
parse_from_commit(b, buf, size);
free(buf);
}
}
static int parse_from(struct branch *b)
{
const char *from;
struct branch *s;
unsigned char sha1[20];
if (!skip_prefix(command_buf.buf, "from ", &from))
return 0;
hashcpy(sha1, b->branch_tree.versions[1].sha1);
s = lookup_branch(from);
if (b == s)
die("Can't create a branch from itself: %s", b->name);
else if (s) {
unsigned char *t = s->branch_tree.versions[1].sha1;
hashcpy(b->sha1, s->sha1);
hashcpy(b->branch_tree.versions[0].sha1, t);
hashcpy(b->branch_tree.versions[1].sha1, t);
} else if (*from == ':') {
uintmax_t idnum = parse_mark_ref_eol(from);
struct object_entry *oe = find_mark(idnum);
if (oe->type != OBJ_COMMIT)
die("Mark :%" PRIuMAX " not a commit", idnum);
if (hashcmp(b->sha1, oe->idx.sha1)) {
hashcpy(b->sha1, oe->idx.sha1);
if (oe->pack_id != MAX_PACK_ID) {
unsigned long size;
char *buf = gfi_unpack_entry(oe, &size);
parse_from_commit(b, buf, size);
free(buf);
} else
parse_from_existing(b);
}
} else if (!get_sha1(from, b->sha1)) {
parse_from_existing(b);
if (is_null_sha1(b->sha1))
b->delete = 1;
}
else
die("Invalid ref name or SHA1 expression: %s", from);
if (b->branch_tree.tree && hashcmp(sha1, b->branch_tree.versions[1].sha1)) {
release_tree_content_recursive(b->branch_tree.tree);
b->branch_tree.tree = NULL;
}
read_next_command();
return 1;
}
static struct hash_list *parse_merge(unsigned int *count)
{
struct hash_list *list = NULL, **tail = &list, *n;
const char *from;
struct branch *s;
*count = 0;
while (skip_prefix(command_buf.buf, "merge ", &from)) {
n = xmalloc(sizeof(*n));
s = lookup_branch(from);
if (s)
hashcpy(n->sha1, s->sha1);
else if (*from == ':') {
uintmax_t idnum = parse_mark_ref_eol(from);
struct object_entry *oe = find_mark(idnum);
if (oe->type != OBJ_COMMIT)
die("Mark :%" PRIuMAX " not a commit", idnum);
hashcpy(n->sha1, oe->idx.sha1);
} else if (!get_sha1(from, n->sha1)) {
unsigned long size;
char *buf = read_object_with_reference(n->sha1,
commit_type, &size, n->sha1);
if (!buf || size < 46)
die("Not a valid commit: %s", from);
free(buf);
} else
die("Invalid ref name or SHA1 expression: %s", from);
n->next = NULL;
*tail = n;
tail = &n->next;
(*count)++;
read_next_command();
}
return list;
}
static void parse_new_commit(const char *arg)
{
static struct strbuf msg = STRBUF_INIT;
struct branch *b;
char *author = NULL;
char *committer = NULL;
struct hash_list *merge_list = NULL;
unsigned int merge_count;
unsigned char prev_fanout, new_fanout;
const char *v;
b = lookup_branch(arg);
if (!b)
b = new_branch(arg);
read_next_command();
parse_mark();
if (skip_prefix(command_buf.buf, "author ", &v)) {
author = parse_ident(v);
read_next_command();
}
if (skip_prefix(command_buf.buf, "committer ", &v)) {
committer = parse_ident(v);
read_next_command();
}
if (!committer)
die("Expected committer but didn't get one");
parse_data(&msg, 0, NULL);
read_next_command();
parse_from(b);
merge_list = parse_merge(&merge_count);
/* ensure the branch is active/loaded */
if (!b->branch_tree.tree || !max_active_branches) {
unload_one_branch();
load_branch(b);
}
prev_fanout = convert_num_notes_to_fanout(b->num_notes);
/* file_change* */
while (command_buf.len > 0) {
if (skip_prefix(command_buf.buf, "M ", &v))
file_change_m(v, b);
else if (skip_prefix(command_buf.buf, "D ", &v))
file_change_d(v, b);
else if (skip_prefix(command_buf.buf, "R ", &v))
file_change_cr(v, b, 1);
else if (skip_prefix(command_buf.buf, "C ", &v))
file_change_cr(v, b, 0);
else if (skip_prefix(command_buf.buf, "N ", &v))
note_change_n(v, b, &prev_fanout);
else if (!strcmp("deleteall", command_buf.buf))
file_change_deleteall(b);
else if (skip_prefix(command_buf.buf, "ls ", &v))
parse_ls(v, b);
else {
unread_command_buf = 1;
break;
}
if (read_next_command() == EOF)
break;
}
new_fanout = convert_num_notes_to_fanout(b->num_notes);
if (new_fanout != prev_fanout)
b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
/* build the tree and the commit */
store_tree(&b->branch_tree);
hashcpy(b->branch_tree.versions[0].sha1,
b->branch_tree.versions[1].sha1);
strbuf_reset(&new_data);
strbuf_addf(&new_data, "tree %s\n",
sha1_to_hex(b->branch_tree.versions[1].sha1));
if (!is_null_sha1(b->sha1))
strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
while (merge_list) {
struct hash_list *next = merge_list->next;
strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
free(merge_list);
merge_list = next;
}
strbuf_addf(&new_data,
"author %s\n"
"committer %s\n"
"\n",
author ? author : committer, committer);
strbuf_addbuf(&new_data, &msg);
free(author);
free(committer);
if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
b->pack_id = pack_id;
b->last_commit = object_count_by_type[OBJ_COMMIT];
}
static void parse_new_tag(const char *arg)
{
static struct strbuf msg = STRBUF_INIT;
const char *from;
char *tagger;
struct branch *s;
struct tag *t;
uintmax_t from_mark = 0;
unsigned char sha1[20];
enum object_type type;
const char *v;
t = pool_alloc(sizeof(struct tag));
memset(t, 0, sizeof(struct tag));
t->name = pool_strdup(arg);
if (last_tag)
last_tag->next_tag = t;
else
first_tag = t;
last_tag = t;
read_next_command();
/* from ... */
if (!skip_prefix(command_buf.buf, "from ", &from))
die("Expected from command, got %s", command_buf.buf);
s = lookup_branch(from);
if (s) {
if (is_null_sha1(s->sha1))
die("Can't tag an empty branch.");
hashcpy(sha1, s->sha1);
type = OBJ_COMMIT;
} else if (*from == ':') {
struct object_entry *oe;
from_mark = parse_mark_ref_eol(from);
oe = find_mark(from_mark);
type = oe->type;
hashcpy(sha1, oe->idx.sha1);
} else if (!get_sha1(from, sha1)) {
struct object_entry *oe = find_object(sha1);
if (!oe) {
type = sha1_object_info(sha1, NULL);
if (type < 0)
die("Not a valid object: %s", from);
} else
type = oe->type;
} else
die("Invalid ref name or SHA1 expression: %s", from);
read_next_command();
/* tagger ... */
if (skip_prefix(command_buf.buf, "tagger ", &v)) {
tagger = parse_ident(v);
read_next_command();
} else
tagger = NULL;
/* tag payload/message */
parse_data(&msg, 0, NULL);
/* build the tag object */
strbuf_reset(&new_data);
strbuf_addf(&new_data,
"object %s\n"
"type %s\n"
"tag %s\n",
sha1_to_hex(sha1), typename(type), t->name);
if (tagger)
strbuf_addf(&new_data,
"tagger %s\n", tagger);
strbuf_addch(&new_data, '\n');
strbuf_addbuf(&new_data, &msg);
free(tagger);
if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
t->pack_id = MAX_PACK_ID;
else
t->pack_id = pack_id;
}
static void parse_reset_branch(const char *arg)
{
struct branch *b;
b = lookup_branch(arg);
if (b) {
hashclr(b->sha1);
hashclr(b->branch_tree.versions[0].sha1);
hashclr(b->branch_tree.versions[1].sha1);
if (b->branch_tree.tree) {
release_tree_content_recursive(b->branch_tree.tree);
b->branch_tree.tree = NULL;
}
}
else
b = new_branch(arg);
read_next_command();
parse_from(b);
if (command_buf.len > 0)
unread_command_buf = 1;
}
static void cat_blob_write(const char *buf, unsigned long size)
{
if (write_in_full(cat_blob_fd, buf, size) != size)
die_errno("Write to frontend failed");
}
static void cat_blob(struct object_entry *oe, unsigned char sha1[20])
{
struct strbuf line = STRBUF_INIT;
unsigned long size;
enum object_type type = 0;
char *buf;
if (!oe || oe->pack_id == MAX_PACK_ID) {
buf = read_sha1_file(sha1, &type, &size);
} else {
type = oe->type;
buf = gfi_unpack_entry(oe, &size);
}
/*
* Output based on batch_one_object() from cat-file.c.
*/
if (type <= 0) {
strbuf_reset(&line);
strbuf_addf(&line, "%s missing\n", sha1_to_hex(sha1));
cat_blob_write(line.buf, line.len);
strbuf_release(&line);
free(buf);
return;
}
if (!buf)
die("Can't read object %s", sha1_to_hex(sha1));
if (type != OBJ_BLOB)
die("Object %s is a %s but a blob was expected.",
sha1_to_hex(sha1), typename(type));
strbuf_reset(&line);
strbuf_addf(&line, "%s %s %lu\n", sha1_to_hex(sha1),
typename(type), size);
cat_blob_write(line.buf, line.len);
strbuf_release(&line);
cat_blob_write(buf, size);
cat_blob_write("\n", 1);
if (oe && oe->pack_id == pack_id) {
last_blob.offset = oe->idx.offset;
strbuf_attach(&last_blob.data, buf, size, size);
last_blob.depth = oe->depth;
} else
free(buf);
}
static void parse_get_mark(const char *p)
{
struct object_entry *oe = oe;
char output[42];
/* get-mark SP <object> LF */
if (*p != ':')
die("Not a mark: %s", p);
oe = find_mark(parse_mark_ref_eol(p));
if (!oe)
die("Unknown mark: %s", command_buf.buf);
snprintf(output, sizeof(output), "%s\n", sha1_to_hex(oe->idx.sha1));
cat_blob_write(output, 41);
}
static void parse_cat_blob(const char *p)
{
struct object_entry *oe = oe;
unsigned char sha1[20];
/* cat-blob SP <object> LF */
if (*p == ':') {
oe = find_mark(parse_mark_ref_eol(p));
if (!oe)
die("Unknown mark: %s", command_buf.buf);
hashcpy(sha1, oe->idx.sha1);
} else {
if (get_sha1_hex(p, sha1))
die("Invalid dataref: %s", command_buf.buf);
if (p[40])
die("Garbage after SHA1: %s", command_buf.buf);
oe = find_object(sha1);
}
cat_blob(oe, sha1);
}
static struct object_entry *dereference(struct object_entry *oe,
unsigned char sha1[20])
{
unsigned long size;
char *buf = NULL;
if (!oe) {
enum object_type type = sha1_object_info(sha1, NULL);
if (type < 0)
die("object not found: %s", sha1_to_hex(sha1));
/* cache it! */
oe = insert_object(sha1);
oe->type = type;
oe->pack_id = MAX_PACK_ID;
oe->idx.offset = 1;
}
switch (oe->type) {
case OBJ_TREE: /* easy case. */
return oe;
case OBJ_COMMIT:
case OBJ_TAG:
break;
default:
die("Not a tree-ish: %s", command_buf.buf);
}
if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */
buf = gfi_unpack_entry(oe, &size);
} else {
enum object_type unused;
buf = read_sha1_file(sha1, &unused, &size);
}
if (!buf)
die("Can't load object %s", sha1_to_hex(sha1));
/* Peel one layer. */
switch (oe->type) {
case OBJ_TAG:
if (size < 40 + strlen("object ") ||
get_sha1_hex(buf + strlen("object "), sha1))
die("Invalid SHA1 in tag: %s", command_buf.buf);
break;
case OBJ_COMMIT:
if (size < 40 + strlen("tree ") ||
get_sha1_hex(buf + strlen("tree "), sha1))
die("Invalid SHA1 in commit: %s", command_buf.buf);
}
free(buf);
return find_object(sha1);
}
static struct object_entry *parse_treeish_dataref(const char **p)
{
unsigned char sha1[20];
struct object_entry *e;
if (**p == ':') { /* <mark> */
e = find_mark(parse_mark_ref_space(p));
if (!e)
die("Unknown mark: %s", command_buf.buf);
hashcpy(sha1, e->idx.sha1);
} else { /* <sha1> */
if (get_sha1_hex(*p, sha1))
die("Invalid dataref: %s", command_buf.buf);
e = find_object(sha1);
*p += 40;
if (*(*p)++ != ' ')
die("Missing space after tree-ish: %s", command_buf.buf);
}
while (!e || e->type != OBJ_TREE)
e = dereference(e, sha1);
return e;
}
static void print_ls(int mode, const unsigned char *sha1, const char *path)
{
static struct strbuf line = STRBUF_INIT;
/* See show_tree(). */
const char *type =
S_ISGITLINK(mode) ? commit_type :
S_ISDIR(mode) ? tree_type :
blob_type;
if (!mode) {
/* missing SP path LF */
strbuf_reset(&line);
strbuf_addstr(&line, "missing ");
quote_c_style(path, &line, NULL, 0);
strbuf_addch(&line, '\n');
} else {
/* mode SP type SP object_name TAB path LF */
strbuf_reset(&line);
strbuf_addf(&line, "%06o %s %s\t",
mode & ~NO_DELTA, type, sha1_to_hex(sha1));
quote_c_style(path, &line, NULL, 0);
strbuf_addch(&line, '\n');
}
cat_blob_write(line.buf, line.len);
}
static void parse_ls(const char *p, struct branch *b)
{
struct tree_entry *root = NULL;
struct tree_entry leaf = {NULL};
/* ls SP (<tree-ish> SP)? <path> */
if (*p == '"') {
if (!b)
die("Not in a commit: %s", command_buf.buf);
root = &b->branch_tree;
} else {
struct object_entry *e = parse_treeish_dataref(&p);
root = new_tree_entry();
hashcpy(root->versions[1].sha1, e->idx.sha1);
if (!is_null_sha1(root->versions[1].sha1))
root->versions[1].mode = S_IFDIR;
load_tree(root);
}
if (*p == '"') {
static struct strbuf uq = STRBUF_INIT;
const char *endp;
strbuf_reset(&uq);
if (unquote_c_style(&uq, p, &endp))
die("Invalid path: %s", command_buf.buf);
if (*endp)
die("Garbage after path in: %s", command_buf.buf);
p = uq.buf;
}
tree_content_get(root, p, &leaf, 1);
/*
* A directory in preparation would have a sha1 of zero
* until it is saved. Save, for simplicity.
*/
if (S_ISDIR(leaf.versions[1].mode))
store_tree(&leaf);
print_ls(leaf.versions[1].mode, leaf.versions[1].sha1, p);
if (leaf.tree)
release_tree_content_recursive(leaf.tree);
if (!b || root != &b->branch_tree)
release_tree_entry(root);
}
static void checkpoint(void)
{
checkpoint_requested = 0;
if (object_count) {
cycle_packfile();
dump_branches();
dump_tags();
dump_marks();
}
}
static void parse_checkpoint(void)
{
checkpoint_requested = 1;
skip_optional_lf();
}
static void parse_progress(void)
{
fwrite(command_buf.buf, 1, command_buf.len, stdout);
fputc('\n', stdout);
fflush(stdout);
skip_optional_lf();
}
static char* make_fast_import_path(const char *path)
{
if (!relative_marks_paths || is_absolute_path(path))
return xstrdup(path);
return xstrdup(git_path("info/fast-import/%s", path));
}
static void option_import_marks(const char *marks,
int from_stream, int ignore_missing)
{
if (import_marks_file) {
if (from_stream)
die("Only one import-marks command allowed per stream");
/* read previous mark file */
if(!import_marks_file_from_stream)
read_marks();
}
import_marks_file = make_fast_import_path(marks);
safe_create_leading_directories_const(import_marks_file);
import_marks_file_from_stream = from_stream;
import_marks_file_ignore_missing = ignore_missing;
}
static void option_date_format(const char *fmt)
{
if (!strcmp(fmt, "raw"))
whenspec = WHENSPEC_RAW;
else if (!strcmp(fmt, "rfc2822"))
whenspec = WHENSPEC_RFC2822;
else if (!strcmp(fmt, "now"))
whenspec = WHENSPEC_NOW;
else
die("unknown --date-format argument %s", fmt);
}
static unsigned long ulong_arg(const char *option, const char *arg)
{
char *endptr;
unsigned long rv = strtoul(arg, &endptr, 0);
if (strchr(arg, '-') || endptr == arg || *endptr)
die("%s: argument must be a non-negative integer", option);
return rv;
}
static void option_depth(const char *depth)
{
max_depth = ulong_arg("--depth", depth);
if (max_depth > MAX_DEPTH)
die("--depth cannot exceed %u", MAX_DEPTH);
}
static void option_active_branches(const char *branches)
{
max_active_branches = ulong_arg("--active-branches", branches);
}
static void option_export_marks(const char *marks)
{
export_marks_file = make_fast_import_path(marks);
safe_create_leading_directories_const(export_marks_file);
}
static void option_cat_blob_fd(const char *fd)
{
unsigned long n = ulong_arg("--cat-blob-fd", fd);
if (n > (unsigned long) INT_MAX)
die("--cat-blob-fd cannot exceed %d", INT_MAX);
cat_blob_fd = (int) n;
}
static void option_export_pack_edges(const char *edges)
{
if (pack_edges)
fclose(pack_edges);
pack_edges = fopen(edges, "a");
if (!pack_edges)
die_errno("Cannot open '%s'", edges);
}
static int parse_one_option(const char *option)
{
if (skip_prefix(option, "max-pack-size=", &option)) {
unsigned long v;
if (!git_parse_ulong(option, &v))
return 0;
if (v < 8192) {
warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
v *= 1024 * 1024;
} else if (v < 1024 * 1024) {
warning("minimum max-pack-size is 1 MiB");
v = 1024 * 1024;
}
max_packsize = v;
} else if (skip_prefix(option, "big-file-threshold=", &option)) {
unsigned long v;
if (!git_parse_ulong(option, &v))
return 0;
big_file_threshold = v;
} else if (skip_prefix(option, "depth=", &option)) {
option_depth(option);
} else if (skip_prefix(option, "active-branches=", &option)) {
option_active_branches(option);
} else if (skip_prefix(option, "export-pack-edges=", &option)) {
option_export_pack_edges(option);
} else if (starts_with(option, "quiet")) {
show_stats = 0;
} else if (starts_with(option, "stats")) {
show_stats = 1;
} else {
return 0;
}
return 1;
}
static int parse_one_feature(const char *feature, int from_stream)
{
const char *arg;
if (skip_prefix(feature, "date-format=", &arg)) {
option_date_format(arg);
} else if (skip_prefix(feature, "import-marks=", &arg)) {
option_import_marks(arg, from_stream, 0);
} else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
option_import_marks(arg, from_stream, 1);
} else if (skip_prefix(feature, "export-marks=", &arg)) {
option_export_marks(arg);
} else if (!strcmp(feature, "get-mark")) {
; /* Don't die - this feature is supported */
} else if (!strcmp(feature, "cat-blob")) {
; /* Don't die - this feature is supported */
} else if (!strcmp(feature, "relative-marks")) {
relative_marks_paths = 1;
} else if (!strcmp(feature, "no-relative-marks")) {
relative_marks_paths = 0;
} else if (!strcmp(feature, "done")) {
require_explicit_termination = 1;
} else if (!strcmp(feature, "force")) {
force_update = 1;
} else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
; /* do nothing; we have the feature */
} else {
return 0;
}
return 1;
}
static void parse_feature(const char *feature)
{
if (seen_data_command)
die("Got feature command '%s' after data command", feature);
if (parse_one_feature(feature, 1))
return;
die("This version of fast-import does not support feature %s.", feature);
}
static void parse_option(const char *option)
{
if (seen_data_command)
die("Got option command '%s' after data command", option);
if (parse_one_option(option))
return;
die("This version of fast-import does not support option: %s", option);
}
static void git_pack_config(void)
{
int indexversion_value;
unsigned long packsizelimit_value;
if (!git_config_get_ulong("pack.depth", &max_depth)) {
if (max_depth > MAX_DEPTH)
max_depth = MAX_DEPTH;
}
if (!git_config_get_int("pack.compression", &pack_compression_level)) {
if (pack_compression_level == -1)
pack_compression_level = Z_DEFAULT_COMPRESSION;
else if (pack_compression_level < 0 ||
pack_compression_level > Z_BEST_COMPRESSION)
git_die_config("pack.compression",
"bad pack compression level %d", pack_compression_level);
pack_compression_seen = 1;
}
if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
pack_idx_opts.version = indexversion_value;
if (pack_idx_opts.version > 2)
git_die_config("pack.indexversion",
"bad pack.indexversion=%"PRIu32, pack_idx_opts.version);
}
if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
max_packsize = packsizelimit_value;
git_config(git_default_config, NULL);
}
static const char fast_import_usage[] =
"git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
static void parse_argv(void)
{
unsigned int i;
for (i = 1; i < global_argc; i++) {
const char *a = global_argv[i];
if (*a != '-' || !strcmp(a, "--"))
break;
if (!skip_prefix(a, "--", &a))
die("unknown option %s", a);
if (parse_one_option(a))
continue;
if (parse_one_feature(a, 0))
continue;
if (skip_prefix(a, "cat-blob-fd=", &a)) {
option_cat_blob_fd(a);
continue;
}
die("unknown option --%s", a);
}
if (i != global_argc)
usage(fast_import_usage);
seen_data_command = 1;
if (import_marks_file)
read_marks();
}
int main(int argc, char **argv)
{
unsigned int i;
git_extract_argv0_path(argv[0]);
git_setup_gettext();
if (argc == 2 && !strcmp(argv[1], "-h"))
usage(fast_import_usage);
setup_git_directory();
reset_pack_idx_option(&pack_idx_opts);
git_pack_config();
if (!pack_compression_seen && core_compression_seen)
pack_compression_level = core_compression_level;
alloc_objects(object_entry_alloc);
strbuf_init(&command_buf, 0);
atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
marks = pool_calloc(1, sizeof(struct mark_set));
global_argc = argc;
global_argv = argv;
rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
for (i = 0; i < (cmd_save - 1); i++)
rc_free[i].next = &rc_free[i + 1];
rc_free[cmd_save - 1].next = NULL;
prepare_packed_git();
start_packfile();
set_die_routine(die_nicely);
set_checkpoint_signal();
while (read_next_command() != EOF) {
const char *v;
if (!strcmp("blob", command_buf.buf))
parse_new_blob();
else if (skip_prefix(command_buf.buf, "ls ", &v))
parse_ls(v, NULL);
else if (skip_prefix(command_buf.buf, "commit ", &v))
parse_new_commit(v);
else if (skip_prefix(command_buf.buf, "tag ", &v))
parse_new_tag(v);
else if (skip_prefix(command_buf.buf, "reset ", &v))
parse_reset_branch(v);
else if (!strcmp("checkpoint", command_buf.buf))
parse_checkpoint();
else if (!strcmp("done", command_buf.buf))
break;
else if (starts_with(command_buf.buf, "progress "))
parse_progress();
else if (skip_prefix(command_buf.buf, "feature ", &v))
parse_feature(v);
else if (skip_prefix(command_buf.buf, "option git ", &v))
parse_option(v);
else if (starts_with(command_buf.buf, "option "))
/* ignore non-git options*/;
else
die("Unsupported command: %s", command_buf.buf);
if (checkpoint_requested)
checkpoint();
}
/* argv hasn't been parsed yet, do so */
if (!seen_data_command)
parse_argv();
if (require_explicit_termination && feof(stdin))
die("stream ends early");
end_packfile();
dump_branches();
dump_tags();
unkeep_all_packs();
dump_marks();
if (pack_edges)
fclose(pack_edges);
if (show_stats) {
uintmax_t total_count = 0, duplicate_count = 0;
for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
total_count += object_count_by_type[i];
for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
duplicate_count += duplicate_count_by_type[i];
fprintf(stderr, "%s statistics:\n", argv[0]);
fprintf(stderr, "---------------------------------------------------------------------\n");
fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count);
fprintf(stderr, " blobs : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB], delta_count_attempts_by_type[OBJ_BLOB]);
fprintf(stderr, " trees : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE], delta_count_attempts_by_type[OBJ_TREE]);
fprintf(stderr, " commits: %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT], delta_count_attempts_by_type[OBJ_COMMIT]);
fprintf(stderr, " tags : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG], delta_count_attempts_by_type[OBJ_TAG]);
fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
fprintf(stderr, " atoms: %10u\n", atom_cnt);
fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)(total_allocd/1024));
fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
fprintf(stderr, "---------------------------------------------------------------------\n");
pack_report();
fprintf(stderr, "---------------------------------------------------------------------\n");
fprintf(stderr, "\n");
}
return failure ? 1 : 0;
}
| Lekensteyn/git | fast-import.c | C | gpl-2.0 | 90,233 |
<?php
/* Get all of the faq entries */
$results = $tc_db->GetAll("SELECT * FROM `".KU_DBPREFIX."front` WHERE `page` = 1 ORDER BY `order` ASC");
foreach($results AS $line) {
$content .= '<div class="content">' . "\n" .
'<h2><span class="newssub">'.stripslashes($line['subject']).'';
$content .= '</span><span class="permalink"><a href="#' . $line['id'] . '" title="permalink">#</a></span></h2>' . "\n" .
stripslashes($line['message']) . '</div><br />' . "\n";
}
return $content;
?> | stormeus/Kusaba-Z | inc/pages/faq.php | PHP | gpl-2.0 | 494 |
tinyMCE.addI18n('ps.modxlink',{
link_desc:"Insert/edit link"
}); | svyatoslavteterin/belton.by | core/packages/tinymce-4.3.3-pl/modPlugin/46c188883a90c37d912c8b5f16d2bdbd/0/tinymce/jscripts/tiny_mce/plugins/modxlink/langs/ps.js | JavaScript | gpl-2.0 | 68 |
"""
Downloads bootloader content for all arches for when the user doesn't want to supply their own.
Copyright 2009, Red Hat, Inc
Michael DeHaan <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
import os
import urlgrabber
import clogger
class ContentDownloader:
def __init__(self,config,logger=None):
"""
Constructor
"""
self.config = config
self.settings = config.settings()
if logger is None:
logger = clogger.Logger()
self.logger = logger
def run(self,force=False):
"""
Download bootloader content for all of the latest bootloaders, since the user
has chosen to not supply their own. You may ask "why not get this from yum", though
Fedora has no IA64 repo, for instance, and we also want this to be able to work on Debian and
further do not want folks to have to install a cross compiler. For those that don't like this approach
they can still source their cross-arch bootloader content manually.
"""
content_server = "http://mdehaan.fedorapeople.org/loaders"
dest = "/var/lib/cobbler/loaders"
files = (
( "%s/README" % content_server, "%s/README" % dest ),
( "%s/COPYING.elilo" % content_server, "%s/COPYING.elilo" % dest ),
( "%s/COPYING.yaboot" % content_server, "%s/COPYING.yaboot" % dest),
( "%s/COPYING.syslinux" % content_server, "%s/COPYING.syslinux" % dest),
( "%s/elilo-3.8-ia64.efi" % content_server, "%s/elilo-ia64.efi" % dest ),
( "%s/yaboot-1.3.14-12" % content_server, "%s/yaboot" % dest),
( "%s/pxelinux.0-3.61" % content_server, "%s/pxelinux.0" % dest),
( "%s/menu.c32-3.61" % content_server, "%s/menu.c32" % dest),
)
self.logger.info("downloading content required to netboot all arches")
for f in files:
src = f[0]
dst = f[1]
if os.path.exists(dst) and not force:
self.logger.info("path %s already exists, not overwriting existing content, use --force if you wish to update" % dst)
continue
self.logger.info("downloading %s to %s" % (src,dst))
urlgrabber.urlgrab(src,dst)
return True
| elsonrodriguez/madhatter | cobbler/action_dlcontent.py | Python | gpl-2.0 | 2,907 |
/****************************************************************************
** Meta object code from reading C++ file 'info_panels.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "info_panels.hpp"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'info_panels.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.5. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_MetaPanel[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: signature, parameters, type, tag, flags
11, 10, 10, 10, 0x05,
27, 10, 10, 10, 0x05,
// slots: signature, parameters, type, tag, flags
37, 10, 10, 10, 0x0a,
59, 10, 10, 10, 0x0a,
67, 10, 10, 10, 0x0a,
81, 10, 10, 10, 0x0a,
114, 10, 10, 10, 0x08,
0 // eod
};
static const char qt_meta_stringdata_MetaPanel[] = {
"MetaPanel\0\0uriSet(QString)\0editing()\0"
"update(input_item_t*)\0clear()\0"
"fingerprint()\0fingerprintUpdate(input_item_t*)\0"
"enterEditMode()\0"
};
void MetaPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
MetaPanel *_t = static_cast<MetaPanel *>(_o);
switch (_id) {
case 0: _t->uriSet((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 1: _t->editing(); break;
case 2: _t->update((*reinterpret_cast< input_item_t*(*)>(_a[1]))); break;
case 3: _t->clear(); break;
case 4: _t->fingerprint(); break;
case 5: _t->fingerprintUpdate((*reinterpret_cast< input_item_t*(*)>(_a[1]))); break;
case 6: _t->enterEditMode(); break;
default: ;
}
}
}
const QMetaObjectExtraData MetaPanel::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject MetaPanel::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_MetaPanel,
qt_meta_data_MetaPanel, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &MetaPanel::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *MetaPanel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *MetaPanel::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_MetaPanel))
return static_cast<void*>(const_cast< MetaPanel*>(this));
return QWidget::qt_metacast(_clname);
}
int MetaPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
}
return _id;
}
// SIGNAL 0
void MetaPanel::uriSet(const QString & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void MetaPanel::editing()
{
QMetaObject::activate(this, &staticMetaObject, 1, 0);
}
static const uint qt_meta_data_ExtraMetaPanel[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
16, 15, 15, 15, 0x0a,
38, 15, 15, 15, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_ExtraMetaPanel[] = {
"ExtraMetaPanel\0\0update(input_item_t*)\0"
"clear()\0"
};
void ExtraMetaPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
ExtraMetaPanel *_t = static_cast<ExtraMetaPanel *>(_o);
switch (_id) {
case 0: _t->update((*reinterpret_cast< input_item_t*(*)>(_a[1]))); break;
case 1: _t->clear(); break;
default: ;
}
}
}
const QMetaObjectExtraData ExtraMetaPanel::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject ExtraMetaPanel::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_ExtraMetaPanel,
qt_meta_data_ExtraMetaPanel, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &ExtraMetaPanel::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *ExtraMetaPanel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *ExtraMetaPanel::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_ExtraMetaPanel))
return static_cast<void*>(const_cast< ExtraMetaPanel*>(this));
return QWidget::qt_metacast(_clname);
}
int ExtraMetaPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
return _id;
}
static const uint qt_meta_data_InputStatsPanel[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
17, 16, 16, 16, 0x0a,
39, 16, 16, 16, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_InputStatsPanel[] = {
"InputStatsPanel\0\0update(input_item_t*)\0"
"clear()\0"
};
void InputStatsPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
InputStatsPanel *_t = static_cast<InputStatsPanel *>(_o);
switch (_id) {
case 0: _t->update((*reinterpret_cast< input_item_t*(*)>(_a[1]))); break;
case 1: _t->clear(); break;
default: ;
}
}
}
const QMetaObjectExtraData InputStatsPanel::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject InputStatsPanel::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_InputStatsPanel,
qt_meta_data_InputStatsPanel, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &InputStatsPanel::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *InputStatsPanel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *InputStatsPanel::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_InputStatsPanel))
return static_cast<void*>(const_cast< InputStatsPanel*>(this));
return QWidget::qt_metacast(_clname);
}
int InputStatsPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
return _id;
}
static const uint qt_meta_data_InfoPanel[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
11, 10, 10, 10, 0x0a,
33, 10, 10, 10, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_InfoPanel[] = {
"InfoPanel\0\0update(input_item_t*)\0"
"clear()\0"
};
void InfoPanel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
InfoPanel *_t = static_cast<InfoPanel *>(_o);
switch (_id) {
case 0: _t->update((*reinterpret_cast< input_item_t*(*)>(_a[1]))); break;
case 1: _t->clear(); break;
default: ;
}
}
}
const QMetaObjectExtraData InfoPanel::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject InfoPanel::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_InfoPanel,
qt_meta_data_InfoPanel, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &InfoPanel::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *InfoPanel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *InfoPanel::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_InfoPanel))
return static_cast<void*>(const_cast< InfoPanel*>(this));
return QWidget::qt_metacast(_clname);
}
int InfoPanel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| dulton/vlc-2.1.4.32.subproject-2013-update2 | modules/gui/qt4/components/info_panels.moc.cpp | C++ | gpl-2.0 | 10,339 |
/* GStreamer
*
* unit test for GstBufferList
*
* Copyright (C) 2009 Axis Communications <dev-gstreamer at axis dot com>
* @author Jonas Holmberg <jonas dot holmberg at axis dot com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <gst/check/gstcheck.h>
#include <gst/gstbufferlist.h>
#include <string.h>
#define TIMESTAMP 42
static GstBufferList *list;
static GstCaps *caps;
static void
setup (void)
{
list = gst_buffer_list_new ();
caps = gst_caps_new_simple ("text/plain", NULL);
}
static void
cleanup (void)
{
gst_caps_unref (caps);
gst_buffer_list_unref (list);
}
static GstBuffer *
buffer_from_string (const gchar * str)
{
guint size;
GstBuffer *buf;
size = strlen (str);
buf = gst_buffer_new_and_alloc (size);
gst_buffer_set_caps (buf, caps);
GST_BUFFER_TIMESTAMP (buf) = TIMESTAMP;
memcpy (GST_BUFFER_DATA (buf), str, size);
GST_BUFFER_SIZE (buf) = size;
return buf;
}
GST_START_TEST (test_add_and_iterate)
{
GstBufferListIterator *it;
GstBuffer *buf1;
GstBuffer *buf2;
GstBuffer *buf3;
GstBuffer *buf4;
GstBuffer *buf;
/* buffer list is initially empty */
fail_unless (gst_buffer_list_n_groups (list) == 0);
it = gst_buffer_list_iterate (list);
ASSERT_CRITICAL (gst_buffer_list_iterator_add (it, NULL));
ASSERT_CRITICAL (gst_buffer_list_iterator_add (NULL, NULL));
/* cannot add buffer without adding a group first */
buf1 = gst_buffer_new ();
ASSERT_CRITICAL (gst_buffer_list_iterator_add (it, buf1));
/* add a group of 2 buffers */
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
gst_buffer_list_iterator_add_group (it);
fail_unless (gst_buffer_list_n_groups (list) == 1);
ASSERT_CRITICAL (gst_buffer_list_iterator_add (it, NULL));
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 1);
gst_buffer_list_iterator_add (it, buf1);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 1); /* list takes ownership */
fail_unless (gst_buffer_list_n_groups (list) == 1);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
buf2 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf2);
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 1);
fail_unless (gst_buffer_list_n_groups (list) == 1);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
/* add another group of 2 buffers */
gst_buffer_list_iterator_add_group (it);
fail_unless (gst_buffer_list_n_groups (list) == 2);
buf3 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf3);
ASSERT_BUFFER_REFCOUNT (buf3, "buf3", 1);
fail_unless (gst_buffer_list_n_groups (list) == 2);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
buf4 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf4);
ASSERT_BUFFER_REFCOUNT (buf4, "buf4", 1);
fail_unless (gst_buffer_list_n_groups (list) == 2);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
/* freeing iterator does not affect list */
gst_buffer_list_iterator_free (it);
fail_unless (gst_buffer_list_n_groups (list) == 2);
/* create a new iterator */
it = gst_buffer_list_iterate (list);
/* iterate list */
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 2);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf1);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 1);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf2);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 2);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf3);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 1);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf4);
fail_unless (gst_buffer_list_iterator_n_buffers (it) == 0);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_if (gst_buffer_list_iterator_next_group (it));
gst_buffer_list_iterator_free (it);
}
GST_END_TEST;
GST_START_TEST (test_make_writable)
{
GstBufferListIterator *it;
GstBufferList *wlist;
GstBuffer *buf1;
GstBuffer *buf2;
GstBuffer *buf3;
GstBuffer *buf;
/* add buffers to list */
it = gst_buffer_list_iterate (list);
gst_buffer_list_iterator_add_group (it);
buf1 = gst_buffer_new_and_alloc (1);
gst_buffer_list_iterator_add (it, buf1);
gst_buffer_list_iterator_add_group (it);
buf2 = gst_buffer_new_and_alloc (2);
gst_buffer_list_iterator_add (it, buf2);
buf3 = gst_buffer_new_and_alloc (3);
gst_buffer_list_iterator_add (it, buf3);
gst_buffer_list_iterator_free (it);
/* making it writable with refcount 1 returns the same list */
wlist = gst_buffer_list_make_writable (list);
fail_unless (wlist == list);
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (it));
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf1);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 1);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf2);
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 1);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf3);
ASSERT_BUFFER_REFCOUNT (buf3, "buf3", 1);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_if (gst_buffer_list_iterator_next_group (it));
gst_buffer_list_iterator_free (it);
/* making it writable with refcount 2 returns a copy of the list with
* increased refcount on the buffers in the list */
gst_buffer_list_ref (list);
fail_unless (GST_MINI_OBJECT_REFCOUNT_VALUE (list) == 2);
wlist = gst_buffer_list_make_writable (list);
fail_unless (GST_MINI_OBJECT_REFCOUNT_VALUE (list) == 1);
fail_unless (GST_MINI_OBJECT_REFCOUNT_VALUE (wlist) == 1);
fail_unless (wlist != list);
it = gst_buffer_list_iterate (wlist);
fail_unless (gst_buffer_list_iterator_next_group (it));
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf1);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 2);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf2);
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 2);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf3);
ASSERT_BUFFER_REFCOUNT (buf3, "buf3", 2);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_if (gst_buffer_list_iterator_next_group (it));
gst_buffer_list_iterator_free (it);
gst_buffer_list_unref (wlist);
}
GST_END_TEST;
GST_START_TEST (test_copy)
{
GstBufferListIterator *it;
GstBufferList *list_copy;
GstBuffer *buf1;
GstBuffer *buf2;
GstBuffer *buf3;
GstBuffer *buf;
/* add buffers to the list */
it = gst_buffer_list_iterate (list);
gst_buffer_list_iterator_add_group (it);
buf1 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf1);
gst_buffer_list_iterator_add_group (it);
buf2 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf2);
buf3 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf3);
gst_buffer_list_iterator_free (it);
/* make a copy */
list_copy = gst_buffer_list_copy (list);
fail_unless (GST_MINI_OBJECT_REFCOUNT_VALUE (list) == 1);
fail_unless (GST_MINI_OBJECT_REFCOUNT_VALUE (list_copy) == 1);
fail_unless (list_copy != list);
it = gst_buffer_list_iterate (list_copy);
fail_unless (gst_buffer_list_iterator_next_group (it));
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf1);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 2);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf2);
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 2);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf3);
ASSERT_BUFFER_REFCOUNT (buf3, "buf3", 2);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_if (gst_buffer_list_iterator_next_group (it));
gst_buffer_list_iterator_free (it);
gst_buffer_list_unref (list_copy);
}
GST_END_TEST;
GST_START_TEST (test_steal)
{
GstBufferListIterator *it;
GstBuffer *buf1;
GstBuffer *buf2;
GstBuffer *buf3;
GstBuffer *buf;
/* add buffers to the list */
it = gst_buffer_list_iterate (list);
gst_buffer_list_iterator_add_group (it);
buf1 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf1);
gst_buffer_list_iterator_add_group (it);
buf2 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf2);
buf3 = gst_buffer_new ();
gst_buffer_list_iterator_add (it, buf3);
gst_buffer_list_iterator_free (it);
/* check some error handling */
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (NULL)));
fail_unless (buf == NULL);
it = gst_buffer_list_iterate (list);
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
fail_unless (buf == NULL);
/* steal the first buffer */
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
fail_unless (gst_buffer_list_iterator_next_group (it));
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
fail_unless (gst_buffer_list_iterator_next (it) == buf1);
buf = gst_buffer_list_iterator_steal (it);
fail_unless (buf == buf1);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 1);
gst_buffer_unref (buf);
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
fail_unless (buf == NULL);
/* steal the second buffer */
fail_unless (gst_buffer_list_iterator_next_group (it));
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
fail_unless (gst_buffer_list_iterator_next (it) == buf2);
buf = gst_buffer_list_iterator_steal (it);
fail_unless (buf == buf2);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 1);
gst_buffer_unref (buf);
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
/* steal the third buffer */
fail_unless (gst_buffer_list_iterator_next (it) == buf3);
buf = gst_buffer_list_iterator_steal (it);
fail_unless (buf == buf3);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 1);
gst_buffer_unref (buf);
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_steal (it)));
gst_buffer_list_iterator_free (it);
/* iterate again when all buffers have been stolen */
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_if (gst_buffer_list_iterator_next_group (it));
gst_buffer_list_iterator_free (it);
}
GST_END_TEST;
GST_START_TEST (test_take)
{
GstBufferListIterator *it;
GstBuffer *buf1;
GstBuffer *buf2;
GstBuffer *buf3;
GstBuffer *buf;
/* add buffers to the list */
it = gst_buffer_list_iterate (list);
gst_buffer_list_iterator_add_group (it);
buf1 = gst_buffer_new ();
gst_buffer_ref (buf1);
gst_buffer_list_iterator_add (it, buf1);
gst_buffer_list_iterator_add_group (it);
buf2 = gst_buffer_new ();
gst_buffer_ref (buf2);
gst_buffer_list_iterator_add (it, buf2);
buf3 = gst_buffer_new ();
gst_buffer_ref (buf3);
gst_buffer_list_iterator_add (it, buf3);
gst_buffer_list_iterator_free (it);
/* check some error handling */
ASSERT_CRITICAL (gst_buffer_list_iterator_take (NULL, NULL));
it = gst_buffer_list_iterate (list);
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, NULL));
buf = gst_buffer_new ();
gst_buffer_ref (buf);
ASSERT_CRITICAL (gst_buffer_list_iterator_take (NULL, buf));
ASSERT_BUFFER_REFCOUNT (buf, "buf", 2);
/* replace the first buffer */
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, buf));
ASSERT_BUFFER_REFCOUNT (buf, "buf", 2);
fail_unless (gst_buffer_list_iterator_next_group (it));
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, buf));
ASSERT_BUFFER_REFCOUNT (buf, "buf", 2);
fail_unless (gst_buffer_list_iterator_next (it) == buf1);
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, NULL));
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 2);
gst_buffer_list_iterator_take (it, buf);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 2);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 1);
gst_buffer_unref (buf1);
/* replace the first buffer again, with itself */
gst_buffer_ref (buf);
gst_buffer_list_iterator_take (it, buf);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 2);
/* replace the second buffer */
gst_buffer_ref (buf);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, buf));
ASSERT_BUFFER_REFCOUNT (buf, "buf", 3);
fail_unless (gst_buffer_list_iterator_next_group (it));
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 2);
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, buf));
ASSERT_BUFFER_REFCOUNT (buf, "buf", 3);
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 2);
fail_unless (gst_buffer_list_iterator_next (it) == buf2);
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, NULL));
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 2);
gst_buffer_list_iterator_take (it, buf);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 3);
ASSERT_BUFFER_REFCOUNT (buf2, "buf2", 1);
gst_buffer_unref (buf2);
/* replace the third buffer */
gst_buffer_ref (buf);
fail_unless (gst_buffer_list_iterator_next (it) == buf3);
ASSERT_BUFFER_REFCOUNT (buf3, "buf3", 2);
gst_buffer_list_iterator_take (it, buf);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 4);
ASSERT_BUFFER_REFCOUNT (buf3, "buf3", 1);
gst_buffer_unref (buf3);
fail_if (gst_buffer_list_iterator_next_group (it));
ASSERT_CRITICAL (gst_buffer_list_iterator_take (it, buf));
ASSERT_BUFFER_REFCOUNT (buf, "buf", 4);
gst_buffer_unref (buf);
gst_buffer_list_iterator_free (it);
}
GST_END_TEST;
static gpointer do_data_func_data;
static gboolean notified;
static GstBuffer *
do_data_func (GstBuffer * buffer, gpointer data)
{
do_data_func_data = data;
fail_if (notified);
return buffer;
}
static GstBuffer *
do_func_null (GstBuffer * buffer)
{
gst_buffer_unref (buffer);
return NULL;
}
GST_START_TEST (test_do)
{
GstBufferListIterator *it;
GstBuffer *buf1;
GstBuffer *buf;
gchar *data;
/* error handling */
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_do (NULL, NULL, NULL)));
fail_unless (buf == NULL);
fail_unless (buf == NULL);
it = gst_buffer_list_iterate (list);
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_do (it, NULL, NULL)));
fail_unless (buf == NULL);
fail_unless (buf == NULL);
/* add buffers to the list */
gst_buffer_list_iterator_add_group (it);
buf1 = gst_buffer_new ();
gst_buffer_ref (buf1);
gst_buffer_list_iterator_add (it, buf1);
gst_buffer_list_iterator_add_group (it);
gst_buffer_list_iterator_free (it);
/* call do-function */
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (it));
ASSERT_CRITICAL ((buf =
gst_buffer_list_iterator_do (it,
(GstBufferListDoFunction) gst_buffer_ref, NULL)));
fail_unless (buf == NULL);
data = (char *) "data";
ASSERT_CRITICAL ((buf = gst_buffer_list_iterator_do (it, do_data_func,
data)));
fail_unless (buf == NULL);
fail_unless (do_data_func_data != data);
buf = gst_buffer_list_iterator_next (it);
fail_unless (buf == buf1);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 2);
buf =
gst_buffer_list_iterator_do (it, (GstBufferListDoFunction) gst_buffer_ref,
NULL);
fail_unless (buf == buf1);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 3);
gst_buffer_unref (buf);
buf = gst_buffer_list_iterator_do (it, do_data_func, data);
fail_unless (buf == buf1);
fail_unless (do_data_func_data == data);
/* do-function that return a new buffer replaces the buffer in the list */
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 2);
buf = gst_buffer_list_iterator_do (it,
(GstBufferListDoFunction) gst_mini_object_make_writable, NULL);
fail_unless (buf != buf1);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 1);
ASSERT_BUFFER_REFCOUNT (buf, "buf1", 1);
gst_buffer_replace (&buf1, buf);
/* do-function that return NULL removes the buffer from the list */
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 2);
fail_unless (gst_buffer_list_iterator_do (it,
(GstBufferListDoFunction) do_func_null, NULL) == NULL);
ASSERT_BUFFER_REFCOUNT (buf1, "buf1", 1);
ASSERT_CRITICAL ((buf =
gst_buffer_list_iterator_do (it,
(GstBufferListDoFunction) gst_buffer_ref, NULL)));
fail_unless (buf == NULL);
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
gst_buffer_list_iterator_free (it);
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_next (it) == NULL);
fail_if (gst_buffer_list_iterator_next_group (it));
gst_buffer_list_iterator_free (it);
gst_buffer_unref (buf1);
}
GST_END_TEST;
GST_START_TEST (test_merge)
{
GstBufferListIterator *it;
GstBufferListIterator *merge_it;
GstBuffer *merged_buf;
GstBuffer *buf;
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_merge_group (it) == NULL);
/* create a new group and add a buffer */
gst_buffer_list_iterator_add_group (it);
fail_unless (gst_buffer_list_iterator_merge_group (it) == NULL);
buf = buffer_from_string ("One");
gst_buffer_ref (buf);
gst_buffer_list_iterator_add (it, buf);
/* merging a group with one buffer returns a copy of the buffer */
merge_it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (merge_it));
merged_buf = gst_buffer_list_iterator_merge_group (merge_it);
fail_unless (merged_buf != buf);
ASSERT_BUFFER_REFCOUNT (merged_buf, "merged_buf", 1);
gst_buffer_unref (buf);
fail_unless (GST_BUFFER_CAPS (merged_buf) == caps);
fail_unless (GST_BUFFER_TIMESTAMP (merged_buf) == TIMESTAMP);
fail_unless (GST_BUFFER_SIZE (merged_buf) == 3);
fail_unless (memcmp (GST_BUFFER_DATA (merged_buf), "One",
GST_BUFFER_SIZE (merged_buf)) == 0);
gst_buffer_unref (merged_buf);
/* add another buffer to the same group */
gst_buffer_list_iterator_add (it, buffer_from_string ("Group"));
/* merging a group returns a new buffer with merged data */
merged_buf = gst_buffer_list_iterator_merge_group (merge_it);
ASSERT_BUFFER_REFCOUNT (merged_buf, "merged_buf", 1);
fail_unless (GST_BUFFER_CAPS (merged_buf) == caps);
fail_unless (GST_BUFFER_TIMESTAMP (merged_buf) == TIMESTAMP);
fail_unless (GST_BUFFER_SIZE (merged_buf) == 8);
fail_unless (memcmp (GST_BUFFER_DATA (merged_buf), "OneGroup",
GST_BUFFER_SIZE (merged_buf)) == 0);
/* merging the same group again should return a new buffer with merged data */
buf = gst_buffer_list_iterator_merge_group (merge_it);
ASSERT_BUFFER_REFCOUNT (buf, "buf", 1);
fail_unless (buf != merged_buf);
fail_unless (GST_BUFFER_SIZE (buf) == 8);
fail_unless (memcmp (GST_BUFFER_DATA (buf), "OneGroup",
GST_BUFFER_SIZE (buf)) == 0);
gst_buffer_unref (buf);
gst_buffer_unref (merged_buf);
/* add a new group */
gst_buffer_list_iterator_add_group (it);
gst_buffer_list_iterator_add (it, buffer_from_string ("AnotherGroup"));
gst_buffer_list_iterator_free (it);
/* merge the first group again */
merged_buf = gst_buffer_list_iterator_merge_group (merge_it);
ASSERT_BUFFER_REFCOUNT (merged_buf, "merged_buf", 1);
fail_unless (GST_BUFFER_CAPS (merged_buf) == caps);
fail_unless (GST_BUFFER_TIMESTAMP (merged_buf) == TIMESTAMP);
fail_unless (GST_BUFFER_SIZE (merged_buf) == 8);
fail_unless (memcmp (GST_BUFFER_DATA (merged_buf), "OneGroup",
GST_BUFFER_SIZE (merged_buf)) == 0);
gst_buffer_unref (merged_buf);
/* merge the second group */
fail_unless (gst_buffer_list_iterator_next_group (merge_it));
merged_buf = gst_buffer_list_iterator_merge_group (merge_it);
ASSERT_BUFFER_REFCOUNT (merged_buf, "merged_buf", 1);
fail_unless (GST_BUFFER_CAPS (merged_buf) == caps);
fail_unless (GST_BUFFER_TIMESTAMP (merged_buf) == TIMESTAMP);
fail_unless (GST_BUFFER_SIZE (merged_buf) == 12);
fail_unless (memcmp (GST_BUFFER_DATA (merged_buf), "AnotherGroup",
GST_BUFFER_SIZE (merged_buf)) == 0);
gst_buffer_unref (merged_buf);
gst_buffer_list_iterator_free (merge_it);
/* steal the second buffer and merge the first group again */
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_next (it) != NULL);
fail_unless (gst_buffer_list_iterator_next (it) != NULL);
buf = gst_buffer_list_iterator_steal (it);
gst_buffer_list_iterator_free (it);
fail_unless (buf != NULL);
fail_unless (memcmp (GST_BUFFER_DATA (buf), "Group",
GST_BUFFER_SIZE (buf)) == 0);
gst_buffer_unref (buf);
merge_it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (merge_it));
merged_buf = gst_buffer_list_iterator_merge_group (merge_it);
ASSERT_BUFFER_REFCOUNT (merged_buf, "merged_buf", 1);
fail_unless (GST_BUFFER_CAPS (merged_buf) == caps);
fail_unless (GST_BUFFER_TIMESTAMP (merged_buf) == TIMESTAMP);
fail_unless (GST_BUFFER_SIZE (merged_buf) == 3);
fail_unless (memcmp (GST_BUFFER_DATA (merged_buf), "One",
GST_BUFFER_SIZE (merged_buf)) == 0);
gst_buffer_unref (merged_buf);
/* steal the first buffer too and merge the first group again */
it = gst_buffer_list_iterate (list);
fail_unless (gst_buffer_list_iterator_next_group (it));
fail_unless (gst_buffer_list_iterator_next (it) != NULL);
buf = gst_buffer_list_iterator_steal (it);
fail_unless (buf != NULL);
fail_unless (memcmp (GST_BUFFER_DATA (buf), "One",
GST_BUFFER_SIZE (buf)) == 0);
gst_buffer_unref (buf);
gst_buffer_list_iterator_free (it);
fail_unless (gst_buffer_list_iterator_merge_group (merge_it) == NULL);
gst_buffer_list_iterator_free (merge_it);
}
GST_END_TEST;
typedef struct
{
GstBuffer *buf[3][3];
guint iter;
} ForeachData;
static GstBufferListItem
foreach_func1 (GstBuffer ** buffer, guint group, guint idx, ForeachData * data)
{
fail_unless (buffer != NULL);
fail_unless (*buffer == data->buf[group][idx]);
data->iter++;
return GST_BUFFER_LIST_CONTINUE;
}
static GstBufferListItem
foreach_func2 (GstBuffer ** buffer, guint group, guint idx, ForeachData * data)
{
fail_unless (idx == 0);
fail_unless (buffer != NULL);
fail_unless (*buffer == data->buf[group][idx]);
data->iter++;
return GST_BUFFER_LIST_SKIP_GROUP;
}
static GstBufferListItem
foreach_func3 (GstBuffer ** buffer, guint group, guint idx, ForeachData * data)
{
fail_unless (group == 0);
fail_unless (idx == 0);
fail_unless (buffer != NULL);
fail_unless (*buffer == data->buf[group][idx]);
data->iter++;
return GST_BUFFER_LIST_END;
}
static GstBufferListItem
foreach_func4 (GstBuffer ** buffer, guint group, guint idx, ForeachData * data)
{
fail_unless (idx == 0);
fail_unless (buffer != NULL);
fail_unless (*buffer == data->buf[group][idx]);
gst_buffer_unref (*buffer);
*buffer = NULL;
data->iter++;
return GST_BUFFER_LIST_SKIP_GROUP;
}
static GstBufferListItem
foreach_func5 (GstBuffer ** buffer, guint group, guint idx, ForeachData * data)
{
fail_unless (buffer != NULL);
data->iter++;
return GST_BUFFER_LIST_CONTINUE;
}
GST_START_TEST (test_foreach)
{
GstBufferListIterator *it;
ForeachData data;
/* add buffers to the list */
it = gst_buffer_list_iterate (list);
gst_buffer_list_iterator_add_group (it);
data.buf[0][0] = gst_buffer_new ();
gst_buffer_list_iterator_add (it, data.buf[0][0]);
gst_buffer_list_iterator_add_group (it);
data.buf[1][0] = gst_buffer_new ();
gst_buffer_list_iterator_add (it, data.buf[1][0]);
data.buf[1][1] = gst_buffer_new ();
gst_buffer_list_iterator_add (it, data.buf[1][1]);
gst_buffer_list_iterator_free (it);
fail_unless (gst_buffer_list_get (list, 0, 0) == data.buf[0][0]);
fail_unless (gst_buffer_list_get (list, 0, 1) == NULL);
fail_unless (gst_buffer_list_get (list, 1, 0) == data.buf[1][0]);
fail_unless (gst_buffer_list_get (list, 1, 1) == data.buf[1][1]);
fail_unless (gst_buffer_list_get (list, 1, 2) == NULL);
fail_unless (gst_buffer_list_get (list, 2, 0) == NULL);
fail_unless (gst_buffer_list_get (list, 2, 1) == NULL);
fail_unless (gst_buffer_list_get (list, 3, 3) == NULL);
/* iterate everything */
data.iter = 0;
gst_buffer_list_foreach (list, (GstBufferListFunc) foreach_func1, &data);
fail_unless (data.iter == 3);
/* iterate only the first buffer of groups */
data.iter = 0;
gst_buffer_list_foreach (list, (GstBufferListFunc) foreach_func2, &data);
fail_unless (data.iter == 2);
/* iterate only the first buffer */
data.iter = 0;
gst_buffer_list_foreach (list, (GstBufferListFunc) foreach_func3, &data);
fail_unless (data.iter == 1);
/* remove the first buffer of each group */
data.iter = 0;
gst_buffer_list_foreach (list, (GstBufferListFunc) foreach_func4, &data);
fail_unless (data.iter == 2);
fail_unless (gst_buffer_list_get (list, 0, 0) == NULL);
fail_unless (gst_buffer_list_get (list, 0, 1) == NULL);
fail_unless (gst_buffer_list_get (list, 1, 0) == data.buf[1][1]);
fail_unless (gst_buffer_list_get (list, 1, 1) == NULL);
fail_unless (gst_buffer_list_get (list, 1, 2) == NULL);
fail_unless (gst_buffer_list_get (list, 2, 0) == NULL);
/* iterate everything, just one more buffer now */
data.iter = 0;
gst_buffer_list_foreach (list, (GstBufferListFunc) foreach_func5, &data);
fail_unless (data.iter == 1);
}
GST_END_TEST;
GST_START_TEST (test_list)
{
GstBufferListIterator *it;
GList *l = NULL;
gint i;
for (i = 0; i < 10; i++) {
gchar name[10];
g_snprintf (name, 10, "%d", i);
l = g_list_append (l, buffer_from_string (name));
}
/* add buffers to the list */
it = gst_buffer_list_iterate (list);
gst_buffer_list_iterator_add_group (it);
gst_buffer_list_iterator_add_list (it, l);
/* add a buffer */
gst_buffer_list_iterator_add (it, buffer_from_string ("10"));
/* add another list */
l = g_list_append (NULL, buffer_from_string ("11"));
gst_buffer_list_iterator_add_list (it, l);
for (i = 0; i < 12; i++) {
GstBuffer *buf;
gchar name[10];
buf = gst_buffer_list_get (list, 0, i);
g_snprintf (name, 10, "%d", i);
fail_unless (memcmp (name, (gchar *) GST_BUFFER_DATA (buf),
GST_BUFFER_SIZE (buf)) == 0);
}
gst_buffer_list_iterator_free (it);
}
GST_END_TEST;
static Suite *
gst_buffer_list_suite (void)
{
Suite *s = suite_create ("GstBufferList");
TCase *tc_chain = tcase_create ("general");
suite_add_tcase (s, tc_chain);
tcase_add_checked_fixture (tc_chain, setup, cleanup);
tcase_add_test (tc_chain, test_add_and_iterate);
tcase_add_test (tc_chain, test_make_writable);
tcase_add_test (tc_chain, test_copy);
tcase_add_test (tc_chain, test_steal);
tcase_add_test (tc_chain, test_take);
tcase_add_test (tc_chain, test_do);
tcase_add_test (tc_chain, test_merge);
tcase_add_test (tc_chain, test_foreach);
tcase_add_test (tc_chain, test_list);
return s;
}
GST_CHECK_MAIN (gst_buffer_list);
| atmark-techno/atmark-dist | user/gstreamer/gstreamer0.10/gstreamer0.10-0.10.36/tests/check/gst/gstbufferlist.c | C | gpl-2.0 | 28,194 |
/* unistd.h <[email protected]> */
#include <features.h>
#include <sys/types.h>
#ifndef __UNISTD_H
#define __UNISTD_H
#include <errno.h>
#include <asm/unistd.h>
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
__BEGIN_DECLS
extern int vhangup __P ((void));
extern int close __P ((int));
extern int read __P ((int __fd, void * __buf, size_t __nbytes));
extern int write __P ((int __fd, __const void * __buf, size_t __n));
extern off_t lseek __P ((int __fd, off_t __n, int __whence));
extern int pipe __P ((int __pipedes[2]));
extern unsigned int alarm __P ((unsigned int __seconds));
extern int sleep __P ((unsigned int __seconds));
extern void usleep __P ((unsigned long __microseconds));
extern int pause __P ((void));
extern char* crypt __P((__const char *__key, __const char *__salt));
extern int isatty __P ((int __fd));
extern char *ttyname __P ((int __fd));
extern int readlink __P ((__const char *__path, char *__buf, size_t __len));
extern int link __P ((__const char *__from, __const char *__to));
extern int symlink __P ((__const char *__from, __const char *__to));
extern int readlink __P ((__const char *__path, char *__buf, size_t __len));
extern int unlink __P ((__const char *__name));
extern char *getcwd __P ((char *__buf, size_t __size));
extern int fchdir __P ((int __fd));
extern int chdir __P ((__const char *__path));
extern int chown __P ((__const char *__file,
uid_t __owner, gid_t __group));
extern int fchown __P ((int __fd,
uid_t __owner, gid_t __group));
extern int chroot __P ((__const char *__path));
extern int truncate __P ((__const char *path, __off_t __length));
extern int ftruncate __P ((int __fd, __off_t __length));
extern int fsync __P ((int __fd));
extern int sync __P ((void));
extern int rmdir __P ((__const char *__path));
extern int access __P ((__const char *__name, int __type));
extern int _clone __P ((int (*fn)(void *arg), void *child_stack, int flags, void *arg));
extern long sysconf __P ((int name));
extern pid_t getpid __P ((void));
extern pid_t getppid __P ((void));
extern pid_t getpgrp __P ((void));
extern pid_t tcgetpgrp __P ((int));
extern int setpgrp __P ((void));
extern int tcsetpgrp __P ((int, pid_t));
extern pid_t setsid __P ((void));
extern int sethostname __P ((__const char *name, size_t len));
extern int gethostname __P ((char *__name, size_t __len));
extern int getdomainname __P ((char *__name, size_t __len));
extern int setdomainname __P ((__const char *__name, size_t __len));
extern char *getpass __P ((__const char *__prompt));
extern int getdtablesize __P ((void));
extern pid_t vfork __P ((void));
extern void _exit __P ((int __status)) __attribute__ ((__noreturn__));
extern int dup __P ((int __fd));
extern int dup2 __P ((int __fd, int __fd2));
extern int execl __P ((__const char *__path, __const char *__arg, ...));
extern int execlp __P ((__const char *__file, __const char *__arg, ...));
extern int execle __P ((__const char *__path, __const char *__arg, ...));
extern int execv __P ((__const char *__path, char *__const __argv[]));
extern int execvp __P ((__const char *__file, char *__const __argv[]));
extern int execve __P ((__const char *__filename, char *__const __argv[], char *__const envp[]));
extern int execvep __P (( __const char *file, char * __const argv[], char * __const envp[]));
extern void *sbrk __P ((ptrdiff_t __delta));
extern int setuid __P ((uid_t uid));
extern int seteuid __P ((uid_t euid));
extern int setreuid __P ((uid_t ruid, uid_t euid));
extern uid_t getuid __P ((void));
extern uid_t geteuid __P ((void));
extern gid_t getgid __P ((void));
extern gid_t getegid __P ((void));
extern int setgid __P ((gid_t gid));
extern int setegid __P ((gid_t egid));
extern int setregid __P ((gid_t rgid, gid_t egid));
extern int getgroups __P ((int size, gid_t list[]));
extern int getopt __P((int argc, char *__const argv[], __const char *optstring));
extern char *optarg;
extern int optind, opterr, optopt;
__END_DECLS
#define fork fork_not_available_use_vfork
#define clone clone_not_available_use__clone
#ifndef SEEK_SET
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#endif
#ifndef R_OK
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
#define X_OK 1 /* Test for execute permission. */
#define F_OK 0 /* Test for existence. */
#endif
/* And now we'll include the sysconf definitions */
#include <bits/confname.h>
extern char **environ;
#endif /* __UNISTD_H */
| rhuitl/uClinux | lib/libc/include/unistd.h | C | gpl-2.0 | 4,536 |
/*
* net/sched/cls_flower.c Flower classifier
*
* Copyright (c) 2015 Jiri Pirko <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/rhashtable.h>
#include <linux/if_ether.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <net/sch_generic.h>
#include <net/pkt_cls.h>
#include <net/ip.h>
#include <net/flow_dissector.h>
struct fl_flow_key {
int indev_ifindex;
struct flow_dissector_key_control control;
struct flow_dissector_key_basic basic;
struct flow_dissector_key_eth_addrs eth;
struct flow_dissector_key_addrs ipaddrs;
union {
struct flow_dissector_key_ipv4_addrs ipv4;
struct flow_dissector_key_ipv6_addrs ipv6;
};
struct flow_dissector_key_ports tp;
} __aligned(BITS_PER_LONG / 8); /* Ensure that we can do comparisons as longs. */
struct fl_flow_mask_range {
unsigned short int start;
unsigned short int end;
};
struct fl_flow_mask {
struct fl_flow_key key;
struct fl_flow_mask_range range;
struct rcu_head rcu;
};
struct cls_fl_head {
struct rhashtable ht;
struct fl_flow_mask mask;
struct flow_dissector dissector;
u32 hgen;
bool mask_assigned;
struct list_head filters;
struct rhashtable_params ht_params;
struct rcu_head rcu;
};
struct cls_fl_filter {
struct rhash_head ht_node;
struct fl_flow_key mkey;
struct tcf_exts exts;
struct tcf_result res;
struct fl_flow_key key;
struct list_head list;
u32 handle;
struct rcu_head rcu;
};
static unsigned short int fl_mask_range(const struct fl_flow_mask *mask)
{
return mask->range.end - mask->range.start;
}
static void fl_mask_update_range(struct fl_flow_mask *mask)
{
const u8 *bytes = (const u8 *) &mask->key;
size_t size = sizeof(mask->key);
size_t i, first = 0, last = size - 1;
for (i = 0; i < sizeof(mask->key); i++) {
if (bytes[i]) {
if (!first && i)
first = i;
last = i;
}
}
mask->range.start = rounddown(first, sizeof(long));
mask->range.end = roundup(last + 1, sizeof(long));
}
static void *fl_key_get_start(struct fl_flow_key *key,
const struct fl_flow_mask *mask)
{
return (u8 *) key + mask->range.start;
}
static void fl_set_masked_key(struct fl_flow_key *mkey, struct fl_flow_key *key,
struct fl_flow_mask *mask)
{
const long *lkey = fl_key_get_start(key, mask);
const long *lmask = fl_key_get_start(&mask->key, mask);
long *lmkey = fl_key_get_start(mkey, mask);
int i;
for (i = 0; i < fl_mask_range(mask); i += sizeof(long))
*lmkey++ = *lkey++ & *lmask++;
}
static void fl_clear_masked_range(struct fl_flow_key *key,
struct fl_flow_mask *mask)
{
memset(fl_key_get_start(key, mask), 0, fl_mask_range(mask));
}
static int fl_classify(struct sk_buff *skb, const struct tcf_proto *tp,
struct tcf_result *res)
{
struct cls_fl_head *head = rcu_dereference_bh(tp->root);
struct cls_fl_filter *f;
struct fl_flow_key skb_key;
struct fl_flow_key skb_mkey;
fl_clear_masked_range(&skb_key, &head->mask);
skb_key.indev_ifindex = skb->skb_iif;
/* skb_flow_dissect() does not set n_proto in case an unknown protocol,
* so do it rather here.
*/
skb_key.basic.n_proto = skb->protocol;
skb_flow_dissect(skb, &head->dissector, &skb_key);
fl_set_masked_key(&skb_mkey, &skb_key, &head->mask);
f = rhashtable_lookup_fast(&head->ht,
fl_key_get_start(&skb_mkey, &head->mask),
head->ht_params);
if (f) {
*res = f->res;
return tcf_exts_exec(skb, &f->exts, res);
}
return -1;
}
static int fl_init(struct tcf_proto *tp)
{
struct cls_fl_head *head;
head = kzalloc(sizeof(*head), GFP_KERNEL);
if (!head)
return -ENOBUFS;
INIT_LIST_HEAD_RCU(&head->filters);
rcu_assign_pointer(tp->root, head);
return 0;
}
static void fl_destroy_filter(struct rcu_head *head)
{
struct cls_fl_filter *f = container_of(head, struct cls_fl_filter, rcu);
tcf_exts_destroy(&f->exts);
kfree(f);
}
static bool fl_destroy(struct tcf_proto *tp, bool force)
{
struct cls_fl_head *head = rtnl_dereference(tp->root);
struct cls_fl_filter *f, *next;
if (!force && !list_empty(&head->filters))
return false;
list_for_each_entry_safe(f, next, &head->filters, list) {
list_del_rcu(&f->list);
call_rcu(&f->rcu, fl_destroy_filter);
}
RCU_INIT_POINTER(tp->root, NULL);
if (head->mask_assigned)
rhashtable_destroy(&head->ht);
kfree_rcu(head, rcu);
return true;
}
static unsigned long fl_get(struct tcf_proto *tp, u32 handle)
{
struct cls_fl_head *head = rtnl_dereference(tp->root);
struct cls_fl_filter *f;
list_for_each_entry(f, &head->filters, list)
if (f->handle == handle)
return (unsigned long) f;
return 0;
}
static const struct nla_policy fl_policy[TCA_FLOWER_MAX + 1] = {
[TCA_FLOWER_UNSPEC] = { .type = NLA_UNSPEC },
[TCA_FLOWER_CLASSID] = { .type = NLA_U32 },
[TCA_FLOWER_INDEV] = { .type = NLA_STRING,
.len = IFNAMSIZ },
[TCA_FLOWER_KEY_ETH_DST] = { .len = ETH_ALEN },
[TCA_FLOWER_KEY_ETH_DST_MASK] = { .len = ETH_ALEN },
[TCA_FLOWER_KEY_ETH_SRC] = { .len = ETH_ALEN },
[TCA_FLOWER_KEY_ETH_SRC_MASK] = { .len = ETH_ALEN },
[TCA_FLOWER_KEY_ETH_TYPE] = { .type = NLA_U16 },
[TCA_FLOWER_KEY_IP_PROTO] = { .type = NLA_U8 },
[TCA_FLOWER_KEY_IPV4_SRC] = { .type = NLA_U32 },
[TCA_FLOWER_KEY_IPV4_SRC_MASK] = { .type = NLA_U32 },
[TCA_FLOWER_KEY_IPV4_DST] = { .type = NLA_U32 },
[TCA_FLOWER_KEY_IPV4_DST_MASK] = { .type = NLA_U32 },
[TCA_FLOWER_KEY_IPV6_SRC] = { .len = sizeof(struct in6_addr) },
[TCA_FLOWER_KEY_IPV6_SRC_MASK] = { .len = sizeof(struct in6_addr) },
[TCA_FLOWER_KEY_IPV6_DST] = { .len = sizeof(struct in6_addr) },
[TCA_FLOWER_KEY_IPV6_DST_MASK] = { .len = sizeof(struct in6_addr) },
[TCA_FLOWER_KEY_TCP_SRC] = { .type = NLA_U16 },
[TCA_FLOWER_KEY_TCP_DST] = { .type = NLA_U16 },
[TCA_FLOWER_KEY_TCP_SRC] = { .type = NLA_U16 },
[TCA_FLOWER_KEY_TCP_DST] = { .type = NLA_U16 },
};
static void fl_set_key_val(struct nlattr **tb,
void *val, int val_type,
void *mask, int mask_type, int len)
{
if (!tb[val_type])
return;
memcpy(val, nla_data(tb[val_type]), len);
if (mask_type == TCA_FLOWER_UNSPEC || !tb[mask_type])
memset(mask, 0xff, len);
else
memcpy(mask, nla_data(tb[mask_type]), len);
}
static int fl_set_key(struct net *net, struct nlattr **tb,
struct fl_flow_key *key, struct fl_flow_key *mask)
{
#ifdef CONFIG_NET_CLS_IND
if (tb[TCA_FLOWER_INDEV]) {
int err = tcf_change_indev(net, tb[TCA_FLOWER_INDEV]);
if (err < 0)
return err;
key->indev_ifindex = err;
mask->indev_ifindex = 0xffffffff;
}
#endif
fl_set_key_val(tb, key->eth.dst, TCA_FLOWER_KEY_ETH_DST,
mask->eth.dst, TCA_FLOWER_KEY_ETH_DST_MASK,
sizeof(key->eth.dst));
fl_set_key_val(tb, key->eth.src, TCA_FLOWER_KEY_ETH_SRC,
mask->eth.src, TCA_FLOWER_KEY_ETH_SRC_MASK,
sizeof(key->eth.src));
fl_set_key_val(tb, &key->basic.n_proto, TCA_FLOWER_KEY_ETH_TYPE,
&mask->basic.n_proto, TCA_FLOWER_UNSPEC,
sizeof(key->basic.n_proto));
if (key->basic.n_proto == htons(ETH_P_IP) ||
key->basic.n_proto == htons(ETH_P_IPV6)) {
fl_set_key_val(tb, &key->basic.ip_proto, TCA_FLOWER_KEY_IP_PROTO,
&mask->basic.ip_proto, TCA_FLOWER_UNSPEC,
sizeof(key->basic.ip_proto));
}
if (key->control.addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
fl_set_key_val(tb, &key->ipv4.src, TCA_FLOWER_KEY_IPV4_SRC,
&mask->ipv4.src, TCA_FLOWER_KEY_IPV4_SRC_MASK,
sizeof(key->ipv4.src));
fl_set_key_val(tb, &key->ipv4.dst, TCA_FLOWER_KEY_IPV4_DST,
&mask->ipv4.dst, TCA_FLOWER_KEY_IPV4_DST_MASK,
sizeof(key->ipv4.dst));
} else if (key->control.addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
fl_set_key_val(tb, &key->ipv6.src, TCA_FLOWER_KEY_IPV6_SRC,
&mask->ipv6.src, TCA_FLOWER_KEY_IPV6_SRC_MASK,
sizeof(key->ipv6.src));
fl_set_key_val(tb, &key->ipv6.dst, TCA_FLOWER_KEY_IPV6_DST,
&mask->ipv6.dst, TCA_FLOWER_KEY_IPV6_DST_MASK,
sizeof(key->ipv6.dst));
}
if (key->basic.ip_proto == IPPROTO_TCP) {
fl_set_key_val(tb, &key->tp.src, TCA_FLOWER_KEY_TCP_SRC,
&mask->tp.src, TCA_FLOWER_UNSPEC,
sizeof(key->tp.src));
fl_set_key_val(tb, &key->tp.dst, TCA_FLOWER_KEY_TCP_DST,
&mask->tp.dst, TCA_FLOWER_UNSPEC,
sizeof(key->tp.dst));
} else if (key->basic.ip_proto == IPPROTO_UDP) {
fl_set_key_val(tb, &key->tp.src, TCA_FLOWER_KEY_UDP_SRC,
&mask->tp.src, TCA_FLOWER_UNSPEC,
sizeof(key->tp.src));
fl_set_key_val(tb, &key->tp.dst, TCA_FLOWER_KEY_UDP_DST,
&mask->tp.dst, TCA_FLOWER_UNSPEC,
sizeof(key->tp.dst));
}
return 0;
}
static bool fl_mask_eq(struct fl_flow_mask *mask1,
struct fl_flow_mask *mask2)
{
const long *lmask1 = fl_key_get_start(&mask1->key, mask1);
const long *lmask2 = fl_key_get_start(&mask2->key, mask2);
return !memcmp(&mask1->range, &mask2->range, sizeof(mask1->range)) &&
!memcmp(lmask1, lmask2, fl_mask_range(mask1));
}
static const struct rhashtable_params fl_ht_params = {
.key_offset = offsetof(struct cls_fl_filter, mkey), /* base offset */
.head_offset = offsetof(struct cls_fl_filter, ht_node),
.automatic_shrinking = true,
};
static int fl_init_hashtable(struct cls_fl_head *head,
struct fl_flow_mask *mask)
{
head->ht_params = fl_ht_params;
head->ht_params.key_len = fl_mask_range(mask);
head->ht_params.key_offset += mask->range.start;
return rhashtable_init(&head->ht, &head->ht_params);
}
#define FL_KEY_MEMBER_OFFSET(member) offsetof(struct fl_flow_key, member)
#define FL_KEY_MEMBER_SIZE(member) (sizeof(((struct fl_flow_key *) 0)->member))
#define FL_KEY_MEMBER_END_OFFSET(member) \
(FL_KEY_MEMBER_OFFSET(member) + FL_KEY_MEMBER_SIZE(member))
#define FL_KEY_IN_RANGE(mask, member) \
(FL_KEY_MEMBER_OFFSET(member) <= (mask)->range.end && \
FL_KEY_MEMBER_END_OFFSET(member) >= (mask)->range.start)
#define FL_KEY_SET(keys, cnt, id, member) \
do { \
keys[cnt].key_id = id; \
keys[cnt].offset = FL_KEY_MEMBER_OFFSET(member); \
cnt++; \
} while(0);
#define FL_KEY_SET_IF_IN_RANGE(mask, keys, cnt, id, member) \
do { \
if (FL_KEY_IN_RANGE(mask, member)) \
FL_KEY_SET(keys, cnt, id, member); \
} while(0);
static void fl_init_dissector(struct cls_fl_head *head,
struct fl_flow_mask *mask)
{
struct flow_dissector_key keys[FLOW_DISSECTOR_KEY_MAX];
size_t cnt = 0;
FL_KEY_SET(keys, cnt, FLOW_DISSECTOR_KEY_CONTROL, control);
FL_KEY_SET(keys, cnt, FLOW_DISSECTOR_KEY_BASIC, basic);
FL_KEY_SET_IF_IN_RANGE(mask, keys, cnt,
FLOW_DISSECTOR_KEY_ETH_ADDRS, eth);
FL_KEY_SET_IF_IN_RANGE(mask, keys, cnt,
FLOW_DISSECTOR_KEY_IPV4_ADDRS, ipv4);
FL_KEY_SET_IF_IN_RANGE(mask, keys, cnt,
FLOW_DISSECTOR_KEY_IPV6_ADDRS, ipv6);
FL_KEY_SET_IF_IN_RANGE(mask, keys, cnt,
FLOW_DISSECTOR_KEY_PORTS, tp);
skb_flow_dissector_init(&head->dissector, keys, cnt);
}
static int fl_check_assign_mask(struct cls_fl_head *head,
struct fl_flow_mask *mask)
{
int err;
if (head->mask_assigned) {
if (!fl_mask_eq(&head->mask, mask))
return -EINVAL;
else
return 0;
}
/* Mask is not assigned yet. So assign it and init hashtable
* according to that.
*/
err = fl_init_hashtable(head, mask);
if (err)
return err;
memcpy(&head->mask, mask, sizeof(head->mask));
head->mask_assigned = true;
fl_init_dissector(head, mask);
return 0;
}
static int fl_set_parms(struct net *net, struct tcf_proto *tp,
struct cls_fl_filter *f, struct fl_flow_mask *mask,
unsigned long base, struct nlattr **tb,
struct nlattr *est, bool ovr)
{
struct tcf_exts e;
int err;
tcf_exts_init(&e, TCA_FLOWER_ACT, 0);
err = tcf_exts_validate(net, tp, tb, est, &e, ovr);
if (err < 0)
return err;
if (tb[TCA_FLOWER_CLASSID]) {
f->res.classid = nla_get_u32(tb[TCA_FLOWER_CLASSID]);
tcf_bind_filter(tp, &f->res, base);
}
err = fl_set_key(net, tb, &f->key, &mask->key);
if (err)
goto errout;
fl_mask_update_range(mask);
fl_set_masked_key(&f->mkey, &f->key, mask);
tcf_exts_change(tp, &f->exts, &e);
return 0;
errout:
tcf_exts_destroy(&e);
return err;
}
static u32 fl_grab_new_handle(struct tcf_proto *tp,
struct cls_fl_head *head)
{
unsigned int i = 0x80000000;
u32 handle;
do {
if (++head->hgen == 0x7FFFFFFF)
head->hgen = 1;
} while (--i > 0 && fl_get(tp, head->hgen));
if (unlikely(i == 0)) {
pr_err("Insufficient number of handles\n");
handle = 0;
} else {
handle = head->hgen;
}
return handle;
}
static int fl_change(struct net *net, struct sk_buff *in_skb,
struct tcf_proto *tp, unsigned long base,
u32 handle, struct nlattr **tca,
unsigned long *arg, bool ovr)
{
struct cls_fl_head *head = rtnl_dereference(tp->root);
struct cls_fl_filter *fold = (struct cls_fl_filter *) *arg;
struct cls_fl_filter *fnew;
struct nlattr *tb[TCA_FLOWER_MAX + 1];
struct fl_flow_mask mask = {};
int err;
if (!tca[TCA_OPTIONS])
return -EINVAL;
err = nla_parse_nested(tb, TCA_FLOWER_MAX, tca[TCA_OPTIONS], fl_policy);
if (err < 0)
return err;
if (fold && handle && fold->handle != handle)
return -EINVAL;
fnew = kzalloc(sizeof(*fnew), GFP_KERNEL);
if (!fnew)
return -ENOBUFS;
tcf_exts_init(&fnew->exts, TCA_FLOWER_ACT, 0);
if (!handle) {
handle = fl_grab_new_handle(tp, head);
if (!handle) {
err = -EINVAL;
goto errout;
}
}
fnew->handle = handle;
err = fl_set_parms(net, tp, fnew, &mask, base, tb, tca[TCA_RATE], ovr);
if (err)
goto errout;
err = fl_check_assign_mask(head, &mask);
if (err)
goto errout;
err = rhashtable_insert_fast(&head->ht, &fnew->ht_node,
head->ht_params);
if (err)
goto errout;
if (fold)
rhashtable_remove_fast(&head->ht, &fold->ht_node,
head->ht_params);
*arg = (unsigned long) fnew;
if (fold) {
list_replace_rcu(&fnew->list, &fold->list);
tcf_unbind_filter(tp, &fold->res);
call_rcu(&fold->rcu, fl_destroy_filter);
} else {
list_add_tail_rcu(&fnew->list, &head->filters);
}
return 0;
errout:
kfree(fnew);
return err;
}
static int fl_delete(struct tcf_proto *tp, unsigned long arg)
{
struct cls_fl_head *head = rtnl_dereference(tp->root);
struct cls_fl_filter *f = (struct cls_fl_filter *) arg;
rhashtable_remove_fast(&head->ht, &f->ht_node,
head->ht_params);
list_del_rcu(&f->list);
tcf_unbind_filter(tp, &f->res);
call_rcu(&f->rcu, fl_destroy_filter);
return 0;
}
static void fl_walk(struct tcf_proto *tp, struct tcf_walker *arg)
{
struct cls_fl_head *head = rtnl_dereference(tp->root);
struct cls_fl_filter *f;
list_for_each_entry_rcu(f, &head->filters, list) {
if (arg->count < arg->skip)
goto skip;
if (arg->fn(tp, (unsigned long) f, arg) < 0) {
arg->stop = 1;
break;
}
skip:
arg->count++;
}
}
static int fl_dump_key_val(struct sk_buff *skb,
void *val, int val_type,
void *mask, int mask_type, int len)
{
int err;
if (!memchr_inv(mask, 0, len))
return 0;
err = nla_put(skb, val_type, len, val);
if (err)
return err;
if (mask_type != TCA_FLOWER_UNSPEC) {
err = nla_put(skb, mask_type, len, mask);
if (err)
return err;
}
return 0;
}
static int fl_dump(struct net *net, struct tcf_proto *tp, unsigned long fh,
struct sk_buff *skb, struct tcmsg *t)
{
struct cls_fl_head *head = rtnl_dereference(tp->root);
struct cls_fl_filter *f = (struct cls_fl_filter *) fh;
struct nlattr *nest;
struct fl_flow_key *key, *mask;
if (!f)
return skb->len;
t->tcm_handle = f->handle;
nest = nla_nest_start(skb, TCA_OPTIONS);
if (!nest)
goto nla_put_failure;
if (f->res.classid &&
nla_put_u32(skb, TCA_FLOWER_CLASSID, f->res.classid))
goto nla_put_failure;
key = &f->key;
mask = &head->mask.key;
if (mask->indev_ifindex) {
struct net_device *dev;
dev = __dev_get_by_index(net, key->indev_ifindex);
if (dev && nla_put_string(skb, TCA_FLOWER_INDEV, dev->name))
goto nla_put_failure;
}
if (fl_dump_key_val(skb, key->eth.dst, TCA_FLOWER_KEY_ETH_DST,
mask->eth.dst, TCA_FLOWER_KEY_ETH_DST_MASK,
sizeof(key->eth.dst)) ||
fl_dump_key_val(skb, key->eth.src, TCA_FLOWER_KEY_ETH_SRC,
mask->eth.src, TCA_FLOWER_KEY_ETH_SRC_MASK,
sizeof(key->eth.src)) ||
fl_dump_key_val(skb, &key->basic.n_proto, TCA_FLOWER_KEY_ETH_TYPE,
&mask->basic.n_proto, TCA_FLOWER_UNSPEC,
sizeof(key->basic.n_proto)))
goto nla_put_failure;
if ((key->basic.n_proto == htons(ETH_P_IP) ||
key->basic.n_proto == htons(ETH_P_IPV6)) &&
fl_dump_key_val(skb, &key->basic.ip_proto, TCA_FLOWER_KEY_IP_PROTO,
&mask->basic.ip_proto, TCA_FLOWER_UNSPEC,
sizeof(key->basic.ip_proto)))
goto nla_put_failure;
if (key->control.addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS &&
(fl_dump_key_val(skb, &key->ipv4.src, TCA_FLOWER_KEY_IPV4_SRC,
&mask->ipv4.src, TCA_FLOWER_KEY_IPV4_SRC_MASK,
sizeof(key->ipv4.src)) ||
fl_dump_key_val(skb, &key->ipv4.dst, TCA_FLOWER_KEY_IPV4_DST,
&mask->ipv4.dst, TCA_FLOWER_KEY_IPV4_DST_MASK,
sizeof(key->ipv4.dst))))
goto nla_put_failure;
else if (key->control.addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS &&
(fl_dump_key_val(skb, &key->ipv6.src, TCA_FLOWER_KEY_IPV6_SRC,
&mask->ipv6.src, TCA_FLOWER_KEY_IPV6_SRC_MASK,
sizeof(key->ipv6.src)) ||
fl_dump_key_val(skb, &key->ipv6.dst, TCA_FLOWER_KEY_IPV6_DST,
&mask->ipv6.dst, TCA_FLOWER_KEY_IPV6_DST_MASK,
sizeof(key->ipv6.dst))))
goto nla_put_failure;
if (key->basic.ip_proto == IPPROTO_TCP &&
(fl_dump_key_val(skb, &key->tp.src, TCA_FLOWER_KEY_TCP_SRC,
&mask->tp.src, TCA_FLOWER_UNSPEC,
sizeof(key->tp.src)) ||
fl_dump_key_val(skb, &key->tp.dst, TCA_FLOWER_KEY_TCP_DST,
&mask->tp.dst, TCA_FLOWER_UNSPEC,
sizeof(key->tp.dst))))
goto nla_put_failure;
else if (key->basic.ip_proto == IPPROTO_UDP &&
(fl_dump_key_val(skb, &key->tp.src, TCA_FLOWER_KEY_UDP_SRC,
&mask->tp.src, TCA_FLOWER_UNSPEC,
sizeof(key->tp.src)) ||
fl_dump_key_val(skb, &key->tp.dst, TCA_FLOWER_KEY_UDP_DST,
&mask->tp.dst, TCA_FLOWER_UNSPEC,
sizeof(key->tp.dst))))
goto nla_put_failure;
if (tcf_exts_dump(skb, &f->exts))
goto nla_put_failure;
nla_nest_end(skb, nest);
if (tcf_exts_dump_stats(skb, &f->exts) < 0)
goto nla_put_failure;
return skb->len;
nla_put_failure:
nla_nest_cancel(skb, nest);
return -1;
}
static struct tcf_proto_ops cls_fl_ops __read_mostly = {
.kind = "flower",
.classify = fl_classify,
.init = fl_init,
.destroy = fl_destroy,
.get = fl_get,
.change = fl_change,
.delete = fl_delete,
.walk = fl_walk,
.dump = fl_dump,
.owner = THIS_MODULE,
};
static int __init cls_fl_init(void)
{
return register_tcf_proto_ops(&cls_fl_ops);
}
static void __exit cls_fl_exit(void)
{
unregister_tcf_proto_ops(&cls_fl_ops);
}
module_init(cls_fl_init);
module_exit(cls_fl_exit);
MODULE_AUTHOR("Jiri Pirko <[email protected]>");
MODULE_DESCRIPTION("Flower classifier");
MODULE_LICENSE("GPL v2");
| identisoft-rashid/ec3_kernel_pre_4.1 | net/sched/cls_flower.c | C | gpl-2.0 | 19,249 |
<?php
namespace Stripe;
/**
* Class WebhookEndpoint
*
* @property string $id
* @property string $object
* @property int $created
* @property string[] $enabled_events
* @property bool $livemode
* @property string $secret
* @property string $status
* @property string $url
*
* @package Stripe
*/
class WebhookEndpoint extends ApiResource
{
const OBJECT_NAME = "webhook_endpoint";
use ApiOperations\All;
use ApiOperations\Create;
use ApiOperations\Delete;
use ApiOperations\Retrieve;
use ApiOperations\Update;
}
| eventespresso/event-espresso-legacy | gateways/stripe/stripe-php-6.43.1/lib/WebhookEndpoint.php | PHP | gpl-2.0 | 549 |
/*
* Copyright (C) 2009 by Jonathan Naylor, G4KLX
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef FECDecoder_H
#define FECDecoder_H
class IFECDecoder {
public:
virtual bool decode(const bool* in, bool* out, unsigned int inLen, unsigned int& outLen) = 0;
private:
};
#endif
| dl5di/OpenDV | Digital Voice/Common/FECDecoder.h | C | gpl-2.0 | 722 |
/* Openswan NAT-Traversal
* Copyright (C) 2002-2003 Mathieu Lafon - Arkoon Network Security
* Copyright 2005 Michael Richardson <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* RCSID $Id: natt_defines.h,v 1.1 2005/04/08 18:23:10 mcr Exp $
*/
#ifndef NATT_DEFINES_H
#ifndef SOL_UDP
#define SOL_UDP 17
#endif
#ifndef UDP_ESPINUDP
#define UDP_ESPINUDP 100
#endif
#define NATT_DEFINES_H
#endif
| rhuitl/uClinux | openswan/include/natt_defines.h | C | gpl-2.0 | 924 |
EasyBlog.module( "featured" , function($) {
var module = this;
// require: start
EasyBlog.require()
.done(function(){
// controller: start
EasyBlog.Controller(
"Featured.Scroller",
{
defaultOptions: {
elements: null,
itemWidth: null,
// Auto rotate option
autorotate: {
enabled : false,
interval : 50
},
// Items
"{placeHolder}" : ".slider-holder",
"{slider}" : ".featured-entries",
"{sliderItems}" : ".slider-holder ul li",
"{sliderNavigation}" : ".featured-navi .featured-a a"
}
},
function(self) {return {
/**
* Featured scroller object initialization happens here.
*
*/
init: function() {
// Set the current holder width to a temporary location.
self.options.itemWidth = self.placeHolder().width() + 1;
// Calculate the total width of the whole parent container as we need to multiply this by the number of child elements.
var totalWidth = self.sliderItems().length * parseInt( self.options.itemWidth );
// Now, we need to stretch the parent's width to match the total items.
self.slider().css( 'width' , totalWidth );
// Make sure the width of each child items has the same width as its parent.
self.sliderItems().css( 'width' , self.options.itemWidth );
if( self.options.autorotate.enabled )
{
setTimeout( function(){
self.initAutoRotate();
}, parseInt( self.options.autorotate.interval ) * 1000 );
}
},
nextItem : function( element )
{
var index = $( element ).data( 'slider' );
var left = 0;
// If the current index is 1, we can just leave left as 0
if( index != 1 )
{
left = self.options.itemWidth * parseInt( index - 1 );
}
// Since any items after the first item is hidden by default, we need to show the current item.
self.slider().children( ':nth-child(' + index + ')' ).show();
// Now let's animate the placeholder.
self.slider().animate( {
left : '-' + left + 'px'
}, 'slow' );
// Remove active class from the navigation anchor link.
self.sliderNavigation( '.active' ).removeClass( 'active' );
// Set the active element on the current item.
$( element ).addClass( 'active' );
},
"{sliderNavigation} click" : function( element ){
self.nextItem( element );
},
/**
* This initializes the auto rotation for the featured items.
*/
initAutoRotate: function(){
var set = false;
self.sliderNavigation().each(function(){
if( $( this ).hasClass( 'active' ) && set != true )
{
if( $( this ).next().length == 0 )
{
self.nextItem( self.sliderNavigation( ':first' ) );
}
else
{
self.nextItem( $(this).next() );
}
set = true;
}
});
setTimeout( function(){
self.initAutoRotate();
}, parseInt( self.options.autorotate.interval ) * 1000 );
}
} }
);
module.resolve();
// controller: end
});
});
| BetterBetterBetter/B3App | media/com_easyblog/scripts/featured.js | JavaScript | gpl-2.0 | 2,903 |
<?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
class Google_Service_ManagedServiceforMicrosoftActiveDirectoryConsumerAPI_TestIamPermissionsRequest extends Google_Collection
{
protected $collection_key = 'permissions';
public $permissions;
public function setPermissions($permissions)
{
$this->permissions = $permissions;
}
public function getPermissions()
{
return $this->permissions;
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/ManagedServiceforMicrosoftActiveDirectoryConsumerAPI/TestIamPermissionsRequest.php | PHP | gpl-3.0 | 965 |
<?php
/**
* Project: Smarty: the PHP compiling template engine
* File: smarty_internal_utility.php
* SVN: $Id: smarty_internal_utility.php 2640 2013-03-23 19:23:26Z slaver7 $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* [email protected]
*
* @link http://www.smarty.net/
* @copyright 2008 New Digital Group, Inc.
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @package Smarty
* @subpackage PluginsInternal
* @version 3-SVN$Rev: 3286 $
*/
/**
* Utility class
*
* @package Smarty
* @subpackage Security
*/
class Smarty_Internal_Utility {
/**
* private constructor to prevent calls creation of new instances
*/
private final function __construct()
{
// intentionally left blank
}
/**
* Compile all template files
*
* @param string $extension template file name extension
* @param bool $force_compile force all to recompile
* @param int $time_limit set maximum execution time
* @param int $max_errors set maximum allowed errors
* @param Smarty $smarty Smarty instance
* @return integer number of template files compiled
*/
public static function compileAllTemplates($extention, $force_compile, $time_limit, $max_errors, Smarty $smarty)
{
// switch off time limit
if (function_exists('set_time_limit')) {
@set_time_limit($time_limit);
}
$smarty->force_compile = $force_compile;
$_count = 0;
$_error_count = 0;
// loop over array of template directories
foreach($smarty->getTemplateDir() as $_dir) {
$_compileDirs = new RecursiveDirectoryIterator($_dir);
$_compile = new RecursiveIteratorIterator($_compileDirs);
foreach ($_compile as $_fileinfo) {
$_file = $_fileinfo->getFilename();
if (substr(basename($_fileinfo->getPathname()),0,1) == '.' || strpos($_file, '.svn') !== false) continue;
if (!substr_compare($_file, $extention, - strlen($extention)) == 0) continue;
if ($_fileinfo->getPath() == substr($_dir, 0, -1)) {
$_template_file = $_file;
} else {
$_template_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file;
}
echo '<br>', $_dir, '---', $_template_file;
flush();
$_start_time = microtime(true);
try {
$_tpl = $smarty->createTemplate($_template_file,null,null,null,false);
if ($_tpl->mustCompile()) {
$_tpl->compileTemplateSource();
$_count++;
echo ' compiled in ', microtime(true) - $_start_time, ' seconds';
flush();
} else {
echo ' is up to date';
flush();
}
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "<br><br>";
$_error_count++;
}
// free memory
$smarty->template_objects = array();
$_tpl->smarty->template_objects = array();
$_tpl = null;
if ($max_errors !== null && $_error_count == $max_errors) {
echo '<br><br>too many errors';
exit();
}
}
}
return $_count;
}
/**
* Compile all config files
*
* @param string $extension config file name extension
* @param bool $force_compile force all to recompile
* @param int $time_limit set maximum execution time
* @param int $max_errors set maximum allowed errors
* @param Smarty $smarty Smarty instance
* @return integer number of config files compiled
*/
public static function compileAllConfig($extention, $force_compile, $time_limit, $max_errors, Smarty $smarty)
{
// switch off time limit
if (function_exists('set_time_limit')) {
@set_time_limit($time_limit);
}
$smarty->force_compile = $force_compile;
$_count = 0;
$_error_count = 0;
// loop over array of template directories
foreach($smarty->getConfigDir() as $_dir) {
$_compileDirs = new RecursiveDirectoryIterator($_dir);
$_compile = new RecursiveIteratorIterator($_compileDirs);
foreach ($_compile as $_fileinfo) {
$_file = $_fileinfo->getFilename();
if (substr(basename($_fileinfo->getPathname()),0,1) == '.' || strpos($_file, '.svn') !== false) continue;
if (!substr_compare($_file, $extention, - strlen($extention)) == 0) continue;
if ($_fileinfo->getPath() == substr($_dir, 0, -1)) {
$_config_file = $_file;
} else {
$_config_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file;
}
echo '<br>', $_dir, '---', $_config_file;
flush();
$_start_time = microtime(true);
try {
$_config = new Smarty_Internal_Config($_config_file, $smarty);
if ($_config->mustCompile()) {
$_config->compileConfigSource();
$_count++;
echo ' compiled in ', microtime(true) - $_start_time, ' seconds';
flush();
} else {
echo ' is up to date';
flush();
}
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "<br><br>";
$_error_count++;
}
if ($max_errors !== null && $_error_count == $max_errors) {
echo '<br><br>too many errors';
exit();
}
}
}
return $_count;
}
/**
* Delete compiled template file
*
* @param string $resource_name template name
* @param string $compile_id compile id
* @param integer $exp_time expiration time
* @param Smarty $smarty Smarty instance
* @return integer number of template files deleted
*/
public static function clearCompiledTemplate($resource_name, $compile_id, $exp_time, Smarty $smarty)
{
$_compile_dir = $smarty->getCompileDir();
$_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null;
$_dir_sep = $smarty->use_sub_dirs ? DS : '^';
if (isset($resource_name)) {
$_save_stat = $smarty->caching;
$smarty->caching = false;
$tpl = new $smarty->template_class($resource_name, $smarty);
$smarty->caching = $_save_stat;
// remove from template cache
$tpl->source; // have the template registered before unset()
if ($smarty->allow_ambiguous_resources) {
$_templateId = $tpl->source->unique_resource . $tpl->cache_id . $tpl->compile_id;
} else {
$_templateId = $smarty->joined_template_dir . '#' . $resource_name . $tpl->cache_id . $tpl->compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
unset($smarty->template_objects[$_templateId]);
if ($tpl->source->exists) {
$_resource_part_1 = basename(str_replace('^', '/', $tpl->compiled->filepath));
$_resource_part_1_length = strlen($_resource_part_1);
} else {
return 0;
}
$_resource_part_2 = str_replace('.php','.cache.php',$_resource_part_1);
$_resource_part_2_length = strlen($_resource_part_2);
}
$_dir = $_compile_dir;
if ($smarty->use_sub_dirs && isset($_compile_id)) {
$_dir .= $_compile_id . $_dir_sep;
}
if (isset($_compile_id)) {
$_compile_id_part = $_compile_dir . $_compile_id . $_dir_sep;
$_compile_id_part_length = strlen($_compile_id_part);
}
$_count = 0;
try {
$_compileDirs = new RecursiveDirectoryIterator($_dir);
// NOTE: UnexpectedValueException thrown for PHP >= 5.3
} catch (Exception $e) {
return 0;
}
$_compile = new RecursiveIteratorIterator($_compileDirs, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($_compile as $_file) {
if (substr(basename($_file->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false)
continue;
$_filepath = (string) $_file;
if ($_file->isDir()) {
if (!$_compile->isDot()) {
// delete folder if empty
@rmdir($_file->getPathname());
}
} else {
$unlink = false;
if ((!isset($_compile_id) || (isset($_filepath[$_compile_id_part_length]) && !strncmp($_filepath, $_compile_id_part, $_compile_id_part_length)))
&& (!isset($resource_name)
|| (isset($_filepath[$_resource_part_1_length])
&& substr_compare($_filepath, $_resource_part_1, -$_resource_part_1_length, $_resource_part_1_length) == 0)
|| (isset($_filepath[$_resource_part_2_length])
&& substr_compare($_filepath, $_resource_part_2, -$_resource_part_2_length, $_resource_part_2_length) == 0))) {
if (isset($exp_time)) {
if (time() - @filemtime($_filepath) >= $exp_time) {
$unlink = true;
}
} else {
$unlink = true;
}
}
if ($unlink && @unlink($_filepath)) {
$_count++;
}
}
}
// clear compiled cache
Smarty_Resource::$sources = array();
Smarty_Resource::$compileds = array();
return $_count;
}
/**
* Return array of tag/attributes of all tags used by an template
*
* @param Smarty_Internal_Template $templae template object
* @return array of tag/attributes
*/
public static function getTags(Smarty_Internal_Template $template)
{
$template->smarty->get_used_tags = true;
$template->compileTemplateSource();
return $template->used_tags;
}
/**
* diagnose Smarty setup
*
* If $errors is secified, the diagnostic report will be appended to the array, rather than being output.
*
* @param Smarty $smarty Smarty instance to test
* @param array $errors array to push results into rather than outputting them
* @return bool status, true if everything is fine, false else
*/
public static function testInstall(Smarty $smarty, &$errors=null)
{
$status = true;
if ($errors === null) {
echo "<PRE>\n";
echo "Smarty Installation test...\n";
echo "Testing template directory...\n";
}
$_stream_resolve_include_path = function_exists('stream_resolve_include_path');
// test if all registered template_dir are accessible
foreach($smarty->getTemplateDir() as $template_dir) {
$_template_dir = $template_dir;
$template_dir = realpath($template_dir);
// resolve include_path or fail existance
if (!$template_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_template_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$template_dir = stream_resolve_include_path($_template_dir);
} else {
$template_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_template_dir);
}
if ($template_dir !== false) {
if ($errors === null) {
echo "$template_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_template_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_template_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
continue;
}
}
if (!is_dir($template_dir)) {
$status = false;
$message = "FAILED: $template_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
} elseif (!is_readable($template_dir)) {
$status = false;
$message = "FAILED: $template_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['template_dir'] = $message;
}
} else {
if ($errors === null) {
echo "$template_dir is OK.\n";
}
}
}
if ($errors === null) {
echo "Testing compile directory...\n";
}
// test if registered compile_dir is accessible
$__compile_dir = $smarty->getCompileDir();
$_compile_dir = realpath($__compile_dir);
if (!$_compile_dir) {
$status = false;
$message = "FAILED: {$__compile_dir} does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} elseif (!is_dir($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} elseif (!is_readable($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} elseif (!is_writable($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not writable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['compile_dir'] = $message;
}
} else {
if ($errors === null) {
echo "{$_compile_dir} is OK.\n";
}
}
if ($errors === null) {
echo "Testing plugins directory...\n";
}
// test if all registered plugins_dir are accessible
// and if core plugins directory is still registered
$_core_plugins_dir = realpath(dirname(__FILE__) .'/../plugins');
$_core_plugins_available = false;
foreach($smarty->getPluginsDir() as $plugin_dir) {
$_plugin_dir = $plugin_dir;
$plugin_dir = realpath($plugin_dir);
// resolve include_path or fail existance
if (!$plugin_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$plugin_dir = stream_resolve_include_path($_plugin_dir);
} else {
$plugin_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_plugin_dir);
}
if ($plugin_dir !== false) {
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_plugin_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_plugin_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
continue;
}
}
if (!is_dir($plugin_dir)) {
$status = false;
$message = "FAILED: $plugin_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
} elseif (!is_readable($plugin_dir)) {
$status = false;
$message = "FAILED: $plugin_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir'] = $message;
}
} elseif ($_core_plugins_dir && $_core_plugins_dir == realpath($plugin_dir)) {
$_core_plugins_available = true;
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
} else {
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
}
}
if (!$_core_plugins_available) {
$status = false;
$message = "WARNING: Smarty's own libs/plugins is not available";
if ($errors === null) {
echo $message . ".\n";
} elseif (!isset($errors['plugins_dir'])) {
$errors['plugins_dir'] = $message;
}
}
if ($errors === null) {
echo "Testing cache directory...\n";
}
// test if all registered cache_dir is accessible
$__cache_dir = $smarty->getCacheDir();
$_cache_dir = realpath($__cache_dir);
if (!$_cache_dir) {
$status = false;
$message = "FAILED: {$__cache_dir} does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} elseif (!is_dir($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} elseif (!is_readable($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} elseif (!is_writable($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not writable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['cache_dir'] = $message;
}
} else {
if ($errors === null) {
echo "{$_cache_dir} is OK.\n";
}
}
if ($errors === null) {
echo "Testing configs directory...\n";
}
// test if all registered config_dir are accessible
foreach($smarty->getConfigDir() as $config_dir) {
$_config_dir = $config_dir;
$config_dir = realpath($config_dir);
// resolve include_path or fail existance
if (!$config_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_config_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$config_dir = stream_resolve_include_path($_config_dir);
} else {
$config_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_config_dir);
}
if ($config_dir !== false) {
if ($errors === null) {
echo "$config_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_config_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_config_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
continue;
}
}
if (!is_dir($config_dir)) {
$status = false;
$message = "FAILED: $config_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
} elseif (!is_readable($config_dir)) {
$status = false;
$message = "FAILED: $config_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['config_dir'] = $message;
}
} else {
if ($errors === null) {
echo "$config_dir is OK.\n";
}
}
}
if ($errors === null) {
echo "Testing sysplugin files...\n";
}
// test if sysplugins are available
$source = SMARTY_SYSPLUGINS_DIR;
if (is_dir($source)) {
$expected = array(
"smarty_cacheresource.php" => true,
"smarty_cacheresource_custom.php" => true,
"smarty_cacheresource_keyvaluestore.php" => true,
"smarty_config_source.php" => true,
"smarty_internal_cacheresource_file.php" => true,
"smarty_internal_compile_append.php" => true,
"smarty_internal_compile_assign.php" => true,
"smarty_internal_compile_block.php" => true,
"smarty_internal_compile_break.php" => true,
"smarty_internal_compile_call.php" => true,
"smarty_internal_compile_capture.php" => true,
"smarty_internal_compile_config_load.php" => true,
"smarty_internal_compile_continue.php" => true,
"smarty_internal_compile_debug.php" => true,
"smarty_internal_compile_eval.php" => true,
"smarty_internal_compile_extends.php" => true,
"smarty_internal_compile_for.php" => true,
"smarty_internal_compile_foreach.php" => true,
"smarty_internal_compile_function.php" => true,
"smarty_internal_compile_if.php" => true,
"smarty_internal_compile_include.php" => true,
"smarty_internal_compile_include_php.php" => true,
"smarty_internal_compile_insert.php" => true,
"smarty_internal_compile_ldelim.php" => true,
"smarty_internal_compile_nocache.php" => true,
"smarty_internal_compile_private_block_plugin.php" => true,
"smarty_internal_compile_private_function_plugin.php" => true,
"smarty_internal_compile_private_modifier.php" => true,
"smarty_internal_compile_private_object_block_function.php" => true,
"smarty_internal_compile_private_object_function.php" => true,
"smarty_internal_compile_private_print_expression.php" => true,
"smarty_internal_compile_private_registered_block.php" => true,
"smarty_internal_compile_private_registered_function.php" => true,
"smarty_internal_compile_private_special_variable.php" => true,
"smarty_internal_compile_rdelim.php" => true,
"smarty_internal_compile_section.php" => true,
"smarty_internal_compile_setfilter.php" => true,
"smarty_internal_compile_while.php" => true,
"smarty_internal_compilebase.php" => true,
"smarty_internal_config.php" => true,
"smarty_internal_config_file_compiler.php" => true,
"smarty_internal_configfilelexer.php" => true,
"smarty_internal_configfileparser.php" => true,
"smarty_internal_data.php" => true,
"smarty_internal_debug.php" => true,
"smarty_internal_filter_handler.php" => true,
"smarty_internal_function_call_handler.php" => true,
"smarty_internal_get_include_path.php" => true,
"smarty_internal_nocache_insert.php" => true,
"smarty_internal_parsetree.php" => true,
"smarty_internal_resource_eval.php" => true,
"smarty_internal_resource_extends.php" => true,
"smarty_internal_resource_file.php" => true,
"smarty_internal_resource_registered.php" => true,
"smarty_internal_resource_stream.php" => true,
"smarty_internal_resource_string.php" => true,
"smarty_internal_smartytemplatecompiler.php" => true,
"smarty_internal_template.php" => true,
"smarty_internal_templatebase.php" => true,
"smarty_internal_templatecompilerbase.php" => true,
"smarty_internal_templatelexer.php" => true,
"smarty_internal_templateparser.php" => true,
"smarty_internal_utility.php" => true,
"smarty_internal_write_file.php" => true,
"smarty_resource.php" => true,
"smarty_resource_custom.php" => true,
"smarty_resource_recompiled.php" => true,
"smarty_resource_uncompiled.php" => true,
"smarty_security.php" => true,
);
$iterator = new DirectoryIterator($source);
foreach ($iterator as $file) {
if (!$file->isDot()) {
$filename = $file->getFilename();
if (isset($expected[$filename])) {
unset($expected[$filename]);
}
}
}
if ($expected) {
$status = false;
$message = "FAILED: files missing from libs/sysplugins: ". join(', ', array_keys($expected));
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['sysplugins'] = $message;
}
} elseif ($errors === null) {
echo "... OK\n";
}
} else {
$status = false;
$message = "FAILED: ". SMARTY_SYSPLUGINS_DIR .' is not a directory';
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['sysplugins_dir_constant'] = $message;
}
}
if ($errors === null) {
echo "Testing plugin files...\n";
}
// test if core plugins are available
$source = SMARTY_PLUGINS_DIR;
if (is_dir($source)) {
$expected = array(
"block.textformat.php" => true,
"function.counter.php" => true,
"function.cycle.php" => true,
"function.fetch.php" => true,
"function.html_checkboxes.php" => true,
"function.html_image.php" => true,
"function.html_options.php" => true,
"function.html_radios.php" => true,
"function.html_select_date.php" => true,
"function.html_select_time.php" => true,
"function.html_table.php" => true,
"function.mailto.php" => true,
"function.math.php" => true,
"modifier.capitalize.php" => true,
"modifier.date_format.php" => true,
"modifier.debug_print_var.php" => true,
"modifier.escape.php" => true,
"modifier.regex_replace.php" => true,
"modifier.replace.php" => true,
"modifier.spacify.php" => true,
"modifier.truncate.php" => true,
"modifiercompiler.cat.php" => true,
"modifiercompiler.count_characters.php" => true,
"modifiercompiler.count_paragraphs.php" => true,
"modifiercompiler.count_sentences.php" => true,
"modifiercompiler.count_words.php" => true,
"modifiercompiler.default.php" => true,
"modifiercompiler.escape.php" => true,
"modifiercompiler.from_charset.php" => true,
"modifiercompiler.indent.php" => true,
"modifiercompiler.lower.php" => true,
"modifiercompiler.noprint.php" => true,
"modifiercompiler.string_format.php" => true,
"modifiercompiler.strip.php" => true,
"modifiercompiler.strip_tags.php" => true,
"modifiercompiler.to_charset.php" => true,
"modifiercompiler.unescape.php" => true,
"modifiercompiler.upper.php" => true,
"modifiercompiler.wordwrap.php" => true,
"outputfilter.trimwhitespace.php" => true,
"shared.escape_special_chars.php" => true,
"shared.literal_compiler_param.php" => true,
"shared.make_timestamp.php" => true,
"shared.mb_str_replace.php" => true,
"shared.mb_unicode.php" => true,
"shared.mb_wordwrap.php" => true,
"variablefilter.htmlspecialchars.php" => true,
);
$iterator = new DirectoryIterator($source);
foreach ($iterator as $file) {
if (!$file->isDot()) {
$filename = $file->getFilename();
if (isset($expected[$filename])) {
unset($expected[$filename]);
}
}
}
if ($expected) {
$status = false;
$message = "FAILED: files missing from libs/plugins: ". join(', ', array_keys($expected));
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins'] = $message;
}
} elseif ($errors === null) {
echo "... OK\n";
}
} else {
$status = false;
$message = "FAILED: ". SMARTY_PLUGINS_DIR .' is not a directory';
if ($errors === null) {
echo $message . ".\n";
} else {
$errors['plugins_dir_constant'] = $message;
}
}
if ($errors === null) {
echo "Tests complete.\n";
echo "</PRE>\n";
}
return $status;
}
}
?> | meetai/2Moons | src/includes/libs/Smarty/sysplugins/smarty_internal_utility.php | PHP | gpl-3.0 | 34,199 |
/*
===========================================================================
Wolfenstein: Enemy Territory GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Wolfenstein: Enemy Territory GPL Source Code (Wolf ET Source Code).
Wolf ET Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Wolf ET Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Wolf: ET Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Wolf ET Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
// Rafael particles
// cg_particles.c
#include "cg_local.h"
#define MUSTARD 1
#define BLOODRED 2
#define EMISIVEFADE 3
#define GREY75 4
#define ZOMBIE 5
typedef struct particle_s
{
struct particle_s *next;
float time;
float endtime;
vec3_t org;
vec3_t vel;
vec3_t accel;
int color;
float colorvel;
float alpha;
float alphavel;
int type;
qhandle_t pshader;
float height;
float width;
float endheight;
float endwidth;
float start;
float end;
float startfade;
qboolean rotate;
int snum;
qboolean link;
// Ridah
int shaderAnim;
int roll;
int accumroll;
} cparticle_t;
typedef enum
{
P_NONE,
P_WEATHER,
P_FLAT,
P_SMOKE,
P_ROTATE,
P_WEATHER_TURBULENT,
P_ANIM, // Ridah
P_DLIGHT_ANIM, // ydnar
P_BLEED,
P_FLAT_SCALEUP,
P_FLAT_SCALEUP_FADE,
P_WEATHER_FLURRY,
P_SMOKE_IMPACT,
P_BUBBLE,
P_BUBBLE_TURBULENT,
P_SPRITE
} particle_type_t;
#define MAX_SHADER_ANIMS 8
#define MAX_SHADER_ANIM_FRAMES 64
static char *shaderAnimNames[MAX_SHADER_ANIMS] = {
"explode1",
"blacksmokeanim",
"twiltb2",
"blacksmokeanimc",
// "expblue",
// "blacksmokeanimb", // uses 'explode1' sequence // JPW NERVE pulled
// "blood",
NULL
};
static qhandle_t shaderAnims[MAX_SHADER_ANIMS][MAX_SHADER_ANIM_FRAMES];
static int shaderAnimCounts[MAX_SHADER_ANIMS] = {
23,
23, // (SA) removing warning messages from startup
45,
23,
25,
23,
5,
};
static float shaderAnimSTRatio[MAX_SHADER_ANIMS] = {
1, // NERVE - SMF - changed from 1.405 to 1
1,
1,
1,
1,
1,
1,
};
static int numShaderAnims;
// done.
#define PARTICLE_GRAVITY 40
#define MAX_PARTICLES 1024 * 8
cparticle_t *active_particles, *free_particles;
cparticle_t particles[MAX_PARTICLES];
int cl_numparticles = MAX_PARTICLES;
qboolean initparticles = qfalse;
vec3_t vforward, vright, vup;
vec3_t rforward, rright, rup;
float oldtime;
/*
===============
CL_ClearParticles
===============
*/
void CG_ClearParticles( void ) {
int i;
memset( particles, 0, sizeof( particles ) );
free_particles = &particles[0];
active_particles = NULL;
for ( i = 0 ; i < cl_numparticles ; i++ )
{
particles[i].next = &particles[i + 1];
particles[i].type = 0;
}
particles[cl_numparticles - 1].next = NULL;
oldtime = cg.time;
// Ridah, init the shaderAnims
for ( i = 0; shaderAnimNames[i]; i++ ) {
int j;
for ( j = 0; j < shaderAnimCounts[i]; j++ ) {
shaderAnims[i][j] = trap_R_RegisterShader( va( "%s%i", shaderAnimNames[i], j + 1 ) );
}
}
numShaderAnims = i;
// done.
initparticles = qtrue;
}
/*
=====================
CG_AddParticleToScene
=====================
*/
#define ROOT_2 1.414213562373f
void CG_AddParticleToScene( cparticle_t *p, vec3_t org, float alpha ) {
vec3_t point;
polyVert_t verts[4];
float width;
float height;
float time, time2;
float ratio;
float invratio;
vec3_t color;
polyVert_t TRIverts[3];
vec3_t rright2, rup2;
if ( p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT || p->type == P_WEATHER_FLURRY
|| p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT ) { // create a front facing polygon
if ( p->type != P_WEATHER_FLURRY ) {
if ( p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT ) {
if ( org[2] > p->end ) {
p->time = cg.time;
VectorCopy( org, p->org ); // Ridah, fixes rare snow flakes that flicker on the ground
p->org[2] = ( p->start + crandom() * 4 );
if ( p->type == P_BUBBLE_TURBULENT ) {
p->vel[0] = crandom() * 4;
p->vel[1] = crandom() * 4;
}
}
} else
{
if ( org[2] < p->end ) {
p->time = cg.time;
VectorCopy( org, p->org ); // Ridah, fixes rare snow flakes that flicker on the ground
while ( p->org[2] < p->end )
{
p->org[2] += ( p->start - p->end );
}
if ( p->type == P_WEATHER_TURBULENT ) {
p->vel[0] = crandom() * 16;
p->vel[1] = crandom() * 16;
}
}
}
// Rafael snow pvs check
if ( !p->link ) {
return;
}
p->alpha = 1;
}
// Ridah, had to do this or MAX_POLYS is being exceeded in village1.bsp
if ( VectorDistanceSquared( cg.snap->ps.origin, org ) > SQR( 1024 ) ) {
return;
}
// done.
if ( p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT ) {
VectorMA( org, -p->height, vup, point );
VectorMA( point, -p->width, vright, point );
VectorCopy( point, verts[0].xyz );
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 255;
verts[0].modulate[1] = 255;
verts[0].modulate[2] = 255;
verts[0].modulate[3] = 255 * p->alpha;
VectorMA( org, -p->height, vup, point );
VectorMA( point, p->width, vright, point );
VectorCopy( point, verts[1].xyz );
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = 255;
verts[1].modulate[1] = 255;
verts[1].modulate[2] = 255;
verts[1].modulate[3] = 255 * p->alpha;
VectorMA( org, p->height, vup, point );
VectorMA( point, p->width, vright, point );
VectorCopy( point, verts[2].xyz );
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = 255;
verts[2].modulate[1] = 255;
verts[2].modulate[2] = 255;
verts[2].modulate[3] = 255 * p->alpha;
VectorMA( org, p->height, vup, point );
VectorMA( point, -p->width, vright, point );
VectorCopy( point, verts[3].xyz );
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = 255;
verts[3].modulate[1] = 255;
verts[3].modulate[2] = 255;
verts[3].modulate[3] = 255 * p->alpha;
} else
{
VectorMA( org, -p->height, vup, point );
VectorMA( point, -p->width, vright, point );
VectorCopy( point, TRIverts[0].xyz );
TRIverts[0].st[0] = 1;
TRIverts[0].st[1] = 0;
TRIverts[0].modulate[0] = 255;
TRIverts[0].modulate[1] = 255;
TRIverts[0].modulate[2] = 255;
TRIverts[0].modulate[3] = 255 * p->alpha;
VectorMA( org, p->height, vup, point );
VectorMA( point, -p->width, vright, point );
VectorCopy( point, TRIverts[1].xyz );
TRIverts[1].st[0] = 0;
TRIverts[1].st[1] = 0;
TRIverts[1].modulate[0] = 255;
TRIverts[1].modulate[1] = 255;
TRIverts[1].modulate[2] = 255;
TRIverts[1].modulate[3] = 255 * p->alpha;
VectorMA( org, p->height, vup, point );
VectorMA( point, p->width, vright, point );
VectorCopy( point, TRIverts[2].xyz );
TRIverts[2].st[0] = 0;
TRIverts[2].st[1] = 1;
TRIverts[2].modulate[0] = 255;
TRIverts[2].modulate[1] = 255;
TRIverts[2].modulate[2] = 255;
TRIverts[2].modulate[3] = 255 * p->alpha;
}
} else if ( p->type == P_SPRITE ) {
vec3_t rr, ru;
vec3_t rotate_ang;
VectorSet( color, 1.0, 1.0, 1.0 );
time = cg.time - p->time;
time2 = p->endtime - p->time;
ratio = time / time2;
width = p->width + ( ratio * ( p->endwidth - p->width ) );
height = p->height + ( ratio * ( p->endheight - p->height ) );
if ( p->roll ) {
vectoangles( cg.refdef_current->viewaxis[0], rotate_ang );
rotate_ang[ROLL] += p->roll;
AngleVectors( rotate_ang, NULL, rr, ru );
}
if ( p->roll ) {
VectorMA( org, -height, ru, point );
VectorMA( point, -width, rr, point );
} else {
VectorMA( org, -height, vup, point );
VectorMA( point, -width, vright, point );
}
VectorCopy( point, verts[0].xyz );
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 255;
verts[0].modulate[1] = 255;
verts[0].modulate[2] = 255;
verts[0].modulate[3] = 255;
if ( p->roll ) {
VectorMA( point, 2 * height, ru, point );
} else {
VectorMA( point, 2 * height, vup, point );
}
VectorCopy( point, verts[1].xyz );
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = 255;
verts[1].modulate[1] = 255;
verts[1].modulate[2] = 255;
verts[1].modulate[3] = 255;
if ( p->roll ) {
VectorMA( point, 2 * width, rr, point );
} else {
VectorMA( point, 2 * width, vright, point );
}
VectorCopy( point, verts[2].xyz );
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = 255;
verts[2].modulate[1] = 255;
verts[2].modulate[2] = 255;
verts[2].modulate[3] = 255;
if ( p->roll ) {
VectorMA( point, -2 * height, ru, point );
} else {
VectorMA( point, -2 * height, vup, point );
}
VectorCopy( point, verts[3].xyz );
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = 255;
verts[3].modulate[1] = 255;
verts[3].modulate[2] = 255;
verts[3].modulate[3] = 255;
} else if ( p->type == P_SMOKE || p->type == P_SMOKE_IMPACT ) { // create a front rotating facing polygon
if ( p->type == P_SMOKE_IMPACT && VectorDistanceSquared( cg.snap->ps.origin, org ) > SQR( 1024 ) ) {
return;
}
if ( p->color == MUSTARD ) {
VectorSet( color, 0.42, 0.33, 0.19 );
} else if ( p->color == BLOODRED ) {
VectorSet( color, 0.22, 0, 0 );
} else if ( p->color == ZOMBIE ) {
VectorSet( color, 0.4, 0.28, 0.23 );
} else if ( p->color == GREY75 ) {
float len;
float greyit;
float val;
len = Distance( cg.snap->ps.origin, org );
if ( !len ) {
len = 1;
}
val = 4096 / len;
greyit = 0.25 * val;
if ( greyit > 0.5 ) {
greyit = 0.5;
}
VectorSet( color, greyit, greyit, greyit );
} else {
VectorSet( color, 1.0, 1.0, 1.0 );
}
time = cg.time - p->time;
time2 = p->endtime - p->time;
ratio = time / time2;
if ( cg.time > p->startfade ) {
invratio = 1 - ( ( cg.time - p->startfade ) / ( p->endtime - p->startfade ) );
if ( p->color == EMISIVEFADE ) {
float fval;
fval = ( invratio * invratio );
if ( fval < 0 ) {
fval = 0;
}
VectorSet( color, fval, fval, fval );
}
invratio *= p->alpha;
} else {
invratio = 1 * p->alpha;
}
if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
invratio = 1;
}
if ( invratio > 1 ) {
invratio = 1;
}
width = p->width + ( ratio * ( p->endwidth - p->width ) );
height = p->height + ( ratio * ( p->endheight - p->height ) );
// if (p->type != P_SMOKE_IMPACT)
{
vec3_t temp;
vectoangles( rforward, temp );
p->accumroll += p->roll;
temp[ROLL] += p->accumroll * 0.1;
// temp[ROLL] += p->roll * 0.1;
AngleVectors( temp, NULL, rright2, rup2 );
}
// else
// {
// VectorCopy (rright, rright2);
// VectorCopy (rup, rup2);
// }
if ( p->rotate ) {
VectorMA( org, -height, rup2, point );
VectorMA( point, -width, rright2, point );
} else
{
VectorMA( org, -p->height, vup, point );
VectorMA( point, -p->width, vright, point );
}
VectorCopy( point, verts[0].xyz );
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 255 * color[0];
verts[0].modulate[1] = 255 * color[1];
verts[0].modulate[2] = 255 * color[2];
verts[0].modulate[3] = 255 * invratio;
if ( p->rotate ) {
VectorMA( org, -height, rup2, point );
VectorMA( point, width, rright2, point );
} else
{
VectorMA( org, -p->height, vup, point );
VectorMA( point, p->width, vright, point );
}
VectorCopy( point, verts[1].xyz );
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = 255 * color[0];
verts[1].modulate[1] = 255 * color[1];
verts[1].modulate[2] = 255 * color[2];
verts[1].modulate[3] = 255 * invratio;
if ( p->rotate ) {
VectorMA( org, height, rup2, point );
VectorMA( point, width, rright2, point );
} else
{
VectorMA( org, p->height, vup, point );
VectorMA( point, p->width, vright, point );
}
VectorCopy( point, verts[2].xyz );
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = 255 * color[0];
verts[2].modulate[1] = 255 * color[1];
verts[2].modulate[2] = 255 * color[2];
verts[2].modulate[3] = 255 * invratio;
if ( p->rotate ) {
VectorMA( org, height, rup2, point );
VectorMA( point, -width, rright2, point );
} else
{
VectorMA( org, p->height, vup, point );
VectorMA( point, -p->width, vright, point );
}
VectorCopy( point, verts[3].xyz );
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = 255 * color[0];
verts[3].modulate[1] = 255 * color[1];
verts[3].modulate[2] = 255 * color[2];
verts[3].modulate[3] = 255 * invratio;
} else if ( p->type == P_BLEED ) {
vec3_t rr, ru;
vec3_t rotate_ang;
float alpha;
alpha = p->alpha;
if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
alpha = 1;
}
if ( p->roll ) {
vectoangles( cg.refdef_current->viewaxis[0], rotate_ang );
rotate_ang[ROLL] += p->roll;
AngleVectors( rotate_ang, NULL, rr, ru );
} else
{
VectorCopy( vup, ru );
VectorCopy( vright, rr );
}
VectorMA( org, -p->height, ru, point );
VectorMA( point, -p->width, rr, point );
VectorCopy( point, verts[0].xyz );
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 111;
verts[0].modulate[1] = 19;
verts[0].modulate[2] = 9;
verts[0].modulate[3] = 255 * alpha;
VectorMA( org, -p->height, ru, point );
VectorMA( point, p->width, rr, point );
VectorCopy( point, verts[1].xyz );
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = 111;
verts[1].modulate[1] = 19;
verts[1].modulate[2] = 9;
verts[1].modulate[3] = 255 * alpha;
VectorMA( org, p->height, ru, point );
VectorMA( point, p->width, rr, point );
VectorCopy( point, verts[2].xyz );
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = 111;
verts[2].modulate[1] = 19;
verts[2].modulate[2] = 9;
verts[2].modulate[3] = 255 * alpha;
VectorMA( org, p->height, ru, point );
VectorMA( point, -p->width, rr, point );
VectorCopy( point, verts[3].xyz );
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = 111;
verts[3].modulate[1] = 19;
verts[3].modulate[2] = 9;
verts[3].modulate[3] = 255 * alpha;
} else if ( p->type == P_FLAT_SCALEUP ) {
float width, height;
float sinR, cosR;
if ( p->color == BLOODRED ) {
VectorSet( color, 1, 1, 1 );
} else {
VectorSet( color, 0.5, 0.5, 0.5 );
}
time = cg.time - p->time;
time2 = p->endtime - p->time;
ratio = time / time2;
width = p->width + ( ratio * ( p->endwidth - p->width ) );
height = p->height + ( ratio * ( p->endheight - p->height ) );
if ( width > p->endwidth ) {
width = p->endwidth;
}
if ( height > p->endheight ) {
height = p->endheight;
}
sinR = height * sin( DEG2RAD( p->roll ) ) * ROOT_2;
cosR = width * cos( DEG2RAD( p->roll ) ) * ROOT_2;
VectorCopy( org, verts[0].xyz );
verts[0].xyz[0] -= sinR;
verts[0].xyz[1] -= cosR;
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 255 * color[0];
verts[0].modulate[1] = 255 * color[1];
verts[0].modulate[2] = 255 * color[2];
verts[0].modulate[3] = 255;
VectorCopy( org, verts[1].xyz );
verts[1].xyz[0] -= cosR;
verts[1].xyz[1] += sinR;
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = verts[0].modulate[0];
verts[1].modulate[1] = verts[0].modulate[1];
verts[1].modulate[2] = verts[0].modulate[2];
verts[1].modulate[3] = verts[0].modulate[3];
VectorCopy( org, verts[2].xyz );
verts[2].xyz[0] += sinR;
verts[2].xyz[1] += cosR;
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = verts[0].modulate[0];
verts[2].modulate[1] = verts[0].modulate[1];
verts[2].modulate[2] = verts[0].modulate[2];
verts[2].modulate[3] = verts[0].modulate[3];
VectorCopy( org, verts[3].xyz );
verts[3].xyz[0] += cosR;
verts[3].xyz[1] -= sinR;
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = verts[0].modulate[0];
verts[3].modulate[1] = verts[0].modulate[1];
verts[3].modulate[2] = verts[0].modulate[2];
verts[3].modulate[3] = verts[0].modulate[3];
} else if ( p->type == P_FLAT ) {
VectorCopy( org, verts[0].xyz );
verts[0].xyz[0] -= p->height;
verts[0].xyz[1] -= p->width;
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 255;
verts[0].modulate[1] = 255;
verts[0].modulate[2] = 255;
verts[0].modulate[3] = 255;
VectorCopy( org, verts[1].xyz );
verts[1].xyz[0] -= p->height;
verts[1].xyz[1] += p->width;
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = 255;
verts[1].modulate[1] = 255;
verts[1].modulate[2] = 255;
verts[1].modulate[3] = 255;
VectorCopy( org, verts[2].xyz );
verts[2].xyz[0] += p->height;
verts[2].xyz[1] += p->width;
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = 255;
verts[2].modulate[1] = 255;
verts[2].modulate[2] = 255;
verts[2].modulate[3] = 255;
VectorCopy( org, verts[3].xyz );
verts[3].xyz[0] += p->height;
verts[3].xyz[1] -= p->width;
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = 255;
verts[3].modulate[1] = 255;
verts[3].modulate[2] = 255;
verts[3].modulate[3] = 255;
}
// Ridah
else if ( p->type == P_ANIM || p->type == P_DLIGHT_ANIM ) { // ydnar
vec3_t rr, ru;
vec3_t rotate_ang;
int i, j;
time = cg.time - p->time;
time2 = p->endtime - p->time;
ratio = time / time2;
if ( ratio >= 1.0 ) {
ratio = 0.9999;
} else if ( ratio < 0.0 ) {
// rain - make sure that ratio isn't negative or
// we'll walk out of bounds when j is calculated below
ratio = 0.0001;
}
width = p->width + ( ratio * ( p->endwidth - p->width ) );
height = p->height + ( ratio * ( p->endheight - p->height ) );
// ydnar: add dlight if necessary
if ( p->type == P_DLIGHT_ANIM ) {
// fixme: support arbitrary color
trap_R_AddLightToScene( org, 320, //% 1.5 * (width > height ? width : height),
1.25 * ( 1.0 - ratio ), 1.0, 0.95, 0.85, 0, 0 );
}
// if we are "inside" this sprite, don't draw
if ( VectorDistanceSquared( cg.snap->ps.origin, org ) < SQR( width / 1.5f ) ) {
return;
}
i = p->shaderAnim;
j = (int)floor( ratio * shaderAnimCounts[p->shaderAnim] );
p->pshader = shaderAnims[i][j];
// JPW NERVE more particle testing
if ( cg_fxflags & 1 ) {
p->roll = 0;
p->pshader = getTestShader();
rotate_ang[ROLL] = 90;
}
// jpw
if ( p->roll ) {
vectoangles( cg.refdef_current->viewaxis[0], rotate_ang );
rotate_ang[ROLL] += p->roll;
AngleVectors( rotate_ang, NULL, rr, ru );
}
if ( p->roll ) {
VectorMA( org, -height, ru, point );
VectorMA( point, -width, rr, point );
} else {
VectorMA( org, -height, vup, point );
VectorMA( point, -width, vright, point );
}
VectorCopy( point, verts[0].xyz );
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[0].modulate[0] = 255;
verts[0].modulate[1] = 255;
verts[0].modulate[2] = 255;
verts[0].modulate[3] = 255;
if ( p->roll ) {
VectorMA( point, 2 * height, ru, point );
} else {
VectorMA( point, 2 * height, vup, point );
}
VectorCopy( point, verts[1].xyz );
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[1].modulate[0] = 255;
verts[1].modulate[1] = 255;
verts[1].modulate[2] = 255;
verts[1].modulate[3] = 255;
if ( p->roll ) {
VectorMA( point, 2 * width, rr, point );
} else {
VectorMA( point, 2 * width, vright, point );
}
VectorCopy( point, verts[2].xyz );
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[2].modulate[0] = 255;
verts[2].modulate[1] = 255;
verts[2].modulate[2] = 255;
verts[2].modulate[3] = 255;
if ( p->roll ) {
VectorMA( point, -2 * height, ru, point );
} else {
VectorMA( point, -2 * height, vup, point );
}
VectorCopy( point, verts[3].xyz );
verts[3].st[0] = 1;
verts[3].st[1] = 0;
verts[3].modulate[0] = 255;
verts[3].modulate[1] = 255;
verts[3].modulate[2] = 255;
verts[3].modulate[3] = 255;
}
// done.
if ( !cg_wolfparticles.integer ) {
return;
}
if ( !p->pshader ) {
// (SA) temp commented out for DM again. FIXME: TODO: this needs to be addressed
// CG_Printf ("CG_AddParticleToScene type %d p->pshader == ZERO\n", p->type);
return;
}
if ( p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT || p->type == P_WEATHER_FLURRY ) {
trap_R_AddPolyToScene( p->pshader, 3, TRIverts );
} else {
trap_R_AddPolyToScene( p->pshader, 4, verts );
}
}
// Ridah, made this static so it doesn't interfere with other files
static float roll = 0.0;
/*
===============
CG_AddParticles
===============
*/
void CG_AddParticles( void ) {
cparticle_t *p, *next;
float alpha;
float time, time2;
vec3_t org;
int color;
cparticle_t *active, *tail;
int type;
vec3_t rotate_ang;
if ( !initparticles ) {
CG_ClearParticles();
}
VectorCopy( cg.refdef_current->viewaxis[0], vforward );
VectorCopy( cg.refdef_current->viewaxis[1], vright );
VectorCopy( cg.refdef_current->viewaxis[2], vup );
vectoangles( cg.refdef_current->viewaxis[0], rotate_ang );
roll += ( ( cg.time - oldtime ) * 0.1 ) ;
rotate_ang[ROLL] += ( roll * 0.9 );
AngleVectors( rotate_ang, rforward, rright, rup );
oldtime = cg.time;
active = NULL;
tail = NULL;
for ( p = active_particles ; p ; p = next )
{
next = p->next;
time = ( cg.time - p->time ) * 0.001;
alpha = p->alpha + time * p->alphavel;
if ( alpha <= 0 ) { // faded out
p->next = free_particles;
free_particles = p;
p->type = 0;
p->color = 0;
p->alpha = 0;
continue;
}
if ( p->type == P_SMOKE || p->type == P_ANIM || p->type == P_DLIGHT_ANIM || p->type == P_BLEED || p->type == P_SMOKE_IMPACT ) {
if ( cg.time > p->endtime ) {
p->next = free_particles;
free_particles = p;
p->type = 0;
p->color = 0;
p->alpha = 0;
continue;
}
}
if ( p->type == P_WEATHER_FLURRY ) {
if ( cg.time > p->endtime ) {
p->next = free_particles;
free_particles = p;
p->type = 0;
p->color = 0;
p->alpha = 0;
continue;
}
}
if ( p->type == P_FLAT_SCALEUP_FADE ) {
if ( cg.time > p->endtime ) {
p->next = free_particles;
free_particles = p;
p->type = 0;
p->color = 0;
p->alpha = 0;
continue;
}
}
if ( p->type == P_SPRITE && p->endtime < 0 ) {
// temporary sprite
CG_AddParticleToScene( p, p->org, alpha );
p->next = free_particles;
free_particles = p;
p->type = 0;
p->color = 0;
p->alpha = 0;
continue;
}
p->next = NULL;
if ( !tail ) {
active = tail = p;
} else
{
tail->next = p;
tail = p;
}
if ( alpha > 1.0 ) {
alpha = 1;
}
color = p->color;
time2 = time * time;
org[0] = p->org[0] + p->vel[0] * time + p->accel[0] * time2;
org[1] = p->org[1] + p->vel[1] * time + p->accel[1] * time2;
org[2] = p->org[2] + p->vel[2] * time + p->accel[2] * time2;
type = p->type;
CG_AddParticleToScene( p, org, alpha );
}
active_particles = active;
}
/*
======================
CG_AddParticles
======================
*/
void CG_ParticleSnowFlurry( qhandle_t pshader, centity_t *cent ) {
cparticle_t *p;
qboolean turb = qtrue;
if ( !pshader ) {
CG_Printf( "CG_ParticleSnowFlurry pshader == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->color = 0;
p->alpha = 0.90;
p->alphavel = 0;
p->start = cent->currentState.origin2[0];
p->end = cent->currentState.origin2[1];
p->endtime = cg.time + cent->currentState.time;
p->startfade = cg.time + cent->currentState.time2;
p->pshader = pshader;
if ( rand() % 100 > 90 ) {
p->height = 32;
p->width = 32;
p->alpha = 0.10;
} else
{
p->height = 1;
p->width = 1;
}
p->vel[2] = -20;
p->type = P_WEATHER_FLURRY;
if ( turb ) {
p->vel[2] = -10;
}
VectorCopy( cent->currentState.origin, p->org );
p->org[0] = p->org[0];
p->org[1] = p->org[1];
p->org[2] = p->org[2];
p->vel[0] = p->vel[1] = 0;
p->accel[0] = p->accel[1] = p->accel[2] = 0;
p->vel[0] += cent->currentState.angles[0] * 32 + ( crandom() * 16 );
p->vel[1] += cent->currentState.angles[1] * 32 + ( crandom() * 16 );
p->vel[2] += cent->currentState.angles[2];
if ( turb ) {
p->accel[0] = crandom() * 16;
p->accel[1] = crandom() * 16;
}
}
void CG_ParticleSnow( qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum ) {
cparticle_t *p;
if ( !pshader ) {
CG_Printf( "CG_ParticleSnow pshader == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->color = 0;
p->alpha = 0.40;
p->alphavel = 0;
p->start = origin[2];
p->end = origin2[2];
p->pshader = pshader;
p->height = 1;
p->width = 1;
p->vel[2] = -50;
if ( turb ) {
p->type = P_WEATHER_TURBULENT;
p->vel[2] = -50 * 1.3;
} else
{
p->type = P_WEATHER;
}
VectorCopy( origin, p->org );
p->org[0] = p->org[0] + ( crandom() * range );
p->org[1] = p->org[1] + ( crandom() * range );
p->org[2] = p->org[2] + ( crandom() * ( p->start - p->end ) );
p->vel[0] = p->vel[1] = 0;
p->accel[0] = p->accel[1] = p->accel[2] = 0;
if ( turb ) {
p->vel[0] = crandom() * 16;
p->vel[1] = crandom() * 16;
}
// Rafael snow pvs check
p->snum = snum;
p->link = qtrue;
}
void CG_ParticleBubble( qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum ) {
cparticle_t *p;
float randsize;
if ( !pshader ) {
CG_Printf( "CG_ParticleSnow pshader == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->color = 0;
p->alpha = 0.40;
p->alphavel = 0;
p->start = origin[2];
p->end = origin2[2];
p->pshader = pshader;
randsize = 1 + ( crandom() * 0.5 );
p->height = randsize;
p->width = randsize;
p->vel[2] = 50 + ( crandom() * 10 );
if ( turb ) {
p->type = P_BUBBLE_TURBULENT;
p->vel[2] = 50 * 1.3;
} else
{
p->type = P_BUBBLE;
}
VectorCopy( origin, p->org );
p->org[0] = p->org[0] + ( crandom() * range );
p->org[1] = p->org[1] + ( crandom() * range );
p->org[2] = p->org[2] + ( crandom() * ( p->start - p->end ) );
p->vel[0] = p->vel[1] = 0;
p->accel[0] = p->accel[1] = p->accel[2] = 0;
if ( turb ) {
p->vel[0] = crandom() * 4;
p->vel[1] = crandom() * 4;
}
// Rafael snow pvs check
p->snum = snum;
p->link = qtrue;
}
void CG_ParticleSmoke( qhandle_t pshader, centity_t *cent ) {
// using cent->density = enttime
// cent->frame = startfade
cparticle_t *p;
vec3_t dir;
if ( !pshader ) {
CG_Printf( "CG_ParticleSmoke == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->endtime = cg.time + cent->currentState.time;
p->startfade = cg.time + cent->currentState.time2;
p->color = 0;
p->alpha = 1.0;
p->alphavel = 0;
p->start = cent->currentState.origin[2];
p->end = cent->currentState.origin2[2];
p->pshader = pshader;
if ( cent->currentState.density == 1 || cent->currentState.modelindex2 ) {
p->rotate = qfalse;
p->height = 8;
p->width = 8;
p->endheight = 32;
p->endwidth = 32;
} else if ( cent->currentState.density == 2 ) {
p->rotate = qtrue;
p->height = 4;
p->width = 4;
p->endheight = 8;
p->endwidth = 8;
} else if ( cent->currentState.density == 3 ) {
p->rotate = qfalse;
{
float scale;
scale = 16 + ( crandom() * 8 );
p->height = 24 + scale;
p->width = 24 + scale;
p->endheight = 64 + scale;
p->endwidth = 64 + scale;
}
} else if ( cent->currentState.density == 4 ) { // white smoke
p->rotate = qtrue;
p->height = cent->currentState.angles2[0];
p->width = cent->currentState.angles2[0];
p->endheight = cent->currentState.angles2[1];
p->endwidth = cent->currentState.angles2[1];
p->color = GREY75;
} else if ( cent->currentState.density == 5 ) { // mustard gas
p->rotate = qtrue;
p->height = cent->currentState.angles2[0];
p->width = cent->currentState.angles2[0];
p->endheight = cent->currentState.angles2[1];
p->endwidth = cent->currentState.angles2[1];
p->color = MUSTARD;
p->alpha = 0.75;
} else // black smoke
{
p->rotate = qtrue;
p->height = cent->currentState.angles2[0];
p->width = cent->currentState.angles2[0];
p->endheight = cent->currentState.angles2[1];
p->endwidth = cent->currentState.angles2[1];
{
int rval;
rval = rand() % 6;
if ( rval == 1 ) {
p->pshader = cgs.media.smokePuffShaderb1;
} else if ( rval == 2 ) {
p->pshader = cgs.media.smokePuffShaderb2;
} else if ( rval == 3 ) {
p->pshader = cgs.media.smokePuffShaderb3;
} else if ( rval == 4 ) {
p->pshader = cgs.media.smokePuffShaderb4;
} else {
p->pshader = cgs.media.smokePuffShaderb5;
}
}
}
p->type = P_SMOKE;
//VectorCopy(cent->currentState.origin, p->org);
VectorCopy( cent->lerpOrigin, p->org );
p->vel[0] = p->vel[1] = 0;
p->accel[0] = p->accel[1] = p->accel[2] = 0;
if ( cent->currentState.density == 1 ) {
p->vel[2] = 5;
} else if ( cent->currentState.density == 2 ) {
p->vel[2] = 5;
} else if ( cent->currentState.density == 3 ) { // cannon
VectorCopy( cent->currentState.origin2, dir );
p->vel[0] = dir[0] * 128 + ( crandom() * 64 );
p->vel[1] = dir[1] * 128 + ( crandom() * 64 );
p->vel[2] = 15 + ( crandom() * 16 );
} else if ( cent->currentState.density == 5 ) { // gas or cover smoke
VectorCopy( cent->currentState.origin2, dir );
p->vel[0] = dir[0] * 32 + ( crandom() * 16 );
p->vel[1] = dir[1] * 32 + ( crandom() * 16 );
p->vel[2] = 4 + ( crandom() * 2 );
} else // smoke
{
VectorCopy( cent->currentState.origin2, dir );
p->vel[0] = dir[0] + ( crandom() * p->height );
p->vel[1] = dir[1] + ( crandom() * p->height );
p->vel[2] = cent->currentState.angles2[2];
}
if ( cent->currentState.frame == 1 ) { // reverse gravity
p->vel[2] *= -1;
}
p->roll = 8 + ( crandom() * 4 );
}
void CG_ParticleBulletDebris( vec3_t org, vec3_t vel, int duration ) {
cparticle_t *p;
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->endtime = cg.time + duration;
p->startfade = cg.time + duration / 2;
p->color = EMISIVEFADE;
p->alpha = 1.0;
p->alphavel = 0;
p->height = 0.5;
p->width = 0.5;
p->endheight = 0.5;
p->endwidth = 0.5;
p->pshader = cgs.media.tracerShader;
p->type = P_SMOKE;
VectorCopy( org, p->org );
p->vel[0] = vel[0];
p->vel[1] = vel[1];
p->vel[2] = vel[2];
p->accel[0] = p->accel[1] = p->accel[2] = 0;
p->accel[2] = -60;
p->vel[2] += -20;
}
// DHM - Nerve :: bullets hitting dirt
void CG_ParticleDirtBulletDebris( vec3_t org, vec3_t vel, int duration ) {
int r = rand() % 3;
cparticle_t *p;
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->endtime = cg.time + duration;
p->startfade = cg.time + duration / 2;
p->color = EMISIVEFADE;
p->alpha = 1.0;
p->alphavel = 0;
p->height = 1.2;
p->width = 1.2;
p->endheight = 4.5;
p->endwidth = 4.5;
if ( r == 0 ) {
p->pshader = cgs.media.dirtParticle1Shader;
} else if ( r == 1 ) {
p->pshader = cgs.media.dirtParticle2Shader;
} else {
p->pshader = cgs.media.dirtParticle3Shader;
}
p->type = P_SMOKE;
VectorCopy( org, p->org );
p->vel[0] = vel[0];
p->vel[1] = vel[1];
p->vel[2] = vel[2];
p->accel[0] = p->accel[1] = p->accel[2] = 0;
p->accel[2] = -330;
p->vel[2] += -20;
}
// NERVE - SMF :: the core of the dirt explosion
void CG_ParticleDirtBulletDebris_Core( vec3_t org, vec3_t vel, int duration, float width, float height, float alpha, qhandle_t shader ) {
cparticle_t *p;
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->endtime = cg.time + duration;
p->startfade = cg.time + duration / 2;
p->color = EMISIVEFADE;
p->alpha = alpha;
p->alphavel = 0;
p->height = width;
p->width = height;
p->endheight = p->height;
p->endwidth = p->width;
p->rotate = 0;
p->type = P_SMOKE;
p->pshader = shader;
if ( cg_fxflags & 1 ) {
p->pshader = getTestShader();
p->rotate = 0;
p->roll = 0;
p->type = P_SPRITE;
}
VectorCopy( org, p->org );
VectorCopy( vel, p->vel );
VectorSet( p->accel, 0, 0, -330 );
}
// DHM - Nerve :: end
/*
======================
CG_ParticleExplosion
======================
*/
void CG_ParticleExplosion( char *animStr, vec3_t origin, vec3_t vel, int duration, int sizeStart, int sizeEnd, qboolean dlight ) {
cparticle_t *p;
int anim;
#if 0 // rain - this is arguably not legal... it seems to mostly be a
// debugging thing anyway, so I'm killing it for now
if ( animStr < (char *)10 ) {
CG_Error( "CG_ParticleExplosion: animStr is probably an index rather than a string" );
}
#endif
// find the animation string
for ( anim = 0; shaderAnimNames[anim]; anim++ ) {
if ( !Q_stricmp( animStr, shaderAnimNames[anim] ) ) {
break;
}
}
if ( !shaderAnimNames[anim] ) {
CG_Error( "CG_ParticleExplosion: unknown animation string: %s\n", animStr );
return;
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = 1.0;
p->alphavel = 0;
if ( duration < 0 ) {
duration *= -1;
p->roll = 0;
} else {
p->roll = crandom() * 179;
}
p->shaderAnim = anim;
p->width = sizeStart;
p->height = sizeStart * shaderAnimSTRatio[anim]; // for sprites that are stretch in either direction
p->endheight = sizeEnd;
p->endwidth = sizeEnd * shaderAnimSTRatio[anim];
p->endtime = cg.time + duration;
// ydnar
if ( dlight ) {
p->type = P_DLIGHT_ANIM;
} else {
p->type = P_ANIM;
}
VectorCopy( origin, p->org );
VectorCopy( vel, p->vel );
VectorClear( p->accel );
}
// Rafael Shrapnel
void CG_AddParticleShrapnel( localEntity_t *le ) {
return;
}
// done.
int CG_NewParticleArea( int num ) {
// const char *str;
char *str;
char *token;
int type;
vec3_t origin, origin2;
int i;
float range = 0;
int turb;
int numparticles;
int snum;
str = (char *) CG_ConfigString( num );
if ( !str[0] ) {
return ( 0 );
}
// returns type 128 64 or 32
token = COM_Parse( &str );
type = atoi( token );
if ( type == 1 ) {
range = 128;
} else if ( type == 2 ) {
range = 64;
} else if ( type == 3 ) {
range = 32;
} else if ( type == 0 ) {
range = 256;
} else if ( type == 4 ) {
range = 8;
} else if ( type == 5 ) {
range = 16;
} else if ( type == 6 ) {
range = 32;
} else if ( type == 7 ) {
range = 64;
}
for ( i = 0; i < 3; i++ )
{
token = COM_Parse( &str );
origin[i] = atof( token );
}
for ( i = 0; i < 3; i++ )
{
token = COM_Parse( &str );
origin2[i] = atof( token );
}
token = COM_Parse( &str );
numparticles = atoi( token );
token = COM_Parse( &str );
turb = atoi( token );
token = COM_Parse( &str );
snum = atoi( token );
for ( i = 0; i < numparticles; i++ )
{
if ( type >= 4 ) {
CG_ParticleBubble( cgs.media.waterBubbleShader, origin, origin2, turb, range, snum );
} else {
CG_ParticleSnow( cgs.media.snowShader, origin, origin2, turb, range, snum );
}
}
return ( 1 );
}
void CG_SnowLink( centity_t *cent, qboolean particleOn ) {
cparticle_t *p, *next;
int id;
id = cent->currentState.frame;
for ( p = active_particles ; p ; p = next )
{
next = p->next;
if ( p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT ) {
if ( p->snum == id ) {
if ( particleOn ) {
p->link = qtrue;
} else {
p->link = qfalse;
}
}
}
}
}
void CG_ParticleImpactSmokePuffExtended( qhandle_t pshader, vec3_t origin, int lifetime, int vel, int acc, int maxroll, float alpha, float size ) {
cparticle_t *p;
if ( !pshader ) {
CG_Printf( "CG_ParticleImpactSmokePuff pshader == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = alpha;
p->alphavel = 0;
// (SA) roll either direction
p->roll = rand() % ( 2 * maxroll );
// p->roll = crandom()*(float)(maxroll*2);
p->roll -= maxroll;
p->pshader = pshader;
p->endtime = cg.time + lifetime;
p->startfade = cg.time + 100;
// xkan, 1/10/2003 - changed calculation to prevent division by 0 for small size
p->width = size * ( 1.0 + random() * 0.5 ); // rand()%(int)(size * .5f) + size;
p->height = size * ( 1.0 + random() * 0.5 ); // rand()%(int)(size * .5f) + size;
p->endheight = p->height * 2;
p->endwidth = p->width * 2;
p->type = P_SMOKE_IMPACT;
VectorCopy( origin, p->org );
VectorSet( p->vel, 0, 0, vel );
VectorSet( p->accel, 0, 0, acc );
p->rotate = qtrue;
}
void CG_ParticleImpactSmokePuff( qhandle_t pshader, vec3_t origin ) {
CG_ParticleImpactSmokePuffExtended( pshader, origin, 500, 20, 20, 30, 0.25f, 8.f );
}
void CG_Particle_Bleed( qhandle_t pshader, vec3_t start, vec3_t dir, int fleshEntityNum, int duration ) {
cparticle_t *p;
if ( !pshader ) {
CG_Printf( "CG_Particle_Bleed pshader == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = 1.0;
p->alphavel = 0;
p->roll = 0;
p->pshader = pshader;
p->endtime = cg.time + duration;
if ( fleshEntityNum ) {
p->startfade = cg.time;
} else {
p->startfade = cg.time + 100;
}
p->width = 4;
p->height = 4;
p->endheight = 4 + rand() % 3;
p->endwidth = p->endheight;
p->type = P_SMOKE;
VectorCopy( start, p->org );
p->vel[0] = 0;
p->vel[1] = 0;
p->vel[2] = -20;
VectorClear( p->accel );
p->rotate = qfalse;
p->roll = rand() % 179;
if ( fleshEntityNum ) {
p->color = MUSTARD;
} else {
p->color = BLOODRED;
}
p->alpha = 0.75;
}
//void CG_Particle_OilParticle (qhandle_t pshader, centity_t *cent)
void CG_Particle_OilParticle( qhandle_t pshader, vec3_t origin, vec3_t dir, int ptime, int snum ) { // snum is parent ent number?
cparticle_t *p;
int time;
int time2;
float ratio;
// float duration = 1500;
float duration = 2000;
time = cg.time;
time2 = cg.time + ptime;
ratio = (float)1 - ( (float)time / (float)time2 );
if ( !pshader ) {
CG_Printf( "CG_Particle_OilParticle == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alphavel = 0;
p->roll = 0;
p->pshader = pshader;
p->endtime = cg.time + duration;
p->startfade = p->endtime;
p->width = 2;
p->height = 2;
p->endwidth = 1;
p->endheight = 1;
p->type = P_SMOKE;
VectorCopy( origin, p->org );
p->vel[0] = ( dir[0] * ( 16 * ratio ) );
p->vel[1] = ( dir[1] * ( 16 * ratio ) );
p->vel[2] = ( dir[2] * ( 16 * ratio ) );
// p->vel[2] = (dir[2]);
p->snum = snum;
VectorClear( p->accel );
p->accel[2] = -20;
p->rotate = qfalse;
p->roll = rand() % 179;
p->alpha = 0.5;
p->color = BLOODRED;
}
void CG_Particle_OilSlick( qhandle_t pshader, centity_t *cent ) {
cparticle_t *p;
if ( !pshader ) {
CG_Printf( "CG_Particle_OilSlick == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
if ( cent->currentState.angles2[2] ) {
p->endtime = cg.time + cent->currentState.angles2[2];
} else {
p->endtime = cg.time + 60000;
}
p->startfade = p->endtime;
p->alpha = 1.0;
p->alphavel = 0;
p->roll = 0;
p->pshader = pshader;
if ( cent->currentState.angles2[0] || cent->currentState.angles2[1] ) {
p->width = cent->currentState.angles2[0];
p->height = cent->currentState.angles2[0];
p->endheight = cent->currentState.angles2[1];
p->endwidth = cent->currentState.angles2[1];
} else
{
p->width = 8;
p->height = 8;
p->endheight = 16;
p->endwidth = 16;
}
p->type = P_FLAT_SCALEUP;
p->snum = cent->currentState.density;
VectorCopy( cent->currentState.origin, p->org );
p->org[2] += 0.55 + ( crandom() * 0.5 );
p->vel[0] = 0;
p->vel[1] = 0;
p->vel[2] = 0;
VectorClear( p->accel );
p->rotate = qfalse;
p->roll = rand() % 179;
p->alpha = 0.75;
}
void CG_OilSlickRemove( centity_t *cent ) {
cparticle_t *p, *next;
int id;
id = cent->currentState.density;
if ( !id ) {
CG_Printf( "CG_OilSlickRevove NULL id\n" );
}
for ( p = active_particles ; p ; p = next )
{
next = p->next;
if ( p->type == P_FLAT_SCALEUP ) {
if ( p->snum == id ) {
p->endtime = cg.time + 100;
p->startfade = p->endtime;
p->type = P_FLAT_SCALEUP_FADE;
}
}
}
}
qboolean ValidBloodPool( vec3_t start ) {
#define EXTRUDE_DIST 0.5
vec3_t angles;
vec3_t right, up;
vec3_t this_pos, x_pos, center_pos, end_pos;
float x, y;
float fwidth, fheight;
trace_t trace;
vec3_t normal;
fwidth = 16;
fheight = 16;
VectorSet( normal, 0, 0, 1 );
vectoangles( normal, angles );
AngleVectors( angles, NULL, right, up );
VectorMA( start, EXTRUDE_DIST, normal, center_pos );
for ( x = -fwidth / 2; x < fwidth; x += fwidth )
{
VectorMA( center_pos, x, right, x_pos );
for ( y = -fheight / 2; y < fheight; y += fheight )
{
VectorMA( x_pos, y, up, this_pos );
VectorMA( this_pos, -EXTRUDE_DIST * 2, normal, end_pos );
CG_Trace( &trace, this_pos, NULL, NULL, end_pos, -1, CONTENTS_SOLID );
if ( trace.entityNum < ( MAX_ENTITIES - 1 ) ) { // may only land on world
return qfalse;
}
if ( !( !trace.startsolid && trace.fraction < 1 ) ) {
return qfalse;
}
}
}
return qtrue;
}
#define NORMALSIZE 16
#define LARGESIZE 32
void CG_ParticleBloodCloud( centity_t *cent, vec3_t origin, vec3_t dir ) {
float length;
float dist;
float crittersize;
vec3_t angles, forward;
vec3_t point;
cparticle_t *p;
int i;
dist = 0;
length = VectorLength( dir );
vectoangles( dir, angles );
AngleVectors( angles, forward, NULL, NULL );
if ( cent->currentState.density == 0 ) { // normal ai size
crittersize = NORMALSIZE;
} else {
crittersize = LARGESIZE;
}
if ( length ) {
dist = length / crittersize;
}
if ( dist < 1 ) {
dist = 1;
}
VectorCopy( origin, point );
for ( i = 0; i < dist; i++ )
{
VectorMA( point, crittersize, forward, point );
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = 1.0;
p->alphavel = 0;
p->roll = 0;
p->pshader = cgs.media.smokePuffShader;
p->endtime = cg.time + 350 + ( crandom() * 100 );
p->startfade = cg.time;
if ( cent->currentState.density == 0 ) { // normal ai size
p->width = NORMALSIZE;
p->height = NORMALSIZE;
p->endheight = NORMALSIZE;
p->endwidth = NORMALSIZE;
} else // large frame
{
p->width = LARGESIZE;
p->height = LARGESIZE;
p->endheight = LARGESIZE;
p->endwidth = LARGESIZE;
}
p->type = P_SMOKE;
VectorCopy( origin, p->org );
p->vel[0] = 0;
p->vel[1] = 0;
p->vel[2] = -1;
VectorClear( p->accel );
p->rotate = qfalse;
p->roll = rand() % 179;
p->color = BLOODRED;
p->alpha = 0.75;
}
}
void CG_ParticleBloodCloudZombie( centity_t *cent, vec3_t origin, vec3_t dir ) {
float length;
float dist;
float crittersize;
vec3_t angles, forward;
vec3_t point;
cparticle_t *p;
int i;
dist = 0;
length = VectorLength( dir );
vectoangles( dir, angles );
AngleVectors( angles, forward, NULL, NULL );
if ( cent->currentState.density == 0 ) { // normal ai size
crittersize = NORMALSIZE / 4;
} else {
crittersize = LARGESIZE / 3;
}
if ( length ) {
dist = length / crittersize;
}
if ( dist < 1 ) {
dist = 1;
}
VectorCopy( origin, point );
for ( i = 0; i < dist; i++ )
{
VectorMA( point, crittersize, forward, point );
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = 0.2;
p->alphavel = 0;
p->roll = 0;
p->pshader = cgs.media.bloodCloudShader;
// RF, stay around for long enough to expand and dissipate naturally
if ( length ) {
p->endtime = cg.time + 3500 + ( crandom() * 2000 );
} else {
p->endtime = cg.time + 750 + ( crandom() * 500 );
}
p->startfade = cg.time;
if ( cent->currentState.density == 0 ) { // normal ai size
p->width = NORMALSIZE;
p->height = NORMALSIZE;
// RF, expand while falling
p->endheight = NORMALSIZE * 4.0;
p->endwidth = NORMALSIZE * 4.0;
} else // large frame
{
p->width = LARGESIZE;
p->height = LARGESIZE;
// RF, expand while falling
p->endheight = LARGESIZE * 3.0;
p->endwidth = LARGESIZE * 3.0;
}
if ( !length ) {
p->width *= 0.2;
p->height *= 0.2;
p->endheight = NORMALSIZE;
p->endwidth = NORMALSIZE;
}
p->type = P_SMOKE;
VectorCopy( origin, p->org );
p->vel[0] = crandom() * 6;
p->vel[1] = crandom() * 6;
p->vel[2] = random() * 6;
// RF, add some gravity/randomness
p->accel[0] = crandom() * 3;
p->accel[1] = crandom() * 3;
p->accel[2] = -PARTICLE_GRAVITY * 0.2;
VectorClear( p->accel );
p->rotate = qfalse;
p->roll = rand() % 179;
p->color = ZOMBIE;
}
}
void CG_ParticleSparks( vec3_t org, vec3_t vel, int duration, float x, float y, float speed ) {
cparticle_t *p;
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->endtime = cg.time + duration;
p->startfade = cg.time + duration / 2;
p->color = EMISIVEFADE;
p->alpha = 0.4;
p->alphavel = 0;
p->height = 0.5;
p->width = 0.5;
p->endheight = 0.5;
p->endwidth = 0.5;
p->pshader = cgs.media.tracerShader;
p->type = P_SMOKE;
VectorCopy( org, p->org );
p->org[0] += ( crandom() * x );
p->org[1] += ( crandom() * y );
p->vel[0] = vel[0];
p->vel[1] = vel[1];
p->vel[2] = vel[2];
p->accel[0] = p->accel[1] = p->accel[2] = 0;
p->vel[0] += ( crandom() * 4 );
p->vel[1] += ( crandom() * 4 );
p->vel[2] += ( 20 + ( crandom() * 10 ) ) * speed;
p->accel[0] = crandom() * 4;
p->accel[1] = crandom() * 4;
}
void CG_ParticleDust( centity_t *cent, vec3_t origin, vec3_t dir ) {
float length;
float dist;
float crittersize;
vec3_t angles, forward;
vec3_t point;
cparticle_t *p;
int i;
dist = 0;
VectorNegate( dir, dir );
length = VectorLength( dir );
vectoangles( dir, angles );
AngleVectors( angles, forward, NULL, NULL );
if ( cent->currentState.density == 0 ) { // normal ai size
crittersize = NORMALSIZE;
} else {
crittersize = LARGESIZE;
}
if ( length ) {
dist = length / crittersize;
}
if ( dist < 1 ) {
dist = 1;
}
VectorCopy( origin, point );
for ( i = 0; i < dist; i++ )
{
VectorMA( point, crittersize, forward, point );
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = 5.0;
p->alphavel = 0;
p->roll = 0;
p->pshader = cgs.media.bloodCloudShader;
// RF, stay around for long enough to expand and dissipate naturally
if ( length ) {
p->endtime = cg.time + 4500 + ( crandom() * 3500 );
} else {
p->endtime = cg.time + 750 + ( crandom() * 500 );
}
p->startfade = cg.time;
if ( cent->currentState.density == 0 ) { // normal ai size
p->width = NORMALSIZE;
p->height = NORMALSIZE;
// RF, expand while falling
p->endheight = NORMALSIZE * 4.0;
p->endwidth = NORMALSIZE * 4.0;
} else // large frame
{
p->width = LARGESIZE;
p->height = LARGESIZE;
// RF, expand while falling
p->endheight = LARGESIZE * 3.0;
p->endwidth = LARGESIZE * 3.0;
}
if ( !length ) {
p->width *= 0.2;
p->height *= 0.2;
p->endheight = NORMALSIZE;
p->endwidth = NORMALSIZE;
}
p->type = P_SMOKE;
VectorCopy( point, p->org );
p->vel[0] = crandom() * 6;
p->vel[1] = crandom() * 6;
p->vel[2] = random() * 20;
// RF, add some gravity/randomness
p->accel[0] = crandom() * 3;
p->accel[1] = crandom() * 3;
p->accel[2] = -PARTICLE_GRAVITY * 0.4;
VectorClear( p->accel );
p->rotate = qfalse;
p->roll = rand() % 179;
if ( cent->currentState.density ) {
p->color = GREY75;
} else {
p->color = MUSTARD;
}
p->alpha = 0.75;
}
}
void CG_ParticleMisc( qhandle_t pshader, vec3_t origin, int size, int duration, float alpha ) {
cparticle_t *p;
if ( !pshader ) {
CG_Printf( "CG_ParticleImpactSmokePuff pshader == ZERO!\n" );
}
if ( !free_particles ) {
return;
}
p = free_particles;
free_particles = p->next;
p->next = active_particles;
active_particles = p;
p->time = cg.time;
p->alpha = 1.0;
p->alphavel = 0;
p->roll = rand() % 179;
p->pshader = pshader;
if ( duration > 0 ) {
p->endtime = cg.time + duration;
} else {
p->endtime = duration;
}
p->startfade = cg.time;
p->width = size;
p->height = size;
p->endheight = size;
p->endwidth = size;
p->type = P_SPRITE;
VectorCopy( origin, p->org );
p->rotate = qfalse;
}
| GenaSG/ET | src/cgame/cg_particles.c | C | gpl-3.0 | 50,490 |
;*****************************************************************************
;* checkasm-a.asm: assembly check tool
;*****************************************************************************
;* Copyright (C) 2008-2017 x264 project
;*
;* Authors: Loren Merritt <[email protected]>
;* Henrik Gramner <[email protected]>
;*
;* This program is free software; you can redistribute it and/or modify
;* it under the terms of the GNU General Public License as published by
;* the Free Software Foundation; either version 2 of the License, or
;* (at your option) any later version.
;*
;* This program is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;* GNU General Public License for more details.
;*
;* You should have received a copy of the GNU General Public License
;* along with this program; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
;*
;* This program is also available under a commercial proprietary license.
;* For more information, contact us at [email protected].
;*****************************************************************************
%include "x86inc.asm"
SECTION_RODATA
error_message: db "failed to preserve register", 0
%if ARCH_X86_64
; just random numbers to reduce the chance of incidental match
ALIGN 16
x6: dq 0x1a1b2550a612b48c,0x79445c159ce79064
x7: dq 0x2eed899d5a28ddcd,0x86b2536fcd8cf636
x8: dq 0xb0856806085e7943,0x3f2bf84fc0fcca4e
x9: dq 0xacbd382dcf5b8de2,0xd229e1f5b281303f
x10: dq 0x71aeaff20b095fd9,0xab63e2e11fa38ed9
x11: dq 0x89b0c0765892729a,0x77d410d5c42c882d
x12: dq 0xc45ea11a955d8dd5,0x24b3c1d2a024048b
x13: dq 0x2e8ec680de14b47c,0xdd7b8919edd42786
x14: dq 0x135ce6888fa02cbf,0x11e53e2b2ac655ef
x15: dq 0x011ff554472a7a10,0x6de8f4c914c334d5
n7: dq 0x21f86d66c8ca00ce
n8: dq 0x75b6ba21077c48ad
n9: dq 0xed56bb2dcb3c7736
n10: dq 0x8bda43d3fd1a7e06
n11: dq 0xb64a9c9e5d318408
n12: dq 0xdf9a54b303f1d3a3
n13: dq 0x4a75479abd64e097
n14: dq 0x249214109d5d1c88
%endif
SECTION .text
cextern_naked puts
; max number of args used by any x264 asm function.
; (max_args % 4) must equal 3 for stack alignment
%define max_args 15
%if ARCH_X86_64
;-----------------------------------------------------------------------------
; void x264_checkasm_stack_clobber( uint64_t clobber, ... )
;-----------------------------------------------------------------------------
cglobal checkasm_stack_clobber, 1,2
; Clobber the stack with junk below the stack pointer
%define argsize (max_args+6)*8
SUB rsp, argsize
mov r1, argsize-8
.loop:
mov [rsp+r1], r0
sub r1, 8
jge .loop
ADD rsp, argsize
RET
%if WIN64
%assign free_regs 7
%else
%assign free_regs 9
%endif
;-----------------------------------------------------------------------------
; intptr_t x264_checkasm_call( intptr_t (*func)(), int *ok, ... )
;-----------------------------------------------------------------------------
INIT_XMM
cglobal checkasm_call, 2,15,16,max_args*8+8
mov r6, r0
mov [rsp+max_args*8], r1
; All arguments have been pushed on the stack instead of registers in order to
; test for incorrect assumptions that 32-bit ints are zero-extended to 64-bit.
mov r0, r6mp
mov r1, r7mp
mov r2, r8mp
mov r3, r9mp
%if UNIX64
mov r4, r10mp
mov r5, r11mp
%assign i 6
%rep max_args-6
mov r9, [rsp+stack_offset+(i+1)*8]
mov [rsp+(i-6)*8], r9
%assign i i+1
%endrep
%else
%assign i 4
%rep max_args-4
mov r9, [rsp+stack_offset+(i+7)*8]
mov [rsp+i*8], r9
%assign i i+1
%endrep
%endif
%if WIN64
%assign i 6
%rep 16-6
mova m %+ i, [x %+ i]
%assign i i+1
%endrep
%endif
%assign i 14
%rep 15-free_regs
mov r %+ i, [n %+ i]
%assign i i-1
%endrep
call r6
%assign i 14
%rep 15-free_regs
xor r %+ i, [n %+ i]
or r14, r %+ i
%assign i i-1
%endrep
%if WIN64
%assign i 6
%rep 16-6
pxor m %+ i, [x %+ i]
por m6, m %+ i
%assign i i+1
%endrep
packsswb m6, m6
movq r5, m6
or r14, r5
%endif
jz .ok
mov r9, rax
mov r10, rdx
lea r0, [error_message]
%if FORMAT_ELF
call puts wrt ..plt
%else
call puts
%endif
mov r1, [rsp+max_args*8]
mov dword [r1], 0
mov rdx, r10
mov rax, r9
.ok:
RET
%else
; just random numbers to reduce the chance of incidental match
%define n3 dword 0x6549315c
%define n4 dword 0xe02f3e23
%define n5 dword 0xb78d0d1d
%define n6 dword 0x33627ba7
;-----------------------------------------------------------------------------
; intptr_t x264_checkasm_call( intptr_t (*func)(), int *ok, ... )
;-----------------------------------------------------------------------------
cglobal checkasm_call, 1,7
mov r3, n3
mov r4, n4
mov r5, n5
mov r6, n6
%rep max_args
push dword [esp+24+max_args*4]
%endrep
call r0
add esp, max_args*4
xor r3, n3
xor r4, n4
xor r5, n5
xor r6, n6
or r3, r4
or r5, r6
or r3, r5
jz .ok
mov r3, eax
mov r4, edx
lea r1, [error_message]
push r1
call puts
add esp, 4
mov r1, r1m
mov dword [r1], 0
mov edx, r4
mov eax, r3
.ok:
REP_RET
%endif ; ARCH_X86_64
;-----------------------------------------------------------------------------
; int x264_stack_pagealign( int (*func)(), int align )
;-----------------------------------------------------------------------------
cglobal stack_pagealign, 2,2
movsxdifnidn r1, r1d
push rbp
mov rbp, rsp
%if WIN64
sub rsp, 32 ; shadow space
%endif
and rsp, ~0xfff
sub rsp, r1
call r0
leave
RET
; Trigger a warmup of vector units
%macro WARMUP 0
cglobal checkasm_warmup, 0,0
xorps m0, m0
RET
%endmacro
INIT_YMM avx
WARMUP
INIT_ZMM avx512
WARMUP
| hzhjellyfish/mUsbCam | x264/tools/checkasm-a.asm | Assembly | gpl-3.0 | 6,026 |
-----------------------------------
-- Area: Temple of Uggalepih
-- MOB: Rompaulion S Ciralle
-- Involved with San d'Oria quest "Knight Stalker"
-----------------------------------
function onMobSpawn(mob)
end;
function onMobDeath(mob, player, isKiller)
-- Get credit if other NM is dead/despawned or in the process of dieing/fading out
local Cleuvarion = GetMobByID(mob:getID() - 1);
if (player:getVar("KnightStalker_Progress") == 4 and Cleuvarion:isDead()) then
player:setVar("KnightStalker_Kill",1);
end
end;
| Whitechaser/darkstar | scripts/zones/Temple_of_Uggalepih/mobs/Rompaulion_S_Citalle.lua | Lua | gpl-3.0 | 539 |
<?php
/**
* Polyfiller for missing PHP json extension.
* Simply avoids fatal errors. Doesn't attempt to really replace the functionality
*/
function loco_compat_json_encode( $value ){
return '{"error":{"code":-1,"message":"json extension is not installed"}}';
}
if( ! extension_loaded('json_encode') && WP_DEBUG && ( ! defined('DOING_AJAX') || ! DOING_AJAX ) ){
LocoAdmin::warning( sprintf( __('PHP extension "%s" is not installed. If you experience problems you should install it','loco-translate'), 'json_encode' ) );
}
if( ! function_exists('json_encode') ){
function json_encode( $value = '' ){
return loco_compat_json_encode( $value );
}
}
| cedewey/sol | wp-content/plugins/loco-translate/old/lib/compat/loco-json.php | PHP | gpl-3.0 | 677 |
#include <hwloc.h>
#include <stdio.h>
/* The body of the test is in a separate .c file and a separate
library, just to ensure that hwloc didn't force compilation with
visibility flags enabled. */
int do_test(void)
{
mytest_hwloc_topology_t topology;
unsigned depth;
hwloc_bitmap_t cpu_set;
/* Just call a bunch of functions to see if we can link and run */
printf("*** Test 1: bitmap alloc\n");
cpu_set = mytest_hwloc_bitmap_alloc();
if (NULL == cpu_set) return 1;
printf("*** Test 2: topology init\n");
if (0 != mytest_hwloc_topology_init(&topology)) return 1;
printf("*** Test 3: topology load\n");
if (0 != mytest_hwloc_topology_load(topology)) return 1;
printf("*** Test 4: topology get depth\n");
depth = mytest_hwloc_topology_get_depth(topology);
if (depth > 10000) return 1;
printf(" Max depth: %u\n", depth);
printf("*** Test 5: topology destroy\n");
mytest_hwloc_topology_destroy(topology);
printf("*** Test 6: bitmap free\n");
mytest_hwloc_bitmap_free(cpu_set);
return 0;
}
| jbreitbart/hwloc-test | vendor/hwloc-1.11.0/tests/embedded/do_test.c | C | gpl-3.0 | 1,078 |
/*
* Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
// ToolManage.h: interface for the CUniToolManage class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_UNITOOLMANAGE_H__058665D6_5812_4FE1_8EE2_647FC440052E__INCLUDED_)
#define AFX_UNITOOLMANAGE_H__058665D6_5812_4FE1_8EE2_647FC440052E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//#include "unitray_comm.h"
class CUniToolManage
{
public:
CUniToolManage ();
virtual ~ CUniToolManage ();
char *cubridmanager_path;
bool bStartVSQL ();
bool bStartEasyManage ();
bool bCheckInstallVSQL ();
bool bCheckInstallEasyManage ();
};
#endif // !defined(AFX_UNITOOLMANAGE_H__058665D6_5812_4FE1_8EE2_647FC440052E__INCLUDED_)
| andrei14vl/cubrid | src/win_tools/cubridtray/ToolManage.h | C | gpl-3.0 | 1,499 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>avr-libc: <compat/ina90.h>: Compatibility with IAR EWB 3.x</title>
<link href="dox.css" rel="stylesheet" type="text/css">
</head>
<body>
<center>
<table width="80%">
<tr>
<td align="left"><a href="http://www.nongnu.org/avr-libc/">AVR Libc Home Page</a></td>
<td align="center" colspan=4><img src="avrs.png" alt="AVRs" align="middle" border="0"></td>
<td align="right"><a href="https://savannah.nongnu.org/projects/avr-libc/">AVR Libc Development Pages</a></td>
</tr>
<tr>
<td align="center" width="13%"><a href="index.html">Main Page</a></td>
<td align="center" width="13%"><a href="pages.html">User Manual</a></td>
<td align="center" width="13%"><a href="modules.html">Library Reference</a></td>
<td align="center" width="13%"><a href="FAQ.html">FAQ</a></td>
<td align="center" width="13%"><a href="globals.html">Alphabetical Index</a></td>
<td align="center" width="13%"><a href="group__demos.html">Example Projects</a></td>
</tr>
</table>
</center>
<hr width="80%">
<!-- Generated by Doxygen 1.5.7 -->
<div class="contents">
<h1><compat/ina90.h>: Compatibility with IAR EWB 3.x</h1><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
</table>
<div class="fragment"><pre class="fragment"><span class="preprocessor"> #include <compat/ina90.h></span>
</pre></div><p>
This is an attempt to provide some compatibility with header files that come with IAR C, to make porting applications between different compilers easier. No 100% compatibility though.<p>
<dl class="note" compact><dt><b>Note:</b></dt><dd>For actual documentation, please see the IAR manual. </dd></dl>
</div>
<hr width="80%">
<p><center>Automatically generated by Doxygen 1.5.7 on 6 Nov 2008.</center></p>
</body>
</html>
| 8cH9azbsFifZ/ble-morse | lib/arduino_ide/Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/doc/avr-libc/group__compat__ina90.html | HTML | gpl-3.0 | 1,943 |
/**
* Aptana Studio
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.js.debug.ui.internal.actions;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.model.IDebugElement;
import org.eclipse.debug.core.model.IWatchExpressionDelegate;
import org.eclipse.debug.core.model.IWatchExpressionListener;
import org.eclipse.debug.core.model.IWatchExpressionResult;
import org.eclipse.debug.ui.DebugUITools;
import com.aptana.debug.ui.DebugUiPlugin;
import com.aptana.js.debug.core.model.JSDebugModel;
/**
* @author Max Stepanov
*/
public class InspectAction extends WatchAction implements IWatchExpressionListener {
/**
* @see com.aptana.js.debug.ui.internal.actions.WatchAction#createExpression(java.lang.String)
*/
protected void createExpression(String expressionText) {
IAdaptable object = DebugUITools.getDebugContext();
IDebugElement context = null;
if (object instanceof IDebugElement) {
context = (IDebugElement) object;
} else if (object instanceof ILaunch) {
context = ((ILaunch) object).getDebugTarget();
}
if (context != null) {
IWatchExpressionDelegate delegate = DebugPlugin.getDefault().getExpressionManager()
.newWatchExpressionDelegate(context.getModelIdentifier());
delegate.evaluateExpression(expressionText, context, this);
}
}
/**
* @see org.eclipse.debug.core.model.IWatchExpressionListener#watchEvaluationFinished(org.eclipse.debug.core.model.IWatchExpressionResult)
*/
public void watchEvaluationFinished(final IWatchExpressionResult result) {
if (DebugUiPlugin.getDefault() == null) {
return;
}
if (result.getValue() != null || result.hasErrors()) {
DebugUiPlugin.getStandardDisplay().syncExec(new Runnable() {
public void run() {
displayResult(result);
}
});
}
}
/**
* displayResult
*
* @param result
*/
protected void displayResult(IWatchExpressionResult result) {
DebugPlugin.getDefault().getExpressionManager().addExpression(JSDebugModel.createInspectExpression(result));
showExpressionsView();
}
}
| HossainKhademian/Studio3 | plugins/com.aptana.js.debug.ui/src/com/aptana/js/debug/ui/internal/actions/InspectAction.java | Java | gpl-3.0 | 2,395 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_16) on Thu Jul 22 17:19:23 CEST 2010 -->
<TITLE>
Uses of Interface models.maillage.Maillage
</TITLE>
<META NAME="date" CONTENT="2010-07-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface models.maillage.Maillage";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?models/maillage/\class-useMaillage.html" target="_top"><B>FRAMES</B></A>
<A HREF="Maillage.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>models.maillage.Maillage</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage">Maillage</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#models.maillage"><B>models.maillage</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="models.maillage"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage">Maillage</A> in <A HREF="../../../models/maillage/package-summary.html">models.maillage</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../models/maillage/package-summary.html">models.maillage</A> that implement <A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage">Maillage</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../models/maillage/Maillage_v1.html" title="class in models.maillage">Maillage_v1</A></B></CODE>
<BR>
Fichier : Maillage.java
Encodage : UTF-8
Cette classe permet de représenter différentes opérations sur le maillage
(graphe), utilisé dans notre jeu.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../models/maillage/Maillage_v2.html" title="class in models.maillage">Maillage_v2</A></B></CODE>
<BR>
Maillage dans sa version 2.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../models/maillage/package-summary.html">models.maillage</A> with parameters of type <A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage">Maillage</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../models/maillage/Fenetre_RepresentationMaillage.html#Fenetre_RepresentationMaillage(models.maillage.Maillage)">Fenetre_RepresentationMaillage</A></B>(<A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage">Maillage</A> maillage)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../models/maillage/Maillage.html" title="interface in models.maillage"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?models/maillage/\class-useMaillage.html" target="_top"><B>FRAMES</B></A>
<A HREF="Maillage.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| PiRSquared17/asd-tower-defense | javadoc/models/maillage/class-use/Maillage.html | HTML | gpl-3.0 | 8,861 |
#
# The patch applied in http://bugs.python.org/issue1207589
# changes the structure of rmenu_specs in EditorWindow.py. This breaks a lot of extensions.
# This file is a re-factoring of rmenu code for other extensions to use.
#
| technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/site-packages/idlexlib/extensions/_rmenu.py | Python | gpl-3.0 | 231 |
/**
* Copyright (c) 2011-2013 Fabien Cazenave, Mozilla.
*
* 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.
*/
/*jshint browser: true, devel: true, es5: true, globalstrict: true */
'use strict';
document.webL10n = (function(window, document, undefined) {
var gL10nData = {};
var gTextData = '';
var gTextProp = 'textContent';
var gLanguage = '';
var gMacros = {};
var gReadyState = 'loading';
/**
* Synchronously loading l10n resources significantly minimizes flickering
* from displaying the app with non-localized strings and then updating the
* strings. Although this will block all script execution on this page, we
* expect that the l10n resources are available locally on flash-storage.
*
* As synchronous XHR is generally considered as a bad idea, we're still
* loading l10n resources asynchronously -- but we keep this in a setting,
* just in case... and applications using this library should hide their
* content until the `localized' event happens.
*/
var gAsyncResourceLoading = true; // read-only
/**
* Debug helpers
*
* gDEBUG == 0: don't display any console message
* gDEBUG == 1: display only warnings, not logs
* gDEBUG == 2: display all console messages
*/
var gDEBUG = 1;
function consoleLog(message) {
if (gDEBUG >= 2) {
console.log('[l10n] ' + message);
}
}
function consoleWarn(message) {
if (gDEBUG) {
console.warn('[l10n] ' + message);
}
}
/**
* DOM helpers for the so-called "HTML API".
*
* These functions are written for modern browsers. For old versions of IE,
* they're overridden in the 'startup' section at the end of this file.
*/
function getL10nResourceLinks() {
return document.querySelectorAll('link[type="application/l10n"]');
}
function getL10nDictionary() {
var script = document.querySelector('script[type="application/l10n"]');
// TODO: support multiple and external JSON dictionaries
return script ? JSON.parse(script.innerHTML) : null;
}
function getTranslatableChildren(element) {
return element ? element.querySelectorAll('*[data-l10n-id]') : [];
}
function getL10nAttributes(element) {
if (!element)
return {};
var l10nId = element.getAttribute('data-l10n-id');
var l10nArgs = element.getAttribute('data-l10n-args');
var args = {};
if (l10nArgs) {
try {
args = JSON.parse(l10nArgs);
} catch (e) {
consoleWarn('could not parse arguments for #' + l10nId);
}
}
return { id: l10nId, args: args };
}
function fireL10nReadyEvent(lang) {
var evtObject = document.createEvent('Event');
evtObject.initEvent('localized', true, false);
evtObject.language = lang;
document.dispatchEvent(evtObject);
}
function xhrLoadText(url, onSuccess, onFailure) {
onSuccess = onSuccess || function _onSuccess(data) {};
onFailure = onFailure || function _onFailure() {
consoleWarn(url + ' not found.');
};
var xhr = new XMLHttpRequest();
xhr.open('GET', url, gAsyncResourceLoading);
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=utf-8');
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status === 0) {
onSuccess(xhr.responseText);
} else {
onFailure();
}
}
};
xhr.onerror = onFailure;
xhr.ontimeout = onFailure;
// in Firefox OS with the app:// protocol, trying to XHR a non-existing
// URL will raise an exception here -- hence this ugly try...catch.
try {
xhr.send(null);
} catch (e) {
onFailure();
}
}
/**
* l10n resource parser:
* - reads (async XHR) the l10n resource matching `lang';
* - imports linked resources (synchronously) when specified;
* - parses the text data (fills `gL10nData' and `gTextData');
* - triggers success/failure callbacks when done.
*
* @param {string} href
* URL of the l10n resource to parse.
*
* @param {string} lang
* locale (language) to parse. Must be a lowercase string.
*
* @param {Function} successCallback
* triggered when the l10n resource has been successully parsed.
*
* @param {Function} failureCallback
* triggered when the an error has occured.
*
* @return {void}
* uses the following global variables: gL10nData, gTextData, gTextProp.
*/
function parseResource(href, lang, successCallback, failureCallback) {
var baseURL = href.replace(/[^\/]*$/, '') || './';
// handle escaped characters (backslashes) in a string
function evalString(text) {
if (text.lastIndexOf('\\') < 0)
return text;
return text.replace(/\\\\/g, '\\')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\b/g, '\b')
.replace(/\\f/g, '\f')
.replace(/\\{/g, '{')
.replace(/\\}/g, '}')
.replace(/\\"/g, '"')
.replace(/\\'/g, "'");
}
// parse *.properties text data into an l10n dictionary
// If gAsyncResourceLoading is false, then the callback will be called
// synchronously. Otherwise it is called asynchronously.
function parseProperties(text, parsedPropertiesCallback) {
var dictionary = {};
// token expressions
var reBlank = /^\s*|\s*$/;
var reComment = /^\s*#|^\s*$/;
var reSection = /^\s*\[(.*)\]\s*$/;
var reImport = /^\s*@import\s+url\((.*)\)\s*$/i;
var reSplit = /^([^=\s]*)\s*=\s*(.+)$/; // TODO: escape EOLs with '\'
// parse the *.properties file into an associative array
function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
var currentLang = '*';
var genericLang = lang.split('-', 1)[0];
var skipLang = false;
var match = '';
function nextEntry() {
// Use infinite loop instead of recursion to avoid reaching the
// maximum recursion limit for content with many lines.
while (true) {
if (!entries.length) {
parsedRawLinesCallback();
return;
}
var line = entries.shift();
// comment or blank line?
if (reComment.test(line))
continue;
// the extended syntax supports [lang] sections and @import rules
if (extendedSyntax) {
match = reSection.exec(line);
if (match) { // section start?
// RFC 4646, section 4.4, "All comparisons MUST be performed
// in a case-insensitive manner."
currentLang = match[1].toLowerCase();
skipLang = (currentLang !== '*') &&
(currentLang !== lang) && (currentLang !== genericLang);
continue;
} else if (skipLang) {
continue;
}
match = reImport.exec(line);
if (match) { // @import rule?
loadImport(baseURL + match[1], nextEntry);
return;
}
}
// key-value pair
var tmp = line.match(reSplit);
if (tmp && tmp.length == 3) {
dictionary[tmp[1]] = evalString(tmp[2]);
}
}
}
nextEntry();
}
// import another *.properties file
function loadImport(url, callback) {
xhrLoadText(url, function(content) {
parseRawLines(content, false, callback); // don't allow recursive imports
}, null);
}
// fill the dictionary
parseRawLines(text, true, function() {
parsedPropertiesCallback(dictionary);
});
}
// load and parse l10n data (warning: global variables are used here)
xhrLoadText(href, function(response) {
gTextData += response; // mostly for debug
// parse *.properties text data into an l10n dictionary
parseProperties(response, function(data) {
// find attribute descriptions, if any
for (var key in data) {
var id, prop, index = key.lastIndexOf('.');
if (index > 0) { // an attribute has been specified
id = key.substring(0, index);
prop = key.substr(index + 1);
} else { // no attribute: assuming text content by default
id = key;
prop = gTextProp;
}
if (!gL10nData[id]) {
gL10nData[id] = {};
}
gL10nData[id][prop] = data[key];
}
// trigger callback
if (successCallback) {
successCallback();
}
});
}, failureCallback);
}
// load and parse all resources for the specified locale
function loadLocale(lang, callback) {
// RFC 4646, section 2.1 states that language tags have to be treated as
// case-insensitive. Convert to lowercase for case-insensitive comparisons.
if (lang) {
lang = lang.toLowerCase();
}
callback = callback || function _callback() {};
clear();
gLanguage = lang;
// check all <link type="application/l10n" href="..." /> nodes
// and load the resource files
var langLinks = getL10nResourceLinks();
var langCount = langLinks.length;
if (langCount === 0) {
// we might have a pre-compiled dictionary instead
var dict = getL10nDictionary();
if (dict && dict.locales && dict.default_locale) {
consoleLog('using the embedded JSON directory, early way out');
gL10nData = dict.locales[lang];
if (!gL10nData) {
var defaultLocale = dict.default_locale.toLowerCase();
for (var anyCaseLang in dict.locales) {
anyCaseLang = anyCaseLang.toLowerCase();
if (anyCaseLang === lang) {
gL10nData = dict.locales[lang];
break;
} else if (anyCaseLang === defaultLocale) {
gL10nData = dict.locales[defaultLocale];
}
}
}
callback();
} else {
consoleLog('no resource to load, early way out');
}
// early way out
fireL10nReadyEvent(lang);
gReadyState = 'complete';
return;
}
// start the callback when all resources are loaded
var onResourceLoaded = null;
var gResourceCount = 0;
onResourceLoaded = function() {
gResourceCount++;
if (gResourceCount >= langCount) {
callback();
fireL10nReadyEvent(lang);
gReadyState = 'complete';
}
};
// load all resource files
function L10nResourceLink(link) {
var href = link.href;
// Note: If |gAsyncResourceLoading| is false, then the following callbacks
// are synchronously called.
this.load = function(lang, callback) {
parseResource(href, lang, callback, function() {
consoleWarn(href + ' not found.');
// lang not found, used default resource instead
consoleWarn('"' + lang + '" resource not found');
gLanguage = '';
// Resource not loaded, but we still need to call the callback.
callback();
});
};
}
for (var i = 0; i < langCount; i++) {
var resource = new L10nResourceLink(langLinks[i]);
resource.load(lang, onResourceLoaded);
}
}
// clear all l10n data
function clear() {
gL10nData = {};
gTextData = '';
gLanguage = '';
// TODO: clear all non predefined macros.
// There's no such macro /yet/ but we're planning to have some...
}
/**
* Get rules for plural forms (shared with JetPack), see:
* http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* https://github.com/mozilla/addon-sdk/blob/master/python-lib/plural-rules-generator.p
*
* @param {string} lang
* locale (language) used.
*
* @return {Function}
* returns a function that gives the plural form name for a given integer:
* var fun = getPluralRules('en');
* fun(1) -> 'one'
* fun(0) -> 'other'
* fun(1000) -> 'other'.
*/
function getPluralRules(lang) {
var locales2rules = {
'af': 3,
'ak': 4,
'am': 4,
'ar': 1,
'asa': 3,
'az': 0,
'be': 11,
'bem': 3,
'bez': 3,
'bg': 3,
'bh': 4,
'bm': 0,
'bn': 3,
'bo': 0,
'br': 20,
'brx': 3,
'bs': 11,
'ca': 3,
'cgg': 3,
'chr': 3,
'cs': 12,
'cy': 17,
'da': 3,
'de': 3,
'dv': 3,
'dz': 0,
'ee': 3,
'el': 3,
'en': 3,
'eo': 3,
'es': 3,
'et': 3,
'eu': 3,
'fa': 0,
'ff': 5,
'fi': 3,
'fil': 4,
'fo': 3,
'fr': 5,
'fur': 3,
'fy': 3,
'ga': 8,
'gd': 24,
'gl': 3,
'gsw': 3,
'gu': 3,
'guw': 4,
'gv': 23,
'ha': 3,
'haw': 3,
'he': 2,
'hi': 4,
'hr': 11,
'hu': 0,
'id': 0,
'ig': 0,
'ii': 0,
'is': 3,
'it': 3,
'iu': 7,
'ja': 0,
'jmc': 3,
'jv': 0,
'ka': 0,
'kab': 5,
'kaj': 3,
'kcg': 3,
'kde': 0,
'kea': 0,
'kk': 3,
'kl': 3,
'km': 0,
'kn': 0,
'ko': 0,
'ksb': 3,
'ksh': 21,
'ku': 3,
'kw': 7,
'lag': 18,
'lb': 3,
'lg': 3,
'ln': 4,
'lo': 0,
'lt': 10,
'lv': 6,
'mas': 3,
'mg': 4,
'mk': 16,
'ml': 3,
'mn': 3,
'mo': 9,
'mr': 3,
'ms': 0,
'mt': 15,
'my': 0,
'nah': 3,
'naq': 7,
'nb': 3,
'nd': 3,
'ne': 3,
'nl': 3,
'nn': 3,
'no': 3,
'nr': 3,
'nso': 4,
'ny': 3,
'nyn': 3,
'om': 3,
'or': 3,
'pa': 3,
'pap': 3,
'pl': 13,
'ps': 3,
'pt': 3,
'rm': 3,
'ro': 9,
'rof': 3,
'ru': 11,
'rwk': 3,
'sah': 0,
'saq': 3,
'se': 7,
'seh': 3,
'ses': 0,
'sg': 0,
'sh': 11,
'shi': 19,
'sk': 12,
'sl': 14,
'sma': 7,
'smi': 7,
'smj': 7,
'smn': 7,
'sms': 7,
'sn': 3,
'so': 3,
'sq': 3,
'sr': 11,
'ss': 3,
'ssy': 3,
'st': 3,
'sv': 3,
'sw': 3,
'syr': 3,
'ta': 3,
'te': 3,
'teo': 3,
'th': 0,
'ti': 4,
'tig': 3,
'tk': 3,
'tl': 4,
'tn': 3,
'to': 0,
'tr': 0,
'ts': 3,
'tzm': 22,
'uk': 11,
'ur': 3,
've': 3,
'vi': 0,
'vun': 3,
'wa': 4,
'wae': 3,
'wo': 0,
'xh': 3,
'xog': 3,
'yo': 0,
'zh': 0,
'zu': 3
};
// utility functions for plural rules methods
function isIn(n, list) {
return list.indexOf(n) !== -1;
}
function isBetween(n, start, end) {
return start <= n && n <= end;
}
// list of all plural rules methods:
// map an integer to the plural form name to use
var pluralRules = {
'0': function(n) {
return 'other';
},
'1': function(n) {
if ((isBetween((n % 100), 3, 10)))
return 'few';
if (n === 0)
return 'zero';
if ((isBetween((n % 100), 11, 99)))
return 'many';
if (n == 2)
return 'two';
if (n == 1)
return 'one';
return 'other';
},
'2': function(n) {
if (n !== 0 && (n % 10) === 0)
return 'many';
if (n == 2)
return 'two';
if (n == 1)
return 'one';
return 'other';
},
'3': function(n) {
if (n == 1)
return 'one';
return 'other';
},
'4': function(n) {
if ((isBetween(n, 0, 1)))
return 'one';
return 'other';
},
'5': function(n) {
if ((isBetween(n, 0, 2)) && n != 2)
return 'one';
return 'other';
},
'6': function(n) {
if (n === 0)
return 'zero';
if ((n % 10) == 1 && (n % 100) != 11)
return 'one';
return 'other';
},
'7': function(n) {
if (n == 2)
return 'two';
if (n == 1)
return 'one';
return 'other';
},
'8': function(n) {
if ((isBetween(n, 3, 6)))
return 'few';
if ((isBetween(n, 7, 10)))
return 'many';
if (n == 2)
return 'two';
if (n == 1)
return 'one';
return 'other';
},
'9': function(n) {
if (n === 0 || n != 1 && (isBetween((n % 100), 1, 19)))
return 'few';
if (n == 1)
return 'one';
return 'other';
},
'10': function(n) {
if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19)))
return 'few';
if ((n % 10) == 1 && !(isBetween((n % 100), 11, 19)))
return 'one';
return 'other';
},
'11': function(n) {
if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14)))
return 'few';
if ((n % 10) === 0 ||
(isBetween((n % 10), 5, 9)) ||
(isBetween((n % 100), 11, 14)))
return 'many';
if ((n % 10) == 1 && (n % 100) != 11)
return 'one';
return 'other';
},
'12': function(n) {
if ((isBetween(n, 2, 4)))
return 'few';
if (n == 1)
return 'one';
return 'other';
},
'13': function(n) {
if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14)))
return 'few';
if (n != 1 && (isBetween((n % 10), 0, 1)) ||
(isBetween((n % 10), 5, 9)) ||
(isBetween((n % 100), 12, 14)))
return 'many';
if (n == 1)
return 'one';
return 'other';
},
'14': function(n) {
if ((isBetween((n % 100), 3, 4)))
return 'few';
if ((n % 100) == 2)
return 'two';
if ((n % 100) == 1)
return 'one';
return 'other';
},
'15': function(n) {
if (n === 0 || (isBetween((n % 100), 2, 10)))
return 'few';
if ((isBetween((n % 100), 11, 19)))
return 'many';
if (n == 1)
return 'one';
return 'other';
},
'16': function(n) {
if ((n % 10) == 1 && n != 11)
return 'one';
return 'other';
},
'17': function(n) {
if (n == 3)
return 'few';
if (n === 0)
return 'zero';
if (n == 6)
return 'many';
if (n == 2)
return 'two';
if (n == 1)
return 'one';
return 'other';
},
'18': function(n) {
if (n === 0)
return 'zero';
if ((isBetween(n, 0, 2)) && n !== 0 && n != 2)
return 'one';
return 'other';
},
'19': function(n) {
if ((isBetween(n, 2, 10)))
return 'few';
if ((isBetween(n, 0, 1)))
return 'one';
return 'other';
},
'20': function(n) {
if ((isBetween((n % 10), 3, 4) || ((n % 10) == 9)) && !(
isBetween((n % 100), 10, 19) ||
isBetween((n % 100), 70, 79) ||
isBetween((n % 100), 90, 99)
))
return 'few';
if ((n % 1000000) === 0 && n !== 0)
return 'many';
if ((n % 10) == 2 && !isIn((n % 100), [12, 72, 92]))
return 'two';
if ((n % 10) == 1 && !isIn((n % 100), [11, 71, 91]))
return 'one';
return 'other';
},
'21': function(n) {
if (n === 0)
return 'zero';
if (n == 1)
return 'one';
return 'other';
},
'22': function(n) {
if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99)))
return 'one';
return 'other';
},
'23': function(n) {
if ((isBetween((n % 10), 1, 2)) || (n % 20) === 0)
return 'one';
return 'other';
},
'24': function(n) {
if ((isBetween(n, 3, 10) || isBetween(n, 13, 19)))
return 'few';
if (isIn(n, [2, 12]))
return 'two';
if (isIn(n, [1, 11]))
return 'one';
return 'other';
}
};
// return a function that gives the plural form name for a given integer
var index = locales2rules[lang.replace(/-.*$/, '')];
if (!(index in pluralRules)) {
consoleWarn('plural form unknown for [' + lang + ']');
return function() { return 'other'; };
}
return pluralRules[index];
}
// pre-defined 'plural' macro
gMacros.plural = function(str, param, key, prop) {
var n = parseFloat(param);
if (isNaN(n))
return str;
// TODO: support other properties (l20n still doesn't...)
if (prop != gTextProp)
return str;
// initialize _pluralRules
if (!gMacros._pluralRules) {
gMacros._pluralRules = getPluralRules(gLanguage);
}
var index = '[' + gMacros._pluralRules(n) + ']';
// try to find a [zero|one|two] key if it's defined
if (n === 0 && (key + '[zero]') in gL10nData) {
str = gL10nData[key + '[zero]'][prop];
} else if (n == 1 && (key + '[one]') in gL10nData) {
str = gL10nData[key + '[one]'][prop];
} else if (n == 2 && (key + '[two]') in gL10nData) {
str = gL10nData[key + '[two]'][prop];
} else if ((key + index) in gL10nData) {
str = gL10nData[key + index][prop];
} else if ((key + '[other]') in gL10nData) {
str = gL10nData[key + '[other]'][prop];
}
return str;
};
/**
* l10n dictionary functions
*/
// fetch an l10n object, warn if not found, apply `args' if possible
function getL10nData(key, args, fallback) {
var data = gL10nData[key];
if (!data) {
consoleWarn('#' + key + ' is undefined.');
if (!fallback) {
return null;
}
data = fallback;
}
/** This is where l10n expressions should be processed.
* The plan is to support C-style expressions from the l20n project;
* until then, only two kinds of simple expressions are supported:
* {[ index ]} and {{ arguments }}.
*/
var rv = {};
for (var prop in data) {
var str = data[prop];
str = substIndexes(str, args, key, prop);
str = substArguments(str, args, key);
rv[prop] = str;
}
return rv;
}
// replace {[macros]} with their values
function substIndexes(str, args, key, prop) {
var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/;
var reMatch = reIndex.exec(str);
if (!reMatch || !reMatch.length)
return str;
// an index/macro has been found
// Note: at the moment, only one parameter is supported
var macroName = reMatch[1];
var paramName = reMatch[2];
var param;
if (args && paramName in args) {
param = args[paramName];
} else if (paramName in gL10nData) {
param = gL10nData[paramName];
}
// there's no macro parser yet: it has to be defined in gMacros
if (macroName in gMacros) {
var macro = gMacros[macroName];
str = macro(str, param, key, prop);
}
return str;
}
// replace {{arguments}} with their values
function substArguments(str, args, key) {
var reArgs = /\{\{\s*(.+?)\s*\}\}/g;
return str.replace(reArgs, function(matched_text, arg) {
if (args && arg in args) {
return args[arg];
}
if (arg in gL10nData) {
return gL10nData[arg];
}
consoleLog('argument {{' + arg + '}} for #' + key + ' is undefined.');
return matched_text;
});
}
// translate an HTML element
function translateElement(element) {
var l10n = getL10nAttributes(element);
if (!l10n.id)
return;
// get the related l10n object
var data = getL10nData(l10n.id, l10n.args);
if (!data) {
consoleWarn('#' + l10n.id + ' is undefined.');
return;
}
// translate element (TODO: security checks?)
if (data[gTextProp]) { // XXX
if (getChildElementCount(element) === 0) {
element[gTextProp] = data[gTextProp];
} else {
// this element has element children: replace the content of the first
// (non-empty) child textNode and clear other child textNodes
var children = element.childNodes;
var found = false;
for (var i = 0, l = children.length; i < l; i++) {
if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {
if (found) {
children[i].nodeValue = '';
} else {
children[i].nodeValue = data[gTextProp];
found = true;
}
}
}
// if no (non-empty) textNode is found, insert a textNode before the
// first element child.
if (!found) {
var textNode = document.createTextNode(data[gTextProp]);
element.insertBefore(textNode, element.firstChild);
}
}
delete data[gTextProp];
}
for (var k in data) {
element[k] = data[k];
}
}
// webkit browsers don't currently support 'children' on SVG elements...
function getChildElementCount(element) {
if (element.children) {
return element.children.length;
}
if (typeof element.childElementCount !== 'undefined') {
return element.childElementCount;
}
var count = 0;
for (var i = 0; i < element.childNodes.length; i++) {
count += element.nodeType === 1 ? 1 : 0;
}
return count;
}
// translate an HTML subtree
function translateFragment(element) {
element = element || document.documentElement;
// check all translatable children (= w/ a `data-l10n-id' attribute)
var children = getTranslatableChildren(element);
var elementCount = children.length;
for (var i = 0; i < elementCount; i++) {
translateElement(children[i]);
}
// translate element itself if necessary
translateElement(element);
}
/**
* Startup & Public API
*
* Warning: this part of the code contains browser-specific chunks --
* that's where obsolete browsers, namely IE8 and earlier, are handled.
*
* Unlike the rest of the lib, this section is not shared with FirefoxOS/Gaia.
*/
// load the default locale on startup
function l10nStartup() {
gReadyState = 'interactive';
// most browsers expose the UI language as `navigator.language'
// but IE uses `navigator.userLanguage' instead
var userLocale = navigator.language || navigator.userLanguage;
consoleLog('loading [' + userLocale + '] resources, ' +
(gAsyncResourceLoading ? 'asynchronously.' : 'synchronously.'));
// load the default locale and translate the document if required
if (document.documentElement.lang === userLocale) {
loadLocale(userLocale);
} else {
loadLocale(userLocale, translateFragment);
}
}
// browser-specific startup
if (document.addEventListener) { // modern browsers and IE9+
if (document.readyState === 'loading') {
// the document is not fully loaded yet: wait for DOMContentLoaded.
document.addEventListener('DOMContentLoaded', l10nStartup);
} else {
// l10n.js is being loaded with <script defer> or <script async>,
// the DOM is ready for parsing.
window.setTimeout(l10nStartup);
}
} else if (window.attachEvent) { // IE8 and before (= oldIE)
// TODO: check if jQuery is loaded (CSS selector + JSON + events)
// dummy `console.log' and `console.warn' functions
if (!window.console) {
consoleLog = function(message) {}; // just ignore console.log calls
consoleWarn = function(message) {
if (gDEBUG) {
alert('[l10n] ' + message); // vintage debugging, baby!
}
};
}
// XMLHttpRequest for IE6
if (!window.XMLHttpRequest) {
xhrLoadText = function(url, onSuccess, onFailure) {
onSuccess = onSuccess || function _onSuccess(data) {};
onFailure = onFailure || function _onFailure() {
consoleWarn(url + ' not found.');
};
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url, gAsyncResourceLoading);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
onSuccess(xhr.responseText);
} else {
onFailure();
}
}
};
xhr.send(null);
};
}
// worst hack ever for IE6 and IE7
if (!window.JSON) {
getL10nAttributes = function(element) {
if (!element)
return {};
var l10nId = element.getAttribute('data-l10n-id'),
l10nArgs = element.getAttribute('data-l10n-args'),
args = {};
if (l10nArgs) try {
args = eval(l10nArgs); // XXX yeah, I know...
} catch (e) {
consoleWarn('could not parse arguments for #' + l10nId);
}
return { id: l10nId, args: args };
};
}
// override `getTranslatableChildren' and `getL10nResourceLinks'
if (!document.querySelectorAll) {
getTranslatableChildren = function(element) {
if (!element)
return [];
var nodes = element.getElementsByTagName('*'),
l10nElements = [],
n = nodes.length;
for (var i = 0; i < n; i++) {
if (nodes[i].getAttribute('data-l10n-id'))
l10nElements.push(nodes[i]);
}
return l10nElements;
};
getL10nResourceLinks = function() {
var links = document.getElementsByTagName('link'),
l10nLinks = [],
n = links.length;
for (var i = 0; i < n; i++) {
if (links[i].type == 'application/l10n')
l10nLinks.push(links[i]);
}
return l10nLinks;
};
}
// override `getL10nDictionary'
if (!window.JSON || !document.querySelectorAll) {
getL10nDictionary = function() {
var scripts = document.getElementsByName('script');
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].type == 'application/l10n') {
return eval(scripts[i].innerHTML);
}
}
return null;
};
}
// fire non-standard `localized' DOM events
if (document.createEventObject && !document.createEvent) {
fireL10nReadyEvent = function(lang) {
// hack to simulate a custom event in IE:
// to catch this event, add an event handler to `onpropertychange'
document.documentElement.localized = 1;
};
}
// startup for IE<9
window.attachEvent('onload', function() {
gTextProp = document.textContent === null ? 'textContent' : 'innerText';
l10nStartup();
});
}
// cross-browser API (sorry, oldIE doesn't support getters & setters)
return {
// get a localized string
get: function(key, args, fallbackString) {
var index = key.lastIndexOf('.');
var prop = gTextProp;
if (index > 0) { // An attribute has been specified
prop = key.substr(index + 1);
key = key.substring(0, index);
}
var fallback;
if (fallbackString) {
fallback = {};
fallback[prop] = fallbackString;
}
var data = getL10nData(key, args, fallback);
if (data && prop in data) {
return data[prop];
}
return '{{' + key + '}}';
},
// debug
getData: function() { return gL10nData; },
getText: function() { return gTextData; },
// get|set the document language
getLanguage: function() { return gLanguage; },
setLanguage: function(lang, callback) {
loadLocale(lang, function() {
if (callback)
callback();
translateFragment();
});
},
// get the direction (ltr|rtl) of the current language
getDirection: function() {
// http://www.w3.org/International/questions/qa-scripts
// Arabic, Hebrew, Farsi, Pashto, Urdu
var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
return (rtlList.indexOf(gLanguage) >= 0) ? 'rtl' : 'ltr';
},
// translate an element or document fragment
translate: translateFragment,
// this can be used to prevent race conditions
getReadyState: function() { return gReadyState; },
ready: function(callback) {
if (!callback) {
return;
} else if (gReadyState == 'complete' || gReadyState == 'interactive') {
window.setTimeout(function() {
callback();
});
} else if (document.addEventListener) {
document.addEventListener('localized', function once() {
document.removeEventListener('localized', once);
callback();
});
} else if (document.attachEvent) {
document.documentElement.attachEvent('onpropertychange', function once(e) {
if (e.propertyName === 'localized') {
document.documentElement.detachEvent('onpropertychange', once);
callback();
}
});
}
}
};
}) (window, document);
// gettext-like shortcut for document.webL10n.get
if (window._ === undefined) {
var _ = document.webL10n.get;
}
| thierry-bugeat/myFeeds | www/js/libs/l10n.js | JavaScript | gpl-3.0 | 34,656 |
import { ComponentFactoryResolver, ElementRef, OnInit, OpaqueToken, Renderer, ViewContainerRef } from '@angular/core';
import { App } from './app';
import { Config } from '../../config/config';
import { Ion } from '../ion';
import { OverlayPortal } from '../nav/overlay-portal';
import { Platform } from '../../platform/platform';
export declare const AppRootToken: OpaqueToken;
/**
* @private
*/
export declare class IonicApp extends Ion implements OnInit {
private _userCmp;
private _cfr;
private _platform;
private _stopScrollPlugin;
private _rafId;
_viewport: ViewContainerRef;
_modalPortal: OverlayPortal;
_overlayPortal: OverlayPortal;
_loadingPortal: OverlayPortal;
_toastPortal: OverlayPortal;
constructor(_userCmp: any, _cfr: ComponentFactoryResolver, elementRef: ElementRef, renderer: Renderer, config: Config, _platform: Platform, app: App);
ngOnInit(): void;
/**
* @private
*/
_getPortal(portal?: AppPortal): OverlayPortal;
/**
* @private
*/
_getActivePortal(): OverlayPortal;
/**
* @private
*/
_disableScroll(shouldDisableScroll: boolean): void;
stopScroll(): Promise<boolean>;
}
export declare const enum AppPortal {
DEFAULT = 0,
MODAL = 1,
LOADING = 2,
TOAST = 3,
}
| kfrerichs/roleplay | node_modules/ionic-angular/umd/components/app/app-root.d.ts | TypeScript | gpl-3.0 | 1,305 |
#ifndef __XRDNETMSG_H__
#define __XRDNETMSG_H__
/******************************************************************************/
/* */
/* X r d N e t M s g . h h */
/* */
/* (c) 2007 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/******************************************************************************/
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <strings.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#else
#include <Winsock2.h>
#endif
#include "XrdNet/XrdNetAddr.hh"
class XrdSysError;
class XrdNetMsg
{
public:
//------------------------------------------------------------------------------
//! Send a UDP message to an endpoint.
//!
//! @param buff The data to send.
//! @param blen Length of the data in buff. If not specified, the length is
//! computed as strlen(buff).
//! @param dest The endpint name which can be host:port or a named socket.
//! If dest is zero, uses dest specified in the constructor.
//! @param timeout maximum seconds to wait for a idle socket. When negative,
//! the default, no time limit applies.
//! @return <0 Message not sent due to error.
//! @return =0 Message send (well as defined by UDP)
//! @return >0 Message not sent, timeout occured.
//------------------------------------------------------------------------------
int Send(const char *buff, // The data to be send
int blen=0, // Length (strlen(buff) if zero)
const char *dest=0, // Hostname to send UDP datagram
int tmo=-1); // Timeout in ms (-1 = none)
//------------------------------------------------------------------------------
//! Send a UDP message to an endpoint using an I/O vector.
//!
//! @param iov The vector of data to send. Total amount be <= 4096 bytes.
//! @param iovcnt The number of elements in the vector.
//! @param dest The endpint name which can be host:port or a named socket.
//! If dest is zero, uses dest specified in the constructor.
//! @param timeout maximum seconds to wait for a idle socket. When negative,
//! the default, no time limit applies.
//! @return <0 Message not sent due to error.
//! @return =0 Message send (well as defined by UDP)
//! @return >0 Message not sent, timeout occured.
//------------------------------------------------------------------------------
int Send(const struct iovec iov[], // Remaining parms as above
int iovcnt, // Number of elements in iovec
const char *dest=0, // Hostname to send UDP datagram
int tmo=-1); // Timeout in ms (-1 = none)
//------------------------------------------------------------------------------
//! Constructor
//!
//! @param erp The error message object for routing error messages.
//! @param aOK If supplied, set to true upon success; false otherwise.
//! @param dest The endpint name which can be host:port or a named socket.
//! This becomes the default endpoint. Any specified endpoint
//! to send must be in the same family (e.g. UNIX). If not
//! specified, then an endpoint must always be specified with
//! send and is restricted to be in the INET family.
//------------------------------------------------------------------------------
XrdNetMsg(XrdSysError *erp, const char *dest=0, bool *aOK=0);
//------------------------------------------------------------------------------
//! Destructor
//------------------------------------------------------------------------------
~XrdNetMsg() {if (FD >= 0) close(FD);}
protected:
int OK2Send(int timeout, const char *dest);
int retErr(int ecode, const char *theDest);
int retErr(int ecode, XrdNetAddr *theDest);
XrdSysError *eDest;
XrdNetAddr dfltDest;
XrdNetAddr specDest;
int destOK;
int FD;
};
#endif
| alja/xrootd | src/XrdNet/XrdNetMsg.hh | C++ | gpl-3.0 | 6,243 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Form for scheduled tasks admin pages.
*
* @deprecated since Moodle 3.9 MDL-63580. Please use the \core\task\manager.
* @todo final deprecation. To be removed in Moodle 4.3 MDL-63594.
*
* @package tool_task
* @copyright 2018 Toni Barbera <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_task;
defined('MOODLE_INTERNAL') || die();
/**
* Running tasks from CLI.
*
* @copyright 2018 Toni Barbera <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class run_from_cli {
/**
* Find the path of PHP CLI binary.
*
* @return string|false The PHP CLI executable PATH
*/
protected static function find_php_cli_path() {
global $CFG;
if (!empty($CFG->pathtophp) && is_executable(trim($CFG->pathtophp))) {
return $CFG->pathtophp;
}
return false;
}
/**
* Returns if Moodle have access to PHP CLI binary or not.
*
* @return bool
*/
public static function is_runnable():bool {
debugging('run_from_cli class is deprecated. Please use \core\task\manager::run_from_cli() instead.',
DEBUG_DEVELOPER);
return \core\task\manager::is_runnable();
}
/**
* Executes a cron from web invocation using PHP CLI.
*
* @param \core\task\task_base $task Task that be executed via CLI.
* @return bool
* @throws \moodle_exception
*/
public static function execute(\core\task\task_base $task):bool {
debugging('run_from_cli class is deprecated. Please use \core\task\manager::run_from_cli() instead.',
DEBUG_DEVELOPER);
return \core\task\manager::run_from_cli($task);
}
}
| marcusboon/moodle | admin/tool/task/classes/run_from_cli.php | PHP | gpl-3.0 | 2,461 |
/**
* Aptana Studio
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ide.syncing.ui.views;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.filesystem.IFileInfo;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.util.TransferDragSourceListener;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import com.aptana.core.CoreStrings;
import com.aptana.core.io.vfs.IExtendedFileStore;
import com.aptana.core.util.FileUtil;
import com.aptana.ide.core.io.IBaseRemoteConnectionPoint;
import com.aptana.ide.core.io.IConnectionPoint;
import com.aptana.ide.syncing.ui.SyncingUIPlugin;
import com.aptana.ide.ui.io.IOUIPlugin;
import com.aptana.ide.ui.io.Utils;
import com.aptana.ide.ui.io.actions.CopyFilesOperation;
import com.aptana.ide.ui.io.navigator.FileTreeContentProvider;
import com.aptana.ide.ui.io.navigator.FileTreeNameSorter;
import com.aptana.ide.ui.io.navigator.actions.FileSystemDeleteAction;
import com.aptana.ide.ui.io.navigator.actions.FileSystemRenameAction;
import com.aptana.ide.ui.io.navigator.actions.OpenFileAction;
import com.aptana.ui.util.SWTUtils;
import com.aptana.ui.util.UIUtils;
/**
* @author Michael Xia ([email protected])
*/
public class ConnectionPointComposite implements SelectionListener, ISelectionChangedListener, IDoubleClickListener,
TransferDragSourceListener, DropTargetListener
{
public static interface Client
{
public void transfer(ConnectionPointComposite source);
}
private static final String[] COLUMN_NAMES = { Messages.ConnectionPointComposite_Column_Filename,
Messages.ConnectionPointComposite_Column_Size, Messages.ConnectionPointComposite_Column_LastModified };
private Composite fMain;
private Link fEndPointLink;
private ToolItem fRefreshItem;
private ToolItem fHomeItem;
private Link fPathLink;
private TreeViewer fTreeViewer;
private MenuItem fOpenItem;
private MenuItem fTransferItem;
private MenuItem fDeleteItem;
private MenuItem fRenameItem;
private MenuItem fRefreshMenuItem;
private MenuItem fPropertiesItem;
private String fName;
private IConnectionPoint fConnectionPoint;
private List<IAdaptable> fEndPointData;
private Client fClient;
public ConnectionPointComposite(Composite parent, String name, Client client)
{
fName = name;
fClient = client;
fEndPointData = new ArrayList<IAdaptable>();
fMain = createControl(parent);
}
public Control getControl()
{
return fMain;
}
public IAdaptable getCurrentInput()
{
// the root input is always IAdaptable
return (IAdaptable) fTreeViewer.getInput();
}
public IAdaptable[] getSelectedElements()
{
ISelection selection = fTreeViewer.getSelection();
if (selection.isEmpty() || !(selection instanceof IStructuredSelection))
{
return new IAdaptable[0];
}
Object[] elements = ((IStructuredSelection) selection).toArray();
// the selection should be all IAdaptable objects, but just to make sure
List<IAdaptable> list = new ArrayList<IAdaptable>();
for (Object element : elements)
{
if (element instanceof IAdaptable)
{
list.add((IAdaptable) element);
}
}
return list.toArray(new IAdaptable[list.size()]);
}
public void setFocus()
{
fMain.setFocus();
}
public void setConnectionPoint(IConnectionPoint connection)
{
fConnectionPoint = connection;
fEndPointData.clear();
if (fConnectionPoint == null)
{
fEndPointLink.setText(""); //$NON-NLS-1$
}
else
{
String label = connection.getName();
String tooltip = label;
if (connection instanceof IBaseRemoteConnectionPoint)
{
IPath path = ((IBaseRemoteConnectionPoint) connection).getPath();
if (path.segmentCount() > 0)
{
tooltip = MessageFormat.format("{0} ({1})", new Object[] { connection.getName(), //$NON-NLS-1$
path.toPortableString() });
}
}
fEndPointLink.setText(MessageFormat.format("<a>{0}</a>", label)); //$NON-NLS-1$
fEndPointLink.setToolTipText(tooltip);
fEndPointData.add(fConnectionPoint);
}
setPath(""); //$NON-NLS-1$
fMain.layout(true, true);
fTreeViewer.setInput(connection);
}
/**
* Adds a focus listener to the tree control to allow users the ability to listen for focus events.
*
* @param listener
*/
public void addTreeFocusListener(FocusListener listener)
{
fTreeViewer.getControl().addFocusListener(listener);
}
public void refresh()
{
Object input = fTreeViewer.getInput();
IResource resource = null;
if (input instanceof IAdaptable)
{
resource = (IResource) ((IAdaptable) input).getAdapter(IResource.class);
}
if (resource != null)
{
try
{
resource.refreshLocal(IResource.DEPTH_INFINITE, null);
}
catch (CoreException e)
{
}
}
updateContent(fEndPointData.get(fEndPointData.size() - 1));
}
public void widgetDefaultSelected(SelectionEvent e)
{
}
public void widgetSelected(SelectionEvent e)
{
Object source = e.getSource();
if (source == fRefreshItem)
{
refresh();
}
else if (source == fHomeItem)
{
gotoHome();
}
else if (source == fOpenItem)
{
open(fTreeViewer.getSelection());
}
else if (source == fTransferItem)
{
if (fClient != null)
{
fClient.transfer(this);
}
}
else if (source == fDeleteItem)
{
delete(fTreeViewer.getSelection());
}
else if (source == fRenameItem)
{
rename();
}
else if (source == fRefreshMenuItem)
{
refresh(fTreeViewer.getSelection());
}
else if (source == fPropertiesItem)
{
openPropertyPage(fTreeViewer.getSelection());
}
else if (source == fPathLink)
{
// e.text has the index; needs to increment by 1 since 0 for
// fEndPointData is the root
updateContent(fEndPointData.get(Integer.parseInt(e.text) + 1));
}
else if (source == fEndPointLink)
{
gotoHome();
}
}
public void selectionChanged(SelectionChangedEvent event)
{
updateMenuStates();
}
public void doubleClick(DoubleClickEvent event)
{
if (fClient == null)
{
open(event.getSelection());
}
else
{
Object object = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (object instanceof IAdaptable)
{
IAdaptable adaptable = (IAdaptable) object;
if (Utils.isDirectory((IAdaptable) object))
{
// goes into the folder
updateContent(adaptable);
}
else
{
fClient.transfer(this);
}
}
}
}
public Transfer getTransfer()
{
return LocalSelectionTransfer.getTransfer();
}
public void dragFinished(DragSourceEvent event)
{
LocalSelectionTransfer.getTransfer().setSelection(null);
LocalSelectionTransfer.getTransfer().setSelectionSetTime(0);
}
public void dragSetData(DragSourceEvent event)
{
event.data = fTreeViewer.getSelection();
}
public void dragStart(DragSourceEvent event)
{
LocalSelectionTransfer.getTransfer().setSelection(fTreeViewer.getSelection());
LocalSelectionTransfer.getTransfer().setSelectionSetTime(event.time & 0xFFFFFFFFL);
}
public void dragEnter(DropTargetEvent event)
{
if (event.detail == DND.DROP_DEFAULT)
{
if ((event.operations & DND.DROP_COPY) == 0)
{
event.detail = DND.DROP_NONE;
}
else
{
event.detail = DND.DROP_COPY;
}
}
}
public void dragLeave(DropTargetEvent event)
{
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
}
public void drop(DropTargetEvent event)
{
IFileStore targetStore = null;
if (event.item == null)
{
targetStore = Utils.getFileStore((IAdaptable) fTreeViewer.getInput());
}
else
{
TreeItem target = (TreeItem) event.item;
targetStore = getFolderStore((IAdaptable) target.getData());
}
if (targetStore == null)
{
return;
}
if (event.data instanceof ITreeSelection)
{
ITreeSelection selection = (ITreeSelection) event.data;
TreePath[] paths = selection.getPaths();
if (paths.length > 0)
{
List<IAdaptable> elements = new ArrayList<IAdaptable>();
for (TreePath path : paths)
{
boolean alreadyIn = false;
for (TreePath path2 : paths)
{
if (!path.equals(path2) && path.startsWith(path2, null))
{
alreadyIn = true;
break;
}
}
if (!alreadyIn)
{
elements.add((IAdaptable) path.getLastSegment());
}
}
CopyFilesOperation operation = new CopyFilesOperation(getControl().getShell());
operation.copyFiles(elements.toArray(new IAdaptable[elements.size()]), targetStore,
new JobChangeAdapter()
{
@Override
public void done(IJobChangeEvent event)
{
IOUIPlugin.refreshNavigatorView(fTreeViewer.getInput());
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
refresh();
}
});
}
});
}
}
}
public void dropAccept(DropTargetEvent event)
{
}
protected Composite createControl(Composite parent)
{
Composite main = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
main.setLayout(layout);
Composite top = createTopComposite(main);
top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
Composite path = createPathComposite(main);
path.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
TreeViewer treeViewer = createTreeViewer(main);
treeViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
return main;
}
private Composite createTopComposite(Composite parent)
{
Composite main = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(3, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
main.setLayout(layout);
Label label = new Label(main, SWT.NONE);
label.setText(fName + ":"); //$NON-NLS-1$
fEndPointLink = new Link(main, SWT.NONE);
fEndPointLink.addSelectionListener(this);
ToolBar toolbar = new ToolBar(main, SWT.FLAT);
fHomeItem = new ToolItem(toolbar, SWT.PUSH);
fHomeItem.setImage(SyncingUIPlugin.getImage("icons/full/obj16/home.png")); //$NON-NLS-1$
fHomeItem.setToolTipText(Messages.ConnectionPointComposite_TTP_Home);
fHomeItem.addSelectionListener(this);
return main;
}
private Composite createPathComposite(Composite parent)
{
Composite main = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
main.setLayout(layout);
fPathLink = new Link(main, SWT.NONE);
fPathLink.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// uses a bold font for path
final Font font = new Font(fPathLink.getDisplay(), SWTUtils.boldFont(fPathLink.getFont()));
fPathLink.setFont(font);
fPathLink.addDisposeListener(new DisposeListener()
{
public void widgetDisposed(DisposeEvent e)
{
font.dispose();
}
});
fPathLink.addSelectionListener(this);
ToolBar toolbar = new ToolBar(main, SWT.FLAT);
fRefreshItem = new ToolItem(toolbar, SWT.PUSH);
fRefreshItem.setImage(SyncingUIPlugin.getImage("icons/full/obj16/refresh.gif")); //$NON-NLS-1$
fRefreshItem.setToolTipText(Messages.ConnectionPointComposite_TTP_Refresh);
fRefreshItem.addSelectionListener(this);
return main;
}
private TreeViewer createTreeViewer(Composite parent)
{
fTreeViewer = new TreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
Tree tree = fTreeViewer.getTree();
tree.setHeaderVisible(true);
TreeColumn column = new TreeColumn(tree, SWT.LEFT);
column.setWidth(300);
column.setText(COLUMN_NAMES[0]);
column = new TreeColumn(tree, SWT.LEFT);
column.setWidth(50);
column.setText(COLUMN_NAMES[1]);
column = new TreeColumn(tree, SWT.LEFT);
column.setWidth(150);
column.setText(COLUMN_NAMES[2]);
fTreeViewer.setContentProvider(new FileTreeContentProvider());
fTreeViewer.setLabelProvider(new ConnectionPointLabelProvider());
fTreeViewer.setComparator(new FileTreeNameSorter());
fTreeViewer.addSelectionChangedListener(this);
fTreeViewer.addDoubleClickListener(this);
fTreeViewer.addDragSupport(DND.DROP_COPY | DND.DROP_DEFAULT,
new Transfer[] { LocalSelectionTransfer.getTransfer() }, this);
fTreeViewer.addDropSupport(DND.DROP_COPY | DND.DROP_DEFAULT,
new Transfer[] { LocalSelectionTransfer.getTransfer() }, this);
// builds the context menu
tree.setMenu(createMenu(tree));
updateMenuStates();
return fTreeViewer;
}
private Menu createMenu(Control parent)
{
Menu menu = new Menu(parent);
fOpenItem = new MenuItem(menu, SWT.PUSH);
fOpenItem.setText(CoreStrings.OPEN);
fOpenItem.setAccelerator(SWT.F3);
fOpenItem.addSelectionListener(this);
fTransferItem = new MenuItem(menu, SWT.PUSH);
fTransferItem.setText(Messages.ConnectionPointComposite_LBL_Transfer);
fTransferItem.addSelectionListener(this);
new MenuItem(menu, SWT.SEPARATOR);
fDeleteItem = new MenuItem(menu, SWT.PUSH);
fDeleteItem.setText(CoreStrings.DELETE);
fDeleteItem.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ETOOL_DELETE));
fDeleteItem.setAccelerator(SWT.DEL);
fDeleteItem.addSelectionListener(this);
fRenameItem = new MenuItem(menu, SWT.PUSH);
fRenameItem.setText(CoreStrings.RENAME);
fRenameItem.setAccelerator(SWT.F2);
fRenameItem.addSelectionListener(this);
new MenuItem(menu, SWT.SEPARATOR);
fRefreshMenuItem = new MenuItem(menu, SWT.PUSH);
fRefreshMenuItem.setText(CoreStrings.REFRESH);
fRefreshMenuItem.setImage(SyncingUIPlugin.getImage("/icons/full/obj16/refresh.gif")); //$NON-NLS-1$
fRefreshMenuItem.setAccelerator(SWT.F5);
fRefreshMenuItem.addSelectionListener(this);
new MenuItem(menu, SWT.SEPARATOR);
fPropertiesItem = new MenuItem(menu, SWT.PUSH);
fPropertiesItem.setText(CoreStrings.PROPERTIES);
fPropertiesItem.setAccelerator(SWT.ALT | '\r');
fPropertiesItem.addSelectionListener(this);
return menu;
}
private void gotoHome()
{
updateContent(fConnectionPoint);
}
private void open(ISelection selection)
{
Object object = ((IStructuredSelection) selection).getFirstElement();
if (object instanceof IAdaptable)
{
IAdaptable adaptable = (IAdaptable) object;
if (Utils.isDirectory((IAdaptable) object))
{
// goes into the folder
updateContent(adaptable);
}
else
{
// opens the file in the editor
OpenFileAction action = new OpenFileAction();
action.updateSelection((IStructuredSelection) selection);
action.run();
}
}
}
private void delete(ISelection selection)
{
final FileSystemDeleteAction action = new FileSystemDeleteAction(getControl().getShell(), fTreeViewer.getTree());
action.updateSelection((IStructuredSelection) selection);
action.addJobListener(new JobChangeAdapter()
{
@Override
public void done(IJobChangeEvent event)
{
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
refresh();
}
});
action.removeJobListener(this);
}
});
action.run();
}
private void rename()
{
FileSystemRenameAction action = new FileSystemRenameAction(getControl().getShell(), fTreeViewer.getTree());
action.run();
refresh();
}
private void refresh(ISelection selection)
{
if (selection.isEmpty())
{
// refreshes the root
refresh();
}
else
{
Object[] elements = ((IStructuredSelection) selection).toArray();
IResource resource;
for (Object element : elements)
{
resource = null;
if (element instanceof IAdaptable)
{
resource = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
}
if (resource != null)
{
try
{
resource.refreshLocal(IResource.DEPTH_INFINITE, null);
}
catch (CoreException e)
{
}
}
fTreeViewer.refresh(element);
}
}
}
private void openPropertyPage(ISelection selection)
{
IAdaptable element = (IAdaptable) ((IStructuredSelection) selection).getFirstElement();
PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(getControl().getShell(), element, null, null,
null);
dialog.open();
}
private void setComboData(IAdaptable data)
{
fEndPointData.clear();
if (data instanceof IContainer)
{
// a workspace project/folder
IContainer container = (IContainer) data;
IContainer root = (IContainer) fConnectionPoint.getAdapter(IResource.class);
String path = getRelativePath(root, container);
if (path != null)
{
String[] segments = (new Path(path)).segments();
IContainer segmentPath = root;
for (String segment : segments)
{
segmentPath = (IContainer) segmentPath.findMember(segment);
fEndPointData.add(segmentPath);
}
}
}
else
{
// a filesystem or remote path
IFileStore fileStore = Utils.getFileStore(data);
if (fileStore != null)
{
IFileStore homeFileStore = Utils.getFileStore(fConnectionPoint);
while (fileStore.getParent() != null && !fileStore.equals(homeFileStore))
{
fEndPointData.add(0, fileStore);
fileStore = fileStore.getParent();
}
}
}
fEndPointData.add(0, fConnectionPoint);
}
private void setPath(String path)
{
StringBuilder linkPath = new StringBuilder();
path = path.replace('\\', '/');
String separator = "/"; //$NON-NLS-1$
if (path.startsWith(separator))
{
// removes the leading separator
path = path.substring(1);
}
String displayedPath = FileUtil.compressLeadingPath(path, 60);
if (displayedPath.equals(path))
{
String[] folders = path.split(separator);
int i;
for (i = 0; i < folders.length - 1; ++i)
{
linkPath.append(MessageFormat.format("<a href=\"{0}\">{1}</a>", i, folders[i])); //$NON-NLS-1$
linkPath.append(separator);
}
if (folders.length > 0)
{
// no need for a link on the last directory since we are in it
linkPath.append(folders[i]);
}
}
else
{
// deals with the compression
linkPath.append("...").append(separator); //$NON-NLS-1$
// strips out the leading '.../'
String endPath = displayedPath.substring(4);
String[] endFolders = endPath.split(separator);
int startIndex = path.split(separator).length - endFolders.length;
int i;
for (i = 0; i < endFolders.length - 1; ++i)
{
linkPath.append(MessageFormat.format("<a href=\"{0}\">{1}</a>", startIndex + i, endFolders[i])); //$NON-NLS-1$
linkPath.append(separator);
}
if (endFolders.length > 0)
{
// no need for a link on the last directory since we are in it
linkPath.append(endFolders[i]);
}
}
fPathLink.setText(Messages.ConnectionPointComposite_LBL_Path + linkPath.toString());
}
private void updateContent(IAdaptable rootElement)
{
setComboData(rootElement);
if (rootElement instanceof IContainer)
{
setPath(getRelativePath((IContainer) fConnectionPoint.getAdapter(IResource.class), (IContainer) rootElement));
}
else
{
IFileStore fileStore = Utils.getFileStore(rootElement);
if (fileStore != null)
{
String path = fileStore.toString();
IFileStore homeFileStore = Utils.getFileStore(fConnectionPoint);
if (homeFileStore != null)
{
String homePath = homeFileStore.toString();
int index = path.indexOf(homePath);
if (index > -1)
{
path = path.substring(index + homePath.length());
}
}
setPath(path);
}
}
fTreeViewer.setInput(rootElement);
}
private void updateMenuStates()
{
ISelection selection = fTreeViewer.getSelection();
boolean hasSelection = !selection.isEmpty() && (selection instanceof IStructuredSelection);
boolean singleSelection = hasSelection && ((IStructuredSelection) selection).size() == 1;
fOpenItem.setEnabled(hasSelection);
fTransferItem.setEnabled(hasSelection);
fDeleteItem.setEnabled(hasSelection);
fRenameItem.setEnabled(hasSelection && singleSelection);
fPropertiesItem.setEnabled(hasSelection && singleSelection);
}
private static IFileStore getFolderStore(IAdaptable destination)
{
IFileStore store = Utils.getFileStore(destination);
IFileInfo info = Utils.getFileInfo(destination, IExtendedFileStore.EXISTENCE);
if (store != null && info != null && !info.isDirectory())
{
store = store.getParent();
}
return store;
}
/**
* @param root
* the root container
* @param element
* a container under the root
* @return the relative path string of the element from the root
*/
private static String getRelativePath(IContainer root, IContainer element)
{
String rootPath = root.getFullPath().toString();
String elementPath = element.getFullPath().toString();
int index = elementPath.indexOf(rootPath);
if (index == -1)
{
return null;
}
return elementPath.substring(index + rootPath.length());
}
}
| HossainKhademian/Studio3 | plugins/com.aptana.syncing.ui/src/com/aptana/ide/syncing/ui/views/ConnectionPointComposite.java | Java | gpl-3.0 | 23,079 |
/**
* Aptana Studio
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ui;
import java.util.Collection;
import java.util.List;
import com.aptana.core.util.IBrowserUtil.BrowserInfo;
public interface IBrowserProvider
{
/**
* @return a list with the current information on configured web browsers.
* @note the default browser may have a null location.
*/
List<BrowserInfo> getWebBrowsers();
/**
* @return the new browsers that have been found.
* @note the default browser may have a null location.
*/
Collection<BrowserInfo> searchMoreBrowsers();
/**
* @return information on the currently configured web browser.
* @note the default browser may have a null location.
*/
BrowserInfo getCurrentWebBrowser();
/**
* @return the version of the given browser.
*/
String getBrowserVersion(BrowserInfo info);
}
| HossainKhademian/Studio3 | plugins/com.aptana.ui/src/com/aptana/ui/IBrowserProvider.java | Java | gpl-3.0 | 1,150 |
--
-- CREATE_INDEX
-- Create ancillary data structures (i.e. indices)
--
--
-- BTREE
--
CREATE INDEX onek_unique1 ON onek USING btree(unique1 int4_ops);
CREATE INDEX IF NOT EXISTS onek_unique1 ON onek USING btree(unique1 int4_ops);
CREATE INDEX IF NOT EXISTS ON onek USING btree(unique1 int4_ops);
CREATE INDEX onek_unique2 ON onek USING btree(unique2 int4_ops);
CREATE INDEX onek_hundred ON onek USING btree(hundred int4_ops);
CREATE INDEX onek_stringu1 ON onek USING btree(stringu1 name_ops);
CREATE INDEX tenk1_unique1 ON tenk1 USING btree(unique1 int4_ops);
CREATE INDEX tenk1_unique2 ON tenk1 USING btree(unique2 int4_ops);
CREATE INDEX tenk1_hundred ON tenk1 USING btree(hundred int4_ops);
CREATE INDEX tenk1_thous_tenthous ON tenk1 (thousand, tenthous);
CREATE INDEX tenk2_unique1 ON tenk2 USING btree(unique1 int4_ops);
CREATE INDEX tenk2_unique2 ON tenk2 USING btree(unique2 int4_ops);
CREATE INDEX tenk2_hundred ON tenk2 USING btree(hundred int4_ops);
CREATE INDEX rix ON road USING btree (name text_ops);
CREATE INDEX iix ON ihighway USING btree (name text_ops);
CREATE INDEX six ON shighway USING btree (name text_ops);
-- test comments
COMMENT ON INDEX six_wrong IS 'bad index';
COMMENT ON INDEX six IS 'good index';
COMMENT ON INDEX six IS NULL;
--
-- BTREE ascending/descending cases
--
-- we load int4/text from pure descending data (each key is a new
-- low key) and name/f8 from pure ascending data (each key is a new
-- high key). we had a bug where new low keys would sometimes be
-- "lost".
--
CREATE INDEX bt_i4_index ON bt_i4_heap USING btree (seqno int4_ops);
CREATE INDEX bt_name_index ON bt_name_heap USING btree (seqno name_ops);
CREATE INDEX bt_txt_index ON bt_txt_heap USING btree (seqno text_ops);
CREATE INDEX bt_f8_index ON bt_f8_heap USING btree (seqno float8_ops);
--
-- BTREE partial indices
--
CREATE INDEX onek2_u1_prtl ON onek2 USING btree(unique1 int4_ops)
where unique1 < 20 or unique1 > 980;
CREATE INDEX onek2_u2_prtl ON onek2 USING btree(unique2 int4_ops)
where stringu1 < 'B';
CREATE INDEX onek2_stu1_prtl ON onek2 USING btree(stringu1 name_ops)
where onek2.stringu1 >= 'J' and onek2.stringu1 < 'K';
--
-- GiST (rtree-equivalent opclasses only)
--
CREATE INDEX grect2ind ON fast_emp4000 USING gist (home_base);
CREATE INDEX gpolygonind ON polygon_tbl USING gist (f1);
CREATE INDEX gcircleind ON circle_tbl USING gist (f1);
INSERT INTO POINT_TBL(f1) VALUES (NULL);
CREATE INDEX gpointind ON point_tbl USING gist (f1);
CREATE TEMP TABLE gpolygon_tbl AS
SELECT polygon(home_base) AS f1 FROM slow_emp4000;
INSERT INTO gpolygon_tbl VALUES ( '(1000,0,0,1000)' );
INSERT INTO gpolygon_tbl VALUES ( '(0,1000,1000,1000)' );
CREATE TEMP TABLE gcircle_tbl AS
SELECT circle(home_base) AS f1 FROM slow_emp4000;
CREATE INDEX ggpolygonind ON gpolygon_tbl USING gist (f1);
CREATE INDEX ggcircleind ON gcircle_tbl USING gist (f1);
--
-- SP-GiST
--
CREATE TABLE quad_point_tbl AS
SELECT point(unique1,unique2) AS p FROM tenk1;
INSERT INTO quad_point_tbl
SELECT '(333.0,400.0)'::point FROM generate_series(1,1000);
INSERT INTO quad_point_tbl VALUES (NULL), (NULL), (NULL);
CREATE INDEX sp_quad_ind ON quad_point_tbl USING spgist (p);
CREATE TABLE kd_point_tbl AS SELECT * FROM quad_point_tbl;
CREATE INDEX sp_kd_ind ON kd_point_tbl USING spgist (p kd_point_ops);
CREATE TABLE radix_text_tbl AS
SELECT name AS t FROM road WHERE name !~ '^[0-9]';
INSERT INTO radix_text_tbl
SELECT 'P0123456789abcdef' FROM generate_series(1,1000);
INSERT INTO radix_text_tbl VALUES ('P0123456789abcde');
INSERT INTO radix_text_tbl VALUES ('P0123456789abcdefF');
CREATE INDEX sp_radix_ind ON radix_text_tbl USING spgist (t);
--
-- Test GiST and SP-GiST indexes
--
-- get non-indexed results for comparison purposes
SET enable_seqscan = ON;
SET enable_indexscan = OFF;
SET enable_bitmapscan = OFF;
SELECT * FROM fast_emp4000
WHERE home_base @ '(200,200),(2000,1000)'::box
ORDER BY (home_base[0])[0];
SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box;
SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL;
SELECT * FROM polygon_tbl WHERE f1 ~ '((1,1),(2,2),(2,1))'::polygon
ORDER BY (poly_center(f1))[0];
SELECT * FROM circle_tbl WHERE f1 && circle(point(1,-2), 1)
ORDER BY area(f1);
SELECT count(*) FROM gpolygon_tbl WHERE f1 && '(1000,1000,0,0)'::polygon;
SELECT count(*) FROM gcircle_tbl WHERE f1 && '<(500,500),500>'::circle;
SELECT count(*) FROM point_tbl WHERE f1 <@ box '(0,0,100,100)';
SELECT count(*) FROM point_tbl WHERE box '(0,0,100,100)' @> f1;
SELECT count(*) FROM point_tbl WHERE f1 <@ polygon '(0,0),(0,100),(100,100),(50,50),(100,0),(0,0)';
SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>';
SELECT count(*) FROM point_tbl p WHERE p.f1 << '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 >> '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 <^ '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 >^ '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 ~= '(-5, -12)';
SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';
SELECT * FROM point_tbl WHERE f1 IS NULL;
SELECT * FROM point_tbl WHERE f1 IS NOT NULL ORDER BY f1 <-> '0,1';
SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1';
SELECT count(*) FROM quad_point_tbl WHERE p IS NULL;
SELECT count(*) FROM quad_point_tbl WHERE p IS NOT NULL;
SELECT count(*) FROM quad_point_tbl;
SELECT count(*) FROM quad_point_tbl WHERE p <@ box '(200,200,1000,1000)';
SELECT count(*) FROM quad_point_tbl WHERE box '(200,200,1000,1000)' @> p;
SELECT count(*) FROM quad_point_tbl WHERE p << '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p >> '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p <^ '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p >^ '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p ~= '(4585, 365)';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdef';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcde';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdefF';
SELECT count(*) FROM radix_text_tbl WHERE t < 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t ~<~ 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t <= 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t ~<=~ 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t = 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t = 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t >= 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t ~>=~ 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t > 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t ~>~ 'Worth St ';
SELECT * FROM gpolygon_tbl ORDER BY f1 <-> '(0,0)'::point LIMIT 10;
SELECT circle_center(f1), round(radius(f1)) as radius FROM gcircle_tbl ORDER BY f1 <-> '(200,300)'::point LIMIT 10;
-- Now check the results from plain indexscan
SET enable_seqscan = OFF;
SET enable_indexscan = ON;
SET enable_bitmapscan = OFF;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT * FROM fast_emp4000
WHERE home_base @ '(200,200),(2000,1000)'::box
ORDER BY (home_base[0])[0];
SELECT * FROM fast_emp4000
WHERE home_base @ '(200,200),(2000,1000)'::box
ORDER BY (home_base[0])[0];
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box;
SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL;
SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM polygon_tbl WHERE f1 ~ '((1,1),(2,2),(2,1))'::polygon
ORDER BY (poly_center(f1))[0];
SELECT * FROM polygon_tbl WHERE f1 ~ '((1,1),(2,2),(2,1))'::polygon
ORDER BY (poly_center(f1))[0];
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM circle_tbl WHERE f1 && circle(point(1,-2), 1)
ORDER BY area(f1);
SELECT * FROM circle_tbl WHERE f1 && circle(point(1,-2), 1)
ORDER BY area(f1);
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM gpolygon_tbl WHERE f1 && '(1000,1000,0,0)'::polygon;
SELECT count(*) FROM gpolygon_tbl WHERE f1 && '(1000,1000,0,0)'::polygon;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM gcircle_tbl WHERE f1 && '<(500,500),500>'::circle;
SELECT count(*) FROM gcircle_tbl WHERE f1 && '<(500,500),500>'::circle;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl WHERE f1 <@ box '(0,0,100,100)';
SELECT count(*) FROM point_tbl WHERE f1 <@ box '(0,0,100,100)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl WHERE box '(0,0,100,100)' @> f1;
SELECT count(*) FROM point_tbl WHERE box '(0,0,100,100)' @> f1;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl WHERE f1 <@ polygon '(0,0),(0,100),(100,100),(50,50),(100,0),(0,0)';
SELECT count(*) FROM point_tbl WHERE f1 <@ polygon '(0,0),(0,100),(100,100),(50,50),(100,0),(0,0)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>';
SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl p WHERE p.f1 << '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 << '(0.0, 0.0)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl p WHERE p.f1 >> '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 >> '(0.0, 0.0)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl p WHERE p.f1 <^ '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 <^ '(0.0, 0.0)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl p WHERE p.f1 >^ '(0.0, 0.0)';
SELECT count(*) FROM point_tbl p WHERE p.f1 >^ '(0.0, 0.0)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT count(*) FROM point_tbl p WHERE p.f1 ~= '(-5, -12)';
SELECT count(*) FROM point_tbl p WHERE p.f1 ~= '(-5, -12)';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';
SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM point_tbl WHERE f1 IS NULL;
SELECT * FROM point_tbl WHERE f1 IS NULL;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM point_tbl WHERE f1 IS NOT NULL ORDER BY f1 <-> '0,1';
SELECT * FROM point_tbl WHERE f1 IS NOT NULL ORDER BY f1 <-> '0,1';
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1';
SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p IS NULL;
SELECT count(*) FROM quad_point_tbl WHERE p IS NULL;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p IS NOT NULL;
SELECT count(*) FROM quad_point_tbl WHERE p IS NOT NULL;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl;
SELECT count(*) FROM quad_point_tbl;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p <@ box '(200,200,1000,1000)';
SELECT count(*) FROM quad_point_tbl WHERE p <@ box '(200,200,1000,1000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE box '(200,200,1000,1000)' @> p;
SELECT count(*) FROM quad_point_tbl WHERE box '(200,200,1000,1000)' @> p;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p << '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p << '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p >> '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p >> '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p <^ '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p <^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p >^ '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p >^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p ~= '(4585, 365)';
SELECT count(*) FROM quad_point_tbl WHERE p ~= '(4585, 365)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p <@ box '(200,200,1000,1000)';
SELECT count(*) FROM kd_point_tbl WHERE p <@ box '(200,200,1000,1000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE box '(200,200,1000,1000)' @> p;
SELECT count(*) FROM kd_point_tbl WHERE box '(200,200,1000,1000)' @> p;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p << '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p << '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p >> '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p >> '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p <^ '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p <^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p >^ '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p >^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p ~= '(4585, 365)';
SELECT count(*) FROM kd_point_tbl WHERE p ~= '(4585, 365)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdef';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdef';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcde';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcde';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdefF';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdefF';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t < 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t < 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~<~ 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t ~<~ 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t <= 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t <= 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~<=~ 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t ~<=~ 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t = 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t = 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t >= 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t >= 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~>=~ 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t ~>=~ 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t > 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t > 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~>~ 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t ~>~ 'Worth St ';
EXPLAIN (COSTS OFF)
SELECT * FROM gpolygon_tbl ORDER BY f1 <-> '(0,0)'::point LIMIT 10;
SELECT * FROM gpolygon_tbl ORDER BY f1 <-> '(0,0)'::point LIMIT 10;
EXPLAIN (COSTS OFF)
SELECT circle_center(f1), round(radius(f1)) as radius FROM gcircle_tbl ORDER BY f1 <-> '(200,300)'::point LIMIT 10;
SELECT circle_center(f1), round(radius(f1)) as radius FROM gcircle_tbl ORDER BY f1 <-> '(200,300)'::point LIMIT 10;
-- Now check the results from bitmap indexscan
SET enable_seqscan = OFF;
SET enable_indexscan = OFF;
SET enable_bitmapscan = ON;
EXPLAIN (COSTS OFF, NODES OFF)
SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1';
SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p IS NULL;
SELECT count(*) FROM quad_point_tbl WHERE p IS NULL;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p IS NOT NULL;
SELECT count(*) FROM quad_point_tbl WHERE p IS NOT NULL;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl;
SELECT count(*) FROM quad_point_tbl;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p <@ box '(200,200,1000,1000)';
SELECT count(*) FROM quad_point_tbl WHERE p <@ box '(200,200,1000,1000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE box '(200,200,1000,1000)' @> p;
SELECT count(*) FROM quad_point_tbl WHERE box '(200,200,1000,1000)' @> p;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p << '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p << '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p >> '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p >> '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p <^ '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p <^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p >^ '(5000, 4000)';
SELECT count(*) FROM quad_point_tbl WHERE p >^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM quad_point_tbl WHERE p ~= '(4585, 365)';
SELECT count(*) FROM quad_point_tbl WHERE p ~= '(4585, 365)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p <@ box '(200,200,1000,1000)';
SELECT count(*) FROM kd_point_tbl WHERE p <@ box '(200,200,1000,1000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE box '(200,200,1000,1000)' @> p;
SELECT count(*) FROM kd_point_tbl WHERE box '(200,200,1000,1000)' @> p;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p << '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p << '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p >> '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p >> '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p <^ '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p <^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p >^ '(5000, 4000)';
SELECT count(*) FROM kd_point_tbl WHERE p >^ '(5000, 4000)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM kd_point_tbl WHERE p ~= '(4585, 365)';
SELECT count(*) FROM kd_point_tbl WHERE p ~= '(4585, 365)';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdef';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdef';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcde';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcde';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdefF';
SELECT count(*) FROM radix_text_tbl WHERE t = 'P0123456789abcdefF';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t < 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t < 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~<~ 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t ~<~ 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t <= 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t <= 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~<=~ 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t ~<=~ 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'Aztec Ct ';
SELECT count(*) FROM radix_text_tbl WHERE t = 'Aztec Ct ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t = 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t = 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t >= 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t >= 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~>=~ 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t ~>=~ 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t > 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t > 'Worth St ';
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM radix_text_tbl WHERE t ~>~ 'Worth St ';
SELECT count(*) FROM radix_text_tbl WHERE t ~>~ 'Worth St ';
RESET enable_seqscan;
RESET enable_indexscan;
RESET enable_bitmapscan;
--
-- GIN over int[] and text[]
--
-- Note: GIN currently supports only bitmap scans, not plain indexscans
--
SET enable_seqscan = OFF;
SET enable_indexscan = OFF;
SET enable_bitmapscan = ON;
CREATE INDEX intarrayidx ON array_index_op_test USING gin (i);
explain (nodes off, costs off)
SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i && '{32}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i @> '{17}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i && '{17}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i @> '{32,17}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i && '{32,17}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i <@ '{38,34,32,89}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i = '{47,77}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i = '{}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i @> '{}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i && '{}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i <@ '{}' ORDER BY seqno;
SELECT * FROM array_op_test WHERE i = '{NULL}' ORDER BY seqno;
SELECT * FROM array_op_test WHERE i @> '{NULL}' ORDER BY seqno;
SELECT * FROM array_op_test WHERE i && '{NULL}' ORDER BY seqno;
SELECT * FROM array_op_test WHERE i <@ '{NULL}' ORDER BY seqno;
CREATE INDEX textarrayidx ON array_index_op_test USING gin (t);
explain (nodes off, costs off)
SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAA72908}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAA72908}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t && '{AAAAAAAA72908}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAAAA646}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t && '{AAAAAAAAAA646}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAA72908,AAAAAAAAAA646}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t && '{AAAAAAAA72908,AAAAAAAAAA646}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t <@ '{AAAAAAAA72908,AAAAAAAAAAAAAAAAAAA17075,AA88409,AAAAAAAAAAAAAAAAAA36842,AAAAAAA48038,AAAAAAAAAAAAAA10611}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t = '{AAAAAAAAAA646,A87088}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t = '{}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t @> '{}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t && '{}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t <@ '{}' ORDER BY seqno;
-- And try it with a multicolumn GIN index
DROP INDEX intarrayidx, textarrayidx;
CREATE INDEX botharrayidx ON array_index_op_test USING gin (i, t);
SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i && '{32}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAA80240}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t && '{AAAAAAA80240}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i @> '{32}' AND t && '{AAAAAAA80240}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE i && '{32}' AND t @> '{AAAAAAA80240}' ORDER BY seqno;
SELECT * FROM array_index_op_test WHERE t = '{}' ORDER BY seqno;
SELECT * FROM array_op_test WHERE i = '{NULL}' ORDER BY seqno;
SELECT * FROM array_op_test WHERE i <@ '{NULL}' ORDER BY seqno;
RESET enable_seqscan;
RESET enable_indexscan;
RESET enable_bitmapscan;
--
-- Try a GIN index with a lot of items with same key. (GIN creates a posting
-- tree when there are enough duplicates)
--
CREATE TABLE array_gin_test (a int[]);
INSERT INTO array_gin_test SELECT ARRAY[1, g%5, g] FROM generate_series(1, 10000) g;
CREATE INDEX array_gin_test_idx ON array_gin_test USING gin (a);
SELECT COUNT(*) FROM array_gin_test WHERE a @> '{2}';
DROP TABLE array_gin_test;
--
-- Test GIN index's reloptions
--
CREATE INDEX gin_relopts_test ON array_index_op_test USING gin (i)
WITH (FASTUPDATE=on, GIN_PENDING_LIST_LIMIT=128);
\d+ gin_relopts_test
--
-- HASH
--
CREATE INDEX hash_i4_index ON hash_i4_heap USING hash (random int4_ops);
CREATE INDEX hash_name_index ON hash_name_heap USING hash (random name_ops);
CREATE INDEX hash_txt_index ON hash_txt_heap USING hash (random text_ops);
CREATE INDEX hash_f8_index ON hash_f8_heap USING hash (random float8_ops);
CREATE UNLOGGED TABLE unlogged_hash_table (id int4);
CREATE INDEX unlogged_hash_index ON unlogged_hash_table USING hash (id int4_ops);
DROP TABLE unlogged_hash_table;
-- CREATE INDEX hash_ovfl_index ON hash_ovfl_heap USING hash (x int4_ops);
--
-- Test functional index
--
CREATE TABLE func_index_heap (f1 text, f2 text);
CREATE UNIQUE INDEX func_index_index on func_index_heap (textcat(f1,f2));
INSERT INTO func_index_heap VALUES('ABC','DEF');
INSERT INTO func_index_heap VALUES('AB','CDEFG');
INSERT INTO func_index_heap VALUES('QWE','RTY');
-- this should fail because of unique index:
INSERT INTO func_index_heap VALUES('ABCD', 'EF');
-- but this shouldn't:
INSERT INTO func_index_heap VALUES('QWERTY');
--
-- Same test, expressional index
--
DROP TABLE func_index_heap;
CREATE TABLE func_index_heap (f1 text, f2 text);
CREATE UNIQUE INDEX func_index_index on func_index_heap ((f1 || f2) text_ops);
INSERT INTO func_index_heap VALUES('ABC','DEF');
INSERT INTO func_index_heap VALUES('AB','CDEFG');
INSERT INTO func_index_heap VALUES('QWE','RTY');
-- this should fail because of unique index:
INSERT INTO func_index_heap VALUES('ABCD', 'EF');
-- but this shouldn't:
INSERT INTO func_index_heap VALUES('QWERTY');
--
-- Also try building functional, expressional, and partial indexes on
-- tables that already contain data.
--
create unique index hash_f8_index_1 on hash_f8_heap(abs(random));
create unique index hash_f8_index_2 on hash_f8_heap((seqno + 1), random);
create unique index hash_f8_index_3 on hash_f8_heap(random) where seqno > 1000;
--
-- Try some concurrent index builds
--
-- Unfortunately this only tests about half the code paths because there are
-- no concurrent updates happening to the table at the same time.
CREATE TABLE concur_heap (f1 text, f2 text);
-- empty table
CREATE INDEX CONCURRENTLY concur_index1 ON concur_heap(f2,f1);
CREATE INDEX CONCURRENTLY IF NOT EXISTS concur_index1 ON concur_heap(f2,f1);
INSERT INTO concur_heap VALUES ('a','b');
INSERT INTO concur_heap VALUES ('b','b');
-- unique index
CREATE UNIQUE INDEX CONCURRENTLY concur_index2 ON concur_heap(f1);
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS concur_index2 ON concur_heap(f1);
-- check if constraint is set up properly to be enforced
INSERT INTO concur_heap VALUES ('b','x');
-- check if constraint is enforced properly at build time
CREATE UNIQUE INDEX CONCURRENTLY concur_index3 ON concur_heap(f2);
-- test that expression indexes and partial indexes work concurrently
CREATE INDEX CONCURRENTLY concur_index4 on concur_heap(f2) WHERE f1='a';
CREATE INDEX CONCURRENTLY concur_index5 on concur_heap(f2) WHERE f1='x';
-- here we also check that you can default the index name
CREATE INDEX CONCURRENTLY on concur_heap((f2||f1));
-- You can't do a concurrent index build in a transaction
BEGIN;
CREATE INDEX CONCURRENTLY concur_index7 ON concur_heap(f1);
COMMIT;
-- But you can do a regular index build in a transaction
BEGIN;
CREATE INDEX std_index on concur_heap(f2);
COMMIT;
-- Failed builds are left invalid by VACUUM FULL, fixed by REINDEX
VACUUM FULL concur_heap;
REINDEX TABLE concur_heap;
DELETE FROM concur_heap WHERE f1 = 'b';
VACUUM FULL concur_heap;
\d concur_heap
REINDEX TABLE concur_heap;
\d concur_heap
--
-- Try some concurrent index drops
--
DROP INDEX CONCURRENTLY "concur_index2"; -- works
DROP INDEX CONCURRENTLY IF EXISTS "concur_index2"; -- notice
-- failures
DROP INDEX CONCURRENTLY "concur_index2", "concur_index3";
BEGIN;
DROP INDEX CONCURRENTLY "concur_index5";
ROLLBACK;
-- successes
DROP INDEX CONCURRENTLY IF EXISTS "concur_index3";
DROP INDEX CONCURRENTLY "concur_index4";
DROP INDEX CONCURRENTLY "concur_index5";
DROP INDEX CONCURRENTLY "concur_index1";
DROP INDEX CONCURRENTLY "concur_heap_expr_idx";
\d concur_heap
DROP TABLE concur_heap;
--
-- Test ADD CONSTRAINT USING INDEX
--
CREATE TABLE cwi_test( a int , b varchar(10), c char);
-- add some data so that all tests have something to work with.
INSERT INTO cwi_test VALUES(1, 2), (3, 4), (5, 6);
CREATE UNIQUE INDEX cwi_uniq_idx ON cwi_test(a , b);
ALTER TABLE cwi_test ADD primary key USING INDEX cwi_uniq_idx;
\d cwi_test
\d cwi_uniq_idx
CREATE UNIQUE INDEX cwi_uniq2_idx ON cwi_test(b , a);
ALTER TABLE cwi_test DROP CONSTRAINT cwi_uniq_idx,
ADD CONSTRAINT cwi_replaced_pkey PRIMARY KEY
USING INDEX cwi_uniq2_idx;
\d cwi_test
\d cwi_replaced_pkey
DROP INDEX cwi_replaced_pkey; -- Should fail; a constraint depends on it
DROP TABLE cwi_test;
--
-- Tests for IS NULL/IS NOT NULL with b-tree indexes
--
SELECT unique1, unique2 INTO onek_with_null FROM onek;
INSERT INTO onek_with_null (unique1,unique2) VALUES (NULL, -1), (NULL, NULL);
CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2,unique1);
SET enable_seqscan = OFF;
SET enable_indexscan = ON;
SET enable_bitmapscan = ON;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL;
DROP INDEX onek_nulltest;
CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2 desc,unique1);
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL;
DROP INDEX onek_nulltest;
CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2 desc nulls last,unique1);
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL;
DROP INDEX onek_nulltest;
CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2 nulls first,unique1);
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL;
SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL;
DROP INDEX onek_nulltest;
-- Check initial-positioning logic too
CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2);
SET enable_seqscan = OFF;
SET enable_indexscan = ON;
SET enable_bitmapscan = OFF;
SELECT unique1, unique2 FROM onek_with_null
ORDER BY unique2 LIMIT 2;
SELECT unique1, unique2 FROM onek_with_null WHERE unique2 >= -1
ORDER BY unique2 LIMIT 2;
SELECT unique1, unique2 FROM onek_with_null WHERE unique2 >= 0
ORDER BY unique2 LIMIT 2;
SELECT unique1, unique2 FROM onek_with_null
ORDER BY unique2 DESC LIMIT 2;
SELECT unique1, unique2 FROM onek_with_null WHERE unique2 >= -1
ORDER BY unique2 DESC LIMIT 2;
SELECT unique1, unique2 FROM onek_with_null WHERE unique2 < 999
ORDER BY unique2 DESC LIMIT 2;
RESET enable_seqscan;
RESET enable_indexscan;
RESET enable_bitmapscan;
DROP TABLE onek_with_null;
--
-- Check bitmap index path planning
--
EXPLAIN (NODES OFF, COSTS OFF)
SELECT * FROM tenk1
WHERE thousand = 42 AND (tenthous = 1 OR tenthous = 3 OR tenthous = 42);
SELECT * FROM tenk1
WHERE thousand = 42 AND (tenthous = 1 OR tenthous = 3 OR tenthous = 42);
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM tenk1
WHERE hundred = 42 AND (thousand = 42 OR thousand = 99);
SELECT count(*) FROM tenk1
WHERE hundred = 42 AND (thousand = 42 OR thousand = 99);
--
-- Check behavior with duplicate index column contents
--
CREATE TABLE dupindexcols AS
SELECT unique1 as id, stringu2::text as f1 FROM tenk1;
CREATE INDEX dupindexcols_i ON dupindexcols (f1, id, f1 text_pattern_ops);
ANALYZE dupindexcols;
EXPLAIN (NODES OFF, COSTS OFF)
SELECT count(*) FROM dupindexcols
WHERE f1 BETWEEN 'WA' AND 'ZZZ' and id < 1000 and f1 ~<~ 'YX';
SELECT count(*) FROM dupindexcols
WHERE f1 BETWEEN 'WA' AND 'ZZZ' and id < 1000 and f1 ~<~ 'YX';
--
-- Check ordering of =ANY indexqual results (bug in 9.2.0)
--
vacuum tenk1; -- ensure we get consistent plans here
explain (costs off)
SELECT unique1 FROM tenk1
WHERE unique1 IN (1,42,7)
ORDER BY unique1;
SELECT unique1 FROM tenk1
WHERE unique1 IN (1,42,7)
ORDER BY unique1;
explain (costs off)
SELECT thousand, tenthous FROM tenk1
WHERE thousand < 2 AND tenthous IN (1001,3000)
ORDER BY thousand;
SELECT thousand, tenthous FROM tenk1
WHERE thousand < 2 AND tenthous IN (1001,3000)
ORDER BY thousand;
SET enable_indexonlyscan = OFF;
explain (costs off)
SELECT thousand, tenthous FROM tenk1
WHERE thousand < 2 AND tenthous IN (1001,3000)
ORDER BY thousand;
SELECT thousand, tenthous FROM tenk1
WHERE thousand < 2 AND tenthous IN (1001,3000)
ORDER BY thousand;
RESET enable_indexscan;
--
-- Check elimination of constant-NULL subexpressions
--
explain (costs off)
select * from tenk1 where (thousand, tenthous) in ((1,1001), (null,null));
--
-- REINDEX (VERBOSE)
--
CREATE TABLE reindex_verbose(id integer primary key);
\set VERBOSITY terse
REINDEX (VERBOSE) TABLE reindex_verbose;
DROP TABLE reindex_verbose;
--
-- REINDEX SCHEMA
--
REINDEX SCHEMA schema_to_reindex; -- failure, schema does not exist
CREATE SCHEMA schema_to_reindex;
SET search_path = 'schema_to_reindex';
CREATE TABLE table1(col1 SERIAL PRIMARY KEY);
INSERT INTO table1 SELECT generate_series(1,400);
CREATE TABLE table2(col1 SERIAL PRIMARY KEY, col2 TEXT NOT NULL);
INSERT INTO table2 SELECT generate_series(1,400), 'abc';
CREATE INDEX ON table2(col2);
CREATE MATERIALIZED VIEW matview AS SELECT col1 FROM table2;
CREATE INDEX ON matview(col1);
CREATE VIEW view AS SELECT col2 FROM table2;
CREATE TABLE reindex_before AS
SELECT oid, relname, relfilenode, relkind, reltoastrelid
FROM pg_class
where relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'schema_to_reindex');
INSERT INTO reindex_before
SELECT oid, 'pg_toast_TABLE', relfilenode, relkind, reltoastrelid
FROM pg_class WHERE oid IN
(SELECT reltoastrelid FROM reindex_before WHERE reltoastrelid > 0);
INSERT INTO reindex_before
SELECT oid, 'pg_toast_TABLE_index', relfilenode, relkind, reltoastrelid
FROM pg_class where oid in
(select indexrelid from pg_index where indrelid in
(select reltoastrelid from reindex_before where reltoastrelid > 0));
REINDEX SCHEMA schema_to_reindex;
CREATE TABLE reindex_after AS SELECT oid, relname, relfilenode, relkind
FROM pg_class
where relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'schema_to_reindex');
SELECT b.relname,
b.relkind,
CASE WHEN a.relfilenode = b.relfilenode THEN 'relfilenode is unchanged'
ELSE 'relfilenode has changed' END
FROM reindex_before b JOIN pg_class a ON b.oid = a.oid
ORDER BY 1;
REINDEX SCHEMA schema_to_reindex;
BEGIN;
REINDEX SCHEMA schema_to_reindex; -- failure, cannot run in a transaction
END;
-- Failure for unauthorized user
CREATE ROLE regression_reindexuser NOLOGIN;
SET SESSION ROLE regression_reindexuser;
REINDEX SCHEMA schema_to_reindex;
-- Clean up
RESET ROLE;
DROP ROLE regression_reindexuser;
SET client_min_messages TO 'warning';
DROP SCHEMA schema_to_reindex CASCADE;
RESET client_min_messages;
| techdragon/Postgres-XL | src/test/regress/sql/create_index.sql | SQL | mpl-2.0 | 37,747 |
<!DOCTYPE HTML>
<html dir="rtl">
<title>Testcase, bug 428810</title>
<style type="text/css">
html, body { margin: 0; padding: 0; }
</style>
<div style="height: 10px">
<div style="float: right; height: 20px; width: 100px"></div>
</div>
<div style="margin-right: 40px; width: 70px; display: list-item;">
<div style="float: right; height: 20px; width: 60px"></div>
<div> </div>
</div>
| Yukarumya/Yukarum-Redfoxes | layout/reftests/bugs/428810-3b-rtl.html | HTML | mpl-2.0 | 418 |
function f() {
var i32 = new Int32Array(1);
var f32 = new Float32Array(i32.buffer);
for (var i = 0; i < 3; i++) {
var a0 = +1;
var a3 = +4;
i32[0] = a0;
var b0 = f32[0];
i32[0] = a3;
var b3 = f32[0];
assertEq(b0 != b3, true);
}
}
f();
| cstipkovic/spidermonkey-research | js/src/jit-test/tests/ion/bug1279898.js | JavaScript | mpl-2.0 | 312 |
/*
* Copyright (C) 2008 Tommi Maekitalo
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef ZIM_FILEHEADER_H
#define ZIM_FILEHEADER_H
#include <zim/zim.h>
#include <zim/endian.h>
#include <zim/uuid.h>
#include <iosfwd>
#include <limits>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
#undef max
#endif
namespace zim
{
class Fileheader
{
public:
static const size_type zimMagic;
static const size_type zimVersion;
static const size_type size;
private:
Uuid uuid;
size_type articleCount;
offset_type titleIdxPos;
offset_type urlPtrPos;
offset_type mimeListPos;
size_type blobCount;
offset_type blobPtrPos;
size_type mainPage;
size_type layoutPage;
offset_type checksumPos;
public:
Fileheader()
: articleCount(0),
titleIdxPos(0),
urlPtrPos(0),
blobCount(0),
blobPtrPos(0),
mainPage(std::numeric_limits<size_type>::max()),
layoutPage(std::numeric_limits<size_type>::max()),
checksumPos(std::numeric_limits<offset_type>::max())
{}
const Uuid& getUuid() const { return uuid; }
void setUuid(const Uuid& uuid_) { uuid = uuid_; }
size_type getArticleCount() const { return articleCount; }
void setArticleCount(size_type s) { articleCount = s; }
offset_type getTitleIdxPos() const { return titleIdxPos; }
void setTitleIdxPos(offset_type p) { titleIdxPos = p; }
offset_type getUrlPtrPos() const { return urlPtrPos; }
void setUrlPtrPos(offset_type p) { urlPtrPos = p; }
offset_type getMimeListPos() const { return mimeListPos; }
void setMimeListPos(offset_type p) { mimeListPos = p; }
size_type getClusterCount() const { return blobCount; }
void setClusterCount(size_type s) { blobCount = s; }
offset_type getClusterPtrPos() const { return blobPtrPos; }
void setClusterPtrPos(offset_type p) { blobPtrPos = p; }
bool hasMainPage() const { return mainPage != std::numeric_limits<size_type>::max(); }
size_type getMainPage() const { return mainPage; }
void setMainPage(size_type s) { mainPage = s; }
bool hasLayoutPage() const { return layoutPage != std::numeric_limits<size_type>::max(); }
size_type getLayoutPage() const { return layoutPage; }
void setLayoutPage(size_type s) { layoutPage = s; }
bool hasChecksum() const { return getMimeListPos() >= 80; }
offset_type getChecksumPos() const { return hasChecksum() ? checksumPos : 0; }
void setChecksumPos(offset_type p) { checksumPos = p; }
};
std::ostream& operator<< (std::ostream& out, const Fileheader& fh);
std::istream& operator>> (std::istream& in, Fileheader& fh);
}
#endif // ZIM_FILEHEADER_H
| carmenfdezb/Zimpedia | sailfish/libs/zimlib/include/zim/fileheader.h | C | mpl-2.0 | 3,814 |
<?php
// include base peer class
require_once 'classes/model/om/BaseSequencesPeer.php';
// include object class
include_once 'classes/model/Sequences.php';
/**
* Skeleton subclass for performing query and update operations on the 'SEQUENCES' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package classes.model
*/
class SequencesPeer extends BaseSequencesPeer {
} // SequencesPeer
| colosa/processmaker | workflow/engine/classes/model/SequencesPeer.php | PHP | agpl-3.0 | 568 |
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package metricsdebug_test
import (
"errors"
"time"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
basetesting "github.com/juju/juju/api/base/testing"
"github.com/juju/juju/api/metricsdebug"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/params"
jujutesting "github.com/juju/juju/juju/testing"
"github.com/juju/juju/state"
"github.com/juju/juju/testing"
"github.com/juju/juju/testing/factory"
)
type metricsdebugSuiteMock struct {
testing.BaseSuite
manager *metricsdebug.Client
}
var _ = gc.Suite(&metricsdebugSuiteMock{})
func (s *metricsdebugSuiteMock) TestGetMetrics(c *gc.C) {
var called bool
now := time.Now()
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "GetMetrics")
result := response.(*params.MetricResults)
result.Results = []params.EntityMetrics{{
Metrics: []params.MetricResult{{
Key: "pings",
Value: "5",
Time: now,
}},
Error: nil,
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics("unit-wordpress/0")
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
c.Assert(metrics, gc.HasLen, 1)
c.Assert(metrics[0].Key, gc.Equals, "pings")
c.Assert(metrics[0].Value, gc.Equals, "5")
c.Assert(metrics[0].Time, gc.Equals, now)
}
func (s *metricsdebugSuiteMock) TestGetMetricsFails(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "GetMetrics")
result := response.(*params.MetricResults)
result.Results = []params.EntityMetrics{{
Error: common.ServerError(errors.New("an error")),
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics("unit-wordpress/0")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(metrics, gc.IsNil)
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestGetMetricsFacadeCallError(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, result interface{},
) error {
called = true
return errors.New("an error")
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics("unit-wordpress/0")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(metrics, gc.IsNil)
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestGetMetricsForModel(c *gc.C) {
var called bool
now := time.Now()
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
requestParam, response interface{},
) error {
c.Assert(request, gc.Equals, "GetMetrics")
entities := requestParam.(params.Entities)
c.Assert(entities, gc.DeepEquals, params.Entities{Entities: []params.Entity{}})
result := response.(*params.MetricResults)
result.Results = []params.EntityMetrics{{
Metrics: []params.MetricResult{{
Key: "pings",
Value: "5",
Time: now,
}},
Error: nil,
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics()
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
c.Assert(metrics, gc.HasLen, 1)
c.Assert(metrics[0].Key, gc.Equals, "pings")
c.Assert(metrics[0].Value, gc.Equals, "5")
c.Assert(metrics[0].Time, gc.Equals, now)
}
func (s *metricsdebugSuiteMock) TestGetMetricsForModelFails(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
requestParam, response interface{},
) error {
called = true
return errors.New("an error")
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics()
c.Assert(called, jc.IsTrue)
c.Assert(metrics, gc.IsNil)
c.Assert(err, gc.ErrorMatches, "an error")
}
func (s *metricsdebugSuiteMock) TestSetMeterStatus(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "SetMeterStatus")
c.Assert(a, gc.DeepEquals, params.MeterStatusParams{
Statuses: []params.MeterStatusParam{{
Tag: "unit-metered/0",
Code: "RED",
Info: "test"},
},
})
result := response.(*params.ErrorResults)
result.Results = []params.ErrorResult{{
Error: nil,
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
err := client.SetMeterStatus("unit-metered/0", "RED", "test")
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestSetMeterStatusAPIServerError(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "SetMeterStatus")
c.Assert(a, gc.DeepEquals, params.MeterStatusParams{
Statuses: []params.MeterStatusParam{{
Tag: "unit-metered/0",
Code: "RED",
Info: "test"},
},
})
result := response.(*params.ErrorResults)
result.Results = []params.ErrorResult{{
Error: common.ServerError(errors.New("an error")),
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
err := client.SetMeterStatus("unit-metered/0", "RED", "test")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestSetMeterStatusFacadeCallError(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
called = true
return errors.New("an error")
})
client := metricsdebug.NewClient(apiCaller)
err := client.SetMeterStatus("unit-metered/0", "RED", "test")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(called, jc.IsTrue)
}
type metricsdebugSuite struct {
jujutesting.JujuConnSuite
manager *metricsdebug.Client
}
var _ = gc.Suite(&metricsdebugSuite{})
func (s *metricsdebugSuite) SetUpTest(c *gc.C) {
s.JujuConnSuite.SetUpTest(c)
s.manager = metricsdebug.NewClient(s.APIState)
c.Assert(s.manager, gc.NotNil)
}
func assertSameMetric(c *gc.C, a params.MetricResult, b *state.MetricBatch) {
c.Assert(a.Key, gc.Equals, b.Metrics()[0].Key)
c.Assert(a.Value, gc.Equals, b.Metrics()[0].Value)
c.Assert(a.Time, jc.TimeBetween(b.Metrics()[0].Time, b.Metrics()[0].Time))
}
func (s *metricsdebugSuite) TestFeatureGetMetrics(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Charm: meteredCharm})
unit := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metric := s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit})
metrics, err := s.manager.GetMetrics("unit-metered/0")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics, gc.HasLen, 1)
assertSameMetric(c, metrics[0], metric)
}
func (s *metricsdebugSuite) TestFeatureGetMultipleMetrics(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{
Charm: meteredCharm,
})
unit0 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
unit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metricUnit0 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit0,
})
metricUnit1 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit1,
})
metrics0, err := s.manager.GetMetrics("unit-metered/0")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics0, gc.HasLen, 1)
assertSameMetric(c, metrics0[0], metricUnit0)
metrics1, err := s.manager.GetMetrics("unit-metered/1")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics1, gc.HasLen, 1)
assertSameMetric(c, metrics1[0], metricUnit1)
metrics2, err := s.manager.GetMetrics("unit-metered/0", "unit-metered/1")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics2, gc.HasLen, 2)
}
func (s *metricsdebugSuite) TestFeatureGetMetricsForModel(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{
Charm: meteredCharm,
})
unit0 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
unit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metricUnit0 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit0,
})
metricUnit1 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit1,
})
metrics, err := s.manager.GetMetrics()
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics, gc.HasLen, 2)
assertSameMetric(c, metrics[0], metricUnit0)
assertSameMetric(c, metrics[1], metricUnit1)
}
func (s *metricsdebugSuite) TestFeatureGetMultipleMetricsWithService(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{
Charm: meteredCharm,
})
unit0 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
unit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metricUnit0 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit0,
})
metricUnit1 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit1,
})
metrics, err := s.manager.GetMetrics("application-metered")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics, gc.HasLen, 2)
assertSameMetric(c, metrics[0], metricUnit0)
assertSameMetric(c, metrics[1], metricUnit1)
}
func (s *metricsdebugSuite) TestSetMeterStatus(c *gc.C) {
testCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
testService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Charm: testCharm})
testUnit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: testService, SetCharmURL: true})
testUnit2 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: testService, SetCharmURL: true})
csCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "cs:quantal/metered-1"})
csService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Name: "cs-service", Charm: csCharm})
csUnit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: csService, SetCharmURL: true})
tests := []struct {
about string
tag string
code string
info string
err string
assert func(*gc.C)
}{{
about: "set service meter status",
tag: testService.Tag().String(),
code: "RED",
info: "test",
assert: func(c *gc.C) {
ms1, err := testUnit1.GetMeterStatus()
c.Assert(err, jc.ErrorIsNil)
c.Assert(ms1, gc.DeepEquals, state.MeterStatus{
Code: state.MeterRed,
Info: "test",
})
ms2, err := testUnit2.GetMeterStatus()
c.Assert(err, jc.ErrorIsNil)
c.Assert(ms2, gc.DeepEquals, state.MeterStatus{
Code: state.MeterRed,
Info: "test",
})
},
}, {
about: "set unit meter status",
tag: testUnit1.Tag().String(),
code: "AMBER",
info: "test",
assert: func(c *gc.C) {
ms1, err := testUnit1.GetMeterStatus()
c.Assert(err, jc.ErrorIsNil)
c.Assert(ms1, gc.DeepEquals, state.MeterStatus{
Code: state.MeterAmber,
Info: "test",
})
},
}, {
about: "not a local charm - service",
tag: csService.Tag().String(),
code: "AMBER",
info: "test",
err: "not a local charm",
}, {
about: "not a local charm - unit",
tag: csUnit1.Tag().String(),
code: "AMBER",
info: "test",
err: "not a local charm",
}, {
about: "invalid meter status",
tag: testUnit1.Tag().String(),
code: "WRONG",
info: "test",
err: "invalid meter status \"NOT AVAILABLE\"",
}, {
about: "not such service",
tag: "application-missing",
code: "AMBER",
info: "test",
err: "application \"missing\" not found",
},
}
for i, test := range tests {
c.Logf("running test %d: %v", i, test.about)
err := s.manager.SetMeterStatus(test.tag, test.code, test.info)
if test.err == "" {
c.Assert(err, jc.ErrorIsNil)
test.assert(c)
} else {
c.Assert(err, gc.ErrorMatches, test.err)
}
}
}
| waigani/juju | api/metricsdebug/client_test.go | GO | agpl-3.0 | 12,837 |
#Manufacturing Settings
Manufacturing Settings can be found at:
`Manufacturing > Setup > Manufacturing Settings`
<img class="screenshot" alt="Manufacturing Settings" src="{{docs_base_url}}/assets/img/manufacturing/manufacturing-settings-1.png">
####Disable Capacity Planning and Time Tracking
As per Capacity Planning feature, when Production Order is created for an item, for each Operation, Time Log is created. Based on actual Operation Time, Time Logs is updated. This also provides total Operations Cost against Production Order.
If you don't track actual operations time, and want to disable creation of Time Log based on Operations, you should check "Disable Capacity Planning and Time Tracking" in the Manufacturing Settings.
####Allow Overtime
In the Workstation master, actual working hours are defined (say 101m to 6pm). As per the Capacity Planning, Time Logs are created against Workstation, for tracking actual operations hour. It also considers working hours of a Workstation when scheduling job (via Time Log).
<img class="screenshot" alt="Manufacturing Settings" src="{{docs_base_url}}/assets/img/articles/manufacturing-settings-2.png">
As per the standard validation, if Operation cannot be completed within working hours of Workstation, then user is asked to divide an Operation into multiple and smaller Operations. However, if `Allow Overtime` field is checked, while creating Time Logs for Operation, working hours of Workstation will not be validated. In this case, Time Logs for Operation will be created beyond working hours of Workstation as well.
####Allow Production on Holidays
Holiday of a company can be recorded in the [Holiday List]({{docs_base_url}}/user/manual/en/human-resources/) master. While scheduling production job on workstation, system doesn't consider a day listed in the Holiday list. If you want production job to be scheduled on holidays as well, `Allow Production on Holidays` field should be checked.
<img class="screenshot" alt="Manufacturing Settings" src="{{docs_base_url}}/assets/img/articles/manufacturing-settings-3.png">
####Over Production Allowance Percentage
In Production Order, `Qty to Manufacture` is set. When creating Manufacture entry against Production Order, it validates `Qty to Manufature` entered in production order, and doesn't allow creating Manufacture Entry for more qty and Production Order qty. If you want to create Manufacture Qty than Production Order qty, mention Over Production Allowance Qty in the Manufacturing Settings. Based on Allowance Percentage mentioned, you will be able to create Manufacture Entry for more Qty than in Production Order.
####Back-flush Raw Materials Based On
When creating Manufacture Entry, raw-material items are back-flush based on BOM of production item. If you want raw-material items to be back-flushed based on Material Transfer entry made against that Production Order instead, then you should set Back-flush Raw Materials Based On "Material Transferred for Manufacture".
<img class="screenshot" alt="Manufacturing Settings" src="{{docs_base_url}}/assets/img/articles/manufacturing-settings-4.png">
####Capacity Planning For (Days)
Define no. of days for which system will do production job allocation in advance.
####Time Between Operations (in mins)
Time gap between two production operations.
####Default Work In Progress Warehouse
This Warehouse will be auto-updated in the Work In Progress Warehouse field of Production Order.
####Default Finished Goods Warehouse
This Warehouse will be auto-updated in the Work In Progress Warehouse field of Production Order. | mahabuber/erpnext | erpnext/docs/user/manual/en/manufacturing/setup/manufacturing-settings.md | Markdown | agpl-3.0 | 3,611 |
<?php
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Access to Memory (AtoM) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>.
*/
class QubitGenerator extends sfPropelAdminGenerator
{
protected function setScaffoldingClassName($className)
{
$this->singularName = strtolower(substr($className, 0, 1)).substr($className, 1);
$this->pluralName = $this->singularName.'s';
$this->className = $className;
$this->peerClassName = $className.'Peer';
}
public function getColumnEditTag($column, $params = array())
{
if ($column->isComponent())
{
$moduleName = $this->getModuleName();
$componentName = $column->getName();
if (false !== $pos = strpos($componentName, '/'))
{
$moduleName = substr($componentName, 0, $pos);
$componentName = substr($componentName, $pos + 1);
}
return "get_component('$moduleName', '$componentName', array('type' => 'edit', '{$this->getSingularName()}' => \${$this->getSingularName()}))";
}
return parent::getColumnEditTag($column, $params);
}
}
| kyfr59/atom-cg35 | lib/propel/generator/QubitGenerator.class.php | PHP | agpl-3.0 | 1,699 |
#include "FOX_OSG_MDIView.h"
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
//________Message_Type_________ ___ID___ ________Message_Handler________
FXMAPFUNC(SEL_CHORE, FOX_OSG_MDIView::ID_CHORE, FOX_OSG_MDIView::OnIdle)
};
FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))
FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
FXIcon *ic, FXPopup *pup, FXuint opt,
FXint x, FXint y, FXint w, FXint h)
: FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
// A visual to drag OpenGL in double-buffered mode; note the glvisual is
// shared between all windows which need the same depths and numbers of buffers
// Thus, while the first visual may take some time to initialize, each subsequent
// window can be created very quickly; we need to determine grpaphics hardware
// characteristics only once.
FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);
m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );
osgViewer::Viewer *viewer = new osgViewer::Viewer;
viewer->getCamera()->setGraphicsContext(m_gwFox);
viewer->getCamera()->setViewport(0,0,w,h);
// set the draw and read buffers up for a double buffered window with rendering going to back buffer
viewer->getCamera()->setDrawBuffer(GL_BACK);
viewer->getCamera()->setReadBuffer(GL_BACK);
viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
// FOX example does not catch the close of the graphics window, so
// don't allow the default escape sets to done to be active.
viewer->setKeyEventSetsDone(0);
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFile("cow.osgt");
if (!loadedModel)
{
return ;
}
// add the stats handler
viewer->addEventHandler(new osgViewer::StatsHandler);
viewer->setSceneData(loadedModel.get());
viewer->setCameraManipulator(new osgGA::TrackballManipulator);
SetViewer(viewer);
getApp()->addChore(this,ID_CHORE);
}
FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
getApp()->removeChore(this,ID_CHORE);
}
long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
m_osgViewer->frame();
getApp()->addChore(this, ID_CHORE);
return 1;
}
void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
m_osgViewer = viewer;
}
| openscenegraph/osg | examples/osgviewerFOX/FOX_OSG_MDIView.cpp | C++ | lgpl-2.1 | 2,636 |
/*
* bytestream.cpp - base class for bytestreams
* Copyright (C) 2003 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "bytestream.h"
#include <QByteArray>
// CS_NAMESPACE_BEGIN
//! \class ByteStream bytestream.h
//! \brief Base class for "bytestreams"
//!
//! This class provides a basic framework for a "bytestream", here defined
//! as a bi-directional, asynchronous pipe of data. It can be used to create
//! several different kinds of bytestream-applications, such as a console or
//! TCP connection, or something more abstract like a security layer or tunnel,
//! all with the same interface. The provided functions make creating such
//! classes simpler. ByteStream is a pure-virtual class, so you do not use it
//! on its own, but instead through a subclass such as \a BSocket.
//!
//! The signals connectionClosed(), delayedCloseFinished(), readyRead(),
//! bytesWritten(), and error() serve the exact same function as those from
//! <A HREF="http://doc.trolltech.com/3.1/qsocket.html">QSocket</A>.
//!
//! The simplest way to create a ByteStream is to reimplement isOpen(), close(),
//! and tryWrite(). Call appendRead() whenever you want to make data available for
//! reading. ByteStream will take care of the buffers with regards to the caller,
//! and will call tryWrite() when the write buffer gains data. It will be your
//! job to call tryWrite() whenever it is acceptable to write more data to
//! the underlying system.
//!
//! If you need more advanced control, reimplement read(), write(), bytesAvailable(),
//! and/or bytesToWrite() as necessary.
//!
//! Use appendRead(), appendWrite(), takeRead(), and takeWrite() to modify the
//! buffers. If you have more advanced requirements, the buffers can be accessed
//! directly with readBuf() and writeBuf().
//!
//! Also available are the static convenience functions ByteStream::appendArray()
//! and ByteStream::takeArray(), which make dealing with byte queues very easy.
class ByteStream::Private
{
public:
Private() {}
QByteArray readBuf, writeBuf;
int errorCode;
QString errorText;
};
//!
//! Constructs a ByteStream object with parent \a parent.
ByteStream::ByteStream(QObject *parent)
:QIODevice(parent)
{
d = new Private;
}
//!
//! Destroys the object and frees allocated resources.
ByteStream::~ByteStream()
{
delete d;
}
//!
//! Writes array \a a to the stream.
qint64 ByteStream::writeData(const char *data, qint64 maxSize)
{
if(!isOpen())
return - 1;
bool doWrite = bytesToWrite() == 0 ? true: false;
d->writeBuf.append(data, maxSize);
if(doWrite)
tryWrite();
return maxSize;
}
//!
//! Reads bytes \a bytes of data from the stream and returns them as an array. If \a bytes is 0, then
//! \a read will return all available data.
qint64 ByteStream::readData(char *data, qint64 maxSize)
{
maxSize = maxSize > d->readBuf.size()? d->readBuf.size() : maxSize;
memcpy(data, d->readBuf.constData(), maxSize);
d->readBuf.remove(0, maxSize);
return maxSize;
}
//!
//! Returns the number of bytes available for reading.
qint64 ByteStream::bytesAvailable() const
{
return QIODevice::bytesAvailable() + d->readBuf.size();
}
//!
//! Returns the number of bytes that are waiting to be written.
qint64 ByteStream::bytesToWrite() const
{
return d->writeBuf.size();
}
//!
//! Clears the read buffer.
void ByteStream::clearReadBuffer()
{
d->readBuf.resize(0);
}
//!
//! Clears the write buffer.
void ByteStream::clearWriteBuffer()
{
d->writeBuf.resize(0);
}
//!
//! Appends \a block to the end of the read buffer.
void ByteStream::appendRead(const QByteArray &block)
{
d->readBuf += block;
}
//!
//! Appends \a block to the end of the write buffer.
void ByteStream::appendWrite(const QByteArray &block)
{
d->writeBuf += block;
}
//!
//! Returns \a size bytes from the start of the read buffer.
//! If \a size is 0, then all available data will be returned.
//! If \a del is TRUE, then the bytes are also removed.
QByteArray ByteStream::takeRead(int size, bool del)
{
return takeArray(d->readBuf, size, del);
}
//!
//! Returns \a size bytes from the start of the write buffer.
//! If \a size is 0, then all available data will be returned.
//! If \a del is TRUE, then the bytes are also removed.
QByteArray ByteStream::takeWrite(int size, bool del)
{
return takeArray(d->writeBuf, size, del);
}
//!
//! Returns a reference to the read buffer.
QByteArray & ByteStream::readBuf()
{
return d->readBuf;
}
//!
//! Returns a reference to the write buffer.
QByteArray & ByteStream::writeBuf()
{
return d->writeBuf;
}
//!
//! Attempts to try and write some bytes from the write buffer, and returns the number
//! successfully written or -1 on error. The default implementation returns -1.
int ByteStream::tryWrite()
{
return -1;
}
//!
//! Returns \a size bytes from the start of the array pointed to by \a from.
//! If \a size is 0, then all available data will be returned.
//! If \a del is TRUE, then the bytes are also removed.
QByteArray ByteStream::takeArray(QByteArray &from, int size, bool del)
{
QByteArray result;
if(size == 0) {
result = from;
if(del)
from.resize(0);
}
else {
result = from.left(size);
if (del) {
from.remove(0, size);
}
}
return result;
}
//!
//! Returns last error code.
int ByteStream::errorCode() const
{
return d->errorCode;
}
//!
//! Returns last error string corresponding to last error code.
QString &ByteStream::errorText() const
{
return d->errorText;
}
//!
//! Sets last error with \a code and \a text and emit it
void ByteStream::setError(int code, const QString &text)
{
d->errorCode = code;
d->errorText = text;
if (code != ErrOk) {
emit error(code);
}
}
void connectionClosed();
void delayedCloseFinished();
void readyRead();
void bytesWritten(qint64);
void error(int);
//! \fn void ByteStream::connectionClosed()
//! This signal is emitted when the remote end of the stream closes.
//! \fn void ByteStream::delayedCloseFinished()
//! This signal is emitted when all pending data has been written to the stream
//! after an attempt to close.
//! \fn void ByteStream::readyRead()
//! This signal is emitted when data is available to be read.
//! \fn void ByteStream::error(int code)
//! This signal is emitted when an error occurs in the stream. The reason for
//! error is indicated by \a code.
// CS_NAMESPACE_END
| harishnavnit/iris | src/irisnet/noncore/cutestuff/bytestream.cpp | C++ | lgpl-2.1 | 7,044 |
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#pragma once
// MOOSE includes
#include "MooseTypes.h"
#include "RestartableData.h"
// Forward declarations
class PostprocessorData;
class SubProblem;
class InputParameters;
class MooseObject;
class MooseApp;
class MooseMesh;
/**
* A class for creating restricted objects
* \see BlockRestartable BoundaryRestartable
*/
class Restartable
{
public:
/**
* Class constructor
*
* @param moose_object The MooseObject that this interface is being implemented on.
* @param system_name The name of the MOOSE system. ie "Kernel", "BCs", etc. Should roughly
* correspond to the section in the input file so errors are easy to understand.
*
* This method will forward the thread id if it exists in the moose_object parameters. Delegates
* to the "MooseApp &" constructor.
*/
Restartable(const MooseObject * moose_object, const std::string & system_name);
/**
* Class constructor
*
* Similar to the other class constructor but also accepts an individual thread ID. If this
* method is used, no thread ID in the parameters object is used. Delegates to the "MooseApp &"
* constructor.
*/
Restartable(const MooseObject * moose_object, const std::string & system_name, THREAD_ID tid);
/**
* This class constructor is used for non-Moose-based objects like interfaces. A name for the
* storage as well as a system name must be passed in along with the thread ID explicitly.
*/
Restartable(MooseApp & moose_app,
const std::string & name,
const std::string & system_name,
THREAD_ID tid);
/**
* Emtpy destructor
*/
virtual ~Restartable() = default;
protected:
/**
* Declare a piece of data as "restartable".
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
*/
template <typename T>
T & declareRestartableData(const std::string & data_name);
/**
* Declare a piece of data as "restartable" and initialize it.
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param init_value The initial value of the data
*/
template <typename T>
T & declareRestartableData(const std::string & data_name, const T & init_value);
/**
* Declare a piece of data as "restartable".
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param context Context pointer that will be passed to the load and store functions
*/
template <typename T>
T & declareRestartableDataWithContext(const std::string & data_name, void * context);
/**
* Declare a piece of data as "restartable".
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param prefix The prefix to prepend to the data_name, to retrieve data from another object.
* @param context Context pointer that will be passed to the load and store functions
*/
template <typename T>
T & declareRestartableDataWithPrefixOverrideAndContext(const std::string & data_name,
const std::string & prefix,
void * context);
/**
* Declare a piece of data as "restartable" and initialize it.
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param init_value The initial value of the data
* @param context Context pointer that will be passed to the load and store functions
*/
template <typename T>
T & declareRestartableDataWithContext(const std::string & data_name,
const T & init_value,
void * context);
/**
* Declare a piece of data as "recoverable".
* This means that in the event of a recovery this piece of data
* will be restored back to its previous value.
*
* Note - this data will NOT be restored on _Restart_!
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
*/
template <typename T>
T & declareRecoverableData(const std::string & data_name);
/**
* Declare a piece of data as "restartable" and initialize it.
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* Note - this data will NOT be restored on _Restart_!
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param init_value The initial value of the data
*/
template <typename T>
T & declareRecoverableData(const std::string & data_name, const T & init_value);
/**
* Declare a piece of data as "restartable".
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param object_name A supplied name for the object that is declaring this data.
*/
template <typename T>
T & declareRestartableDataWithObjectName(const std::string & data_name,
const std::string & object_name);
/**
* Declare a piece of data as "restartable".
* This means that in the event of a restart this piece of data
* will be restored back to its previous value.
*
* NOTE: This returns a _reference_! Make sure you store it in a _reference_!
*
* @param data_name The name of the data (usually just use the same name as the member variable)
* @param object_name A supplied name for the object that is declaring this data.
* @param context Context pointer that will be passed to the load and store functions
*/
template <typename T>
T & declareRestartableDataWithObjectNameWithContext(const std::string & data_name,
const std::string & object_name,
void * context);
protected:
/// Reference to the application
MooseApp & _restartable_app;
/// The system name this object is in
const std::string _restartable_system_name;
/// The thread ID for this object
const THREAD_ID _restartable_tid;
/// Flag for toggling read only status (see ReporterData)
bool _restartable_read_only;
private:
/// The name of the object
std::string _restartable_name;
/// Helper function for actually registering the restartable data.
RestartableDataValue & registerRestartableDataOnApp(const std::string & name,
std::unique_ptr<RestartableDataValue> data,
THREAD_ID tid);
/// Helper function for actually registering the restartable data.
void registerRestartableNameWithFilterOnApp(const std::string & name,
Moose::RESTARTABLE_FILTER filter);
};
template <typename T>
T &
Restartable::declareRestartableData(const std::string & data_name)
{
return declareRestartableDataWithContext<T>(data_name, nullptr);
}
template <typename T>
T &
Restartable::declareRestartableData(const std::string & data_name, const T & init_value)
{
return declareRestartableDataWithContext<T>(data_name, init_value, nullptr);
}
template <typename T>
T &
Restartable::declareRestartableDataWithContext(const std::string & data_name, void * context)
{
std::string full_name = _restartable_system_name + "/" + _restartable_name + "/" + data_name;
auto data_ptr = libmesh_make_unique<RestartableData<T>>(full_name, context);
// See comment in overloaded version of this function with "init_value"
auto & restartable_data_ref = static_cast<RestartableData<T> &>(
registerRestartableDataOnApp(full_name, std::move(data_ptr), _restartable_tid));
return restartable_data_ref.set();
}
template <typename T>
T &
Restartable::declareRestartableDataWithContext(const std::string & data_name,
const T & init_value,
void * context)
{
std::string full_name = _restartable_system_name + "/" + _restartable_name + "/" + data_name;
// Here we will create the RestartableData even though we may not use this instance.
// If it's already in use, the App will return a reference to the existing instance and we'll
// return that one instead. We might refactor this to have the app create the RestartableData
// at a later date.
auto data_ptr = libmesh_make_unique<RestartableData<T>>(full_name, context);
auto & restartable_data_ref = static_cast<RestartableData<T> &>(
registerRestartableDataOnApp(full_name, std::move(data_ptr), _restartable_tid));
restartable_data_ref.set() = init_value;
return restartable_data_ref.set();
}
template <typename T>
T &
Restartable::declareRestartableDataWithObjectName(const std::string & data_name,
const std::string & object_name)
{
return declareRestartableDataWithObjectNameWithContext<T>(data_name, object_name, nullptr);
}
template <typename T>
T &
Restartable::declareRestartableDataWithObjectNameWithContext(const std::string & data_name,
const std::string & object_name,
void * context)
{
std::string old_name = _restartable_name;
_restartable_name = object_name;
T & value = declareRestartableDataWithContext<T>(data_name, context);
_restartable_name = old_name;
return value;
}
template <typename T>
T &
Restartable::declareRecoverableData(const std::string & data_name)
{
std::string full_name = _restartable_system_name + "/" + _restartable_name + "/" + data_name;
registerRestartableNameWithFilterOnApp(full_name, Moose::RESTARTABLE_FILTER::RECOVERABLE);
return declareRestartableDataWithContext<T>(data_name, nullptr);
}
template <typename T>
T &
Restartable::declareRecoverableData(const std::string & data_name, const T & init_value)
{
std::string full_name = _restartable_system_name + "/" + _restartable_name + "/" + data_name;
registerRestartableNameWithFilterOnApp(full_name, Moose::RESTARTABLE_FILTER::RECOVERABLE);
return declareRestartableDataWithContext<T>(data_name, init_value, nullptr);
}
| harterj/moose | framework/include/restart/Restartable.h | C | lgpl-2.1 | 12,018 |
/**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This is the base module should be extended by all plugins for the
* [document previewer]{@link module:alfresco/preview/AlfDocumentPreview}. This provides basic
* height calculations for the preview (which can be overridden if required). The
* [display]{@link module:alfresco/preview/AlfDocumentPreviewPlugin#display} function should be
* overridden to implement the preview behaviour.
*
* @module alfresco/preview/AlfDocumentPreviewPlugin
* @extends external:dijit/_WidgetBase
* @mixes module:alfresco/layout/HeightMixin
* @mixes module:alfresco/core/ResizeMixin
* @mixes module:alfresco/core/Core
* @author Dave Draper
*/
define(["dojo/_base/declare",
"dijit/_WidgetBase",
"alfresco/layout/HeightMixin",
"alfresco/core/ResizeMixin",
"alfresco/core/Core",
"dojo/_base/lang"],
function(declare, _Widget, HeightMixin, ResizeMixin, Core, lang) {
return declare([_Widget, HeightMixin, ResizeMixin, Core], {
/**
*
* @instance
* @param {object[]} args
*/
constructor: function alfresco_preview_AlfDocumentPreviewPlugin__constructor(args) {
lang.mixin(args);
// Ensure that an initial attributes instance variable is defined to avoid
// errors when the [setAttributes]{@link module:alfresco/preview/AlfDocumentPreviewPlugin#setAttributes}
// function is called.
if (!this.attributes)
{
this.attributes = {};
}
},
/**
* Updates the attributes with the values from the [AlfDocumentPreview]{@link module:alfresco/preview/AlfDocumentPreview}
* instance for the current Node being previewed.
*
* @instance
* @param {object[]} attributes The attributes object to mixin into the default settings.
*/
setAttributes: function alfresco_preview_AlfDocumentPreviewPlugin__setAttributes(attributes) {
var clonedAttributes = lang.clone(attributes);
lang.mixin(this.attributes, clonedAttributes);
},
/**
* If [display]{@link module:alfresco/preview/AlfDocumentPreview#display} returns HTML to be
* added as the preview then this function will be called after it has been added to the document.
* This provides an opportunity for the plugin to perform any additional initialisation.
*
* @instance
* @since 1.0.51
*/
onMarkupAdded: function alfresco_preview_AlfDocumentPreviewPlugin__onMarkupAdded() {
// By default don't report anything.
},
/**
* Tests if the plugin can be used in the users browser.
*
* @instance
* @overridable
*/
report: function alfresco_preview_AlfDocumentPreviewPlugin__report() {
// By default don't report anything.
},
/**
* By default does nothing.
*
* @instance
* @overridable
*/
display: function alfresco_preview_AlfDocumentPreviewPlugin__display() {
this.alfSetupResizeSubscriptions(this.onRecalculatePreviewLayout, this);
},
/**
* Handler for window resize event. This will call [_setPreviewerElementHeight]
* {@link module:alfresco/preview/AlfDocumentPreviewPlugin#_setPreviewerElementHeight}
* but can be extended or overridden to perform additional preview layout actions.
*
* @instance
*/
onRecalculatePreviewLayout: function alfresco_preview_AlfDocumentPreviewPlugin__onRecalculatePreviewLayout() {
this._setPreviewerElementHeight();
},
/**
* Sets the height of the previewer element using functions provided by calling the
* [setHeight function]{@link module:alfresco/layout/HeightMixin#setHeight} provided by the
* [HeightMixin]{@link module:alfresco/layout/HeightMixin} module.
*
* @instance
*/
_setPreviewerElementHeight: function alfresco_preview_AlfDocumentPreviewPlugin___setPreviewerElementHeight() {
var pE = this.previewManager.getPreviewerElement();
this.heightMode = this.previewManager.heightMode;
this.heightAdjustment = this.previewManager.heightAdjustment || 0;
this.setHeight(pE);
}
});
}); | davidcognite/Aikau | aikau/src/main/resources/alfresco/preview/AlfDocumentPreviewPlugin.js | JavaScript | lgpl-3.0 | 5,033 |
/*! \file include/kernel/ext2.h
* \brief ext2 file system header.
* \author
* Filippo Brogi
* \note Copyright (©) 2003
* Filippo Brogi
* \date Last update:
* 2003-09-30 by Andrea Righi
* init_ext2() now returns a boolean value.\n
*/
#ifndef EXT2_H
#define EXT2_H
//#include <const.h>
typedef unsigned short word;
typedef unsigned int dword;
typedef unsigned char byte;
//typedef int bool;
#define TRUE 1
#define FALSE 0
/** \ingroup FileSystem
* \defgroup FSext2 Ext2
* The ext2 file system.
* @{
*/
// dimensione blocco del disco
#define SIZE_SEC 512
// numero magico ext2
#define N_EXT2_NUMERO_MAGICO 0xEF53 //for normal versione of ext2
#define P_EXT2_NUMERO_MAGICO 0xEF51 //for versions of ext2fs prior to 0.2b.
// costanti errore ext2
#define EXT2_ERRORS_CONTINUE 1 // continua come se niente fosse
#define EXT2_ERRORS_RO 2 // rimonta a sola lettura
#define EXT3_ERRORS_PANIC 3 // causa un panic nel kernel
// valori EXT2_OS
#define EXT2_OS_LINUX 0
#define EXT2_OS_HURD 1
#define EXT2_MASIX 2
#define EXT2_FREEBSD 3
#define EXT2_OS_LITES4 4
// livelli di revisione
#define EXT2_GOOD_OLD_REV 0 //original format
#define EXT2DYNAMIC_REV 1 // formato v2 con dimensione inode dinamica
// valori EXT2_*_INO
#define EXT2_BAD_INO 0x01 //blocco inode danneggiato
#define EXT2_ROOT_INO 0x02 // inode directory radice
#define EXT2_ACL_IDX_INO 0x03 //ACL index inode
#define EXT2_ACL_DARA_INO 0x04 //ACL data inode
#define EXT2_BOOTLOADER INO 0x05 //boot loader inode
#define EXT2_UNDEL_DIR_INO 0x06 // inode directory ripristinata
// valori EXT2_S_I
// ------------ file format ------------
#define MODE_MASK 0xF000 // format mask
#define MODE_SOCK 0xC000 // socket
#define MODE_LINK 0xA000 // symbolic link
#define MODE_FILE 0x8000 // regular file
#define MODE_BDEV 0x6000 // block device
#define MODE_DIR 0x4000 // directory
#define MODE_CDEV 0x2000 // character device
#define MODE_FIFO 0x1000 // fifo
// ------------ access rights ------------
#define EXT2_S_ISUID 0x0800 // SUID
#define EXT2_S_ISGID 0x0400 // SGID
#define EXT2_S_ISVTX 0x0200 // sticky bit
#define EXT2_S_IRWXU 0x01C0 // user access rights mask
#define EXT2_S_IRUSR 0x0100 // read
#define EXT2_S_IWUSR 0x0080 // write
#define EXT2_S_IXUSR 0x0040 // execute
#define EXT2_S_IRWXG 0x0038 // group access right mask
#define EXT2_S_IRGRP 0x0020 // read
#define EXT2_S_IWGRP 0x0010 // write
#define EXT2_S_IXGRP 0x0008 // execute
#define EXT2_S_IRWXO 0x0007 // others access rights mask
#define EXT2_S_IROTH 0x0004 // read
#define EXT2_S_IWOTH 0x0003 // write
#define EXT2_S_IXOTH 0x0001 // execute
// valori EXT2_FT
//------------ tipo file ---------------
#define EXT2_FT_UNKNOWN 0
#define EXT2_FT_REG_FILE 1
#define EXT2_FT_DIR 2
#define EXT2_FT_CHRDEV 3
#define EXT2_FT_BLKDEV 4
#define EXT2_FT_FIFO 5
#define EXT2_FT_SOCK 6
#define EXT2_FT_SYMLINK 7
#define EXT2_FT_MAX 8
#define DIM_SUPER_BLOCK 1024
#define START_SUPER_BLOCK 1024
struct super_block
{
dword s_inodes_count; //numero totale inode liberi e utilizzati
dword s_blocks_count; //numero totale di blocchi liberi e utilizzati
dword s_r_blocks_count; //numero totale di blocchi riservati al super user
dword s_free_blocks_count; //numero di blocchi liberi compresi quelli riservati
dword s_free_inodes_count; //numero totale di inode liberi
dword s_first_data_block; /* id of the block containing the structure of the sb
generally this value '0 for file systems with a size of
block greater than 1KB. The super block always starts with 1024 bytes of disk
which generally coincides with the first byte of the third sector */
dword s_log_block_size; /* la dimensione del blocco si calcola come il numero
di bit che si ottiene shiftando 1024. Questo valore puo` essere solo positivo;
block size = 1024 << s_log_block_size; */
dword s_log_frag_size; /* la dimensione del frammento si calcola come il numero
di bit da shiftare dal valore 1024
if (positive)
fragment size = 1024 << s_log_frag_size;
else
fragment size = 1024 >> -s_log_frag_size; */
dword s_blocks_per_group; //numero totale blocchi del gruppo
dword s_frags_per_group; //numero totale frammenti per gruppo
dword s_inodes_per_group; //numero totale di inodes per gruppo
dword s_mtime; // data ultimo montaggio del file system
dword s_wtime; // ultimo accesso in scrittura al file system
word s_mnt_count; // numero di volte che e' stato montato dall'ultima volta
// in cui e' stata completamente verificata
word s_max_mnt_count; //numero massimo di volte che un file system puo` essere
//montato prima che sia eseguito un check completo
word s_magic; // numero magico
word s_state; /* state of the mounted file system. When the fs and 'was mounted
state and 'place to EXT2_ERROR_FS. When the file system is not 'yet
value can be mounted EXT2_VALID_FS or EXT2_ERROR_FS if not 'status
completely disassembled */
word s_errors; //cosa fare in caso di errore
word s_minor_rev_level; //
dword s_lastcheck; // ultimo check del file system
dword s_checkinterval; // massimo tempo di intervallamento tra due check
dword s_creator_os; // identificativo so creatore del file system
dword s_rev_level; // valore livello di revisione
word s_def_resuid; // id user default per i blocchi riservati
word s_def_resgid; // id group default per i blocchi riservati
dword s_first_ino; /* indice del primo inode utilizzabile per file standard.
nella revisione non dinamica del file system questo valore e' fissato a 11. Con
quella dinamica e' possibile modificare questo valore*/
word s_inode_size; /* dimensione della struttura inode. Nel caso non
dinamico questo valore e' 128*/
word s_block_group_nr; // numero dei gruppi nel superblocco
dword s_feature_compact; //
dword s_feature_incompact; //
dword s_feature_ro_compact; //
byte s_uuid[16]; // id del volume 128 bit
word s_volume_name; //
byte s_last_mounted[8]; // path directory dove e' stato montato il fs
dword s_algo_bitmap; /* usato da algoritmi di compressione per determinare i
metodi utilizzati */
byte s_reserved[886]; // riservati al sistema operativo
};
/*
The descriptor of group and 'an array of structure group_desc each
which defines a group of blocks, giving the location of the table
inodes, bitmap blocks, and inodes, and other information yet. In
General and 'allocated consecutively to the disk block containing the super
block
*/
struct group_descriptor{
dword bg_block_bitmap; // id primo blocco della bitmap dei blocchi del gruppo
dword bg_inode_bitmap; // id primo blocco della bitmap degli inode
dword bg_inode_table; //primo blocco della tabella degli inode
word bg_free_blocks_count; //numero totale di blocchi liberi
word bg_free_inodes_count; // numero totale inode liberi
word bg_used_dirs_count; // numero inode allocati nelle directory
word bg_pad; // valore usato per il padding della struttura
dword bg_reserved[3]; // valori riservati per future implementazioni
};
/*
The "block bitmap" and 'normally located on the first block or second block
if you have the backup of the superblock. Its official location
you can get by reading the descriptor in bg_block_bitmap group. Each
bit represents the current state of the block, 1 being used, while 0 indicates
Free / available.
L ' "inode bitmap" works the same way the bitmap of the blocks. This
bitmap is determined from bg_inode_bitmap. When you create the table
all the reserved inode inode are marked as used.
The inode table and 'used to keep track of each file: lease
size, type, access rights are all stored in the inode. Names
Files are not stored here, in the inode table all files are
referenced with their inode number. The inode table and 'referenced
by bg_inode_table and contains s_inodes_per_group
*/
struct i_node{
word i_mode; // formato del file e diritti di accesso
word i_uid; // user id associato col file
dword i_size; // dimensione in byte del file
dword i_atime; // ultimo accesso in secondi a partire dal 1/1/1970
dword i_ctime; // data di creazione in secondi dal 1/1/1970
dword i_mtime; // data ultima modifica in secondi dal 1/1/1970
dword i_dtime; // data della cancellazione del file a partire dal 1/1/1970
word i_gid; // gruppo che ha accesso al file
word i_links_count; // numero dei riferimenti all'inode
dword i_blocks; /* amount of blocks associated with the file your currently
used and those that will be used in case of an increase in
file size. Qusto In case the size of blocks and '512 kB and
that specified in the superblock */
dword i_flags; // comportamento del file system quando accede ai dati
dword i_osd1; // valore dipendendente dal SO
dword i_block[15]; /* array used to identify the disk blocks in
which is stored the file. The first 12 elements are used to direct
directly the data blocks associated with files, the 13-th and 'used to
addressing indiriretto single on 14-th for indirect addressing
double and 15 th for the triple */
dword i_generation; // indica versione del file (usato da NFS)
dword i_file_acl; //numero el blocco contenenti gli attributi estesi
dword i_dir_acl; // indica la high size del file
dword i_faddr; // locazione dell'ultimo frammento del file
/* inode osd2 structure Linux */
byte l_i_frag; //numero frammento
byte l_i_fsize; // dimensione frammento
word reserved1; // reserved
word l_i_uid_high; // bit dell'user id
word l_i_gid_high; // bit del group id
dword reserved2; // reserved
};
/*
Directories are stored as files and can be identified by looking at the
value of the inode i_mode and verifying that it is equal to
EXT2_S_IFDIR. The root and 'always stored in second position
of the inode table. Each subdirectory you can get watching
contents of the directory tree root.
*/
struct dir_ff{
dword inode; // numero entry del file. 0 indica che non e' usata
word rec_len; // move to the next element in the current directory
byte name_len; // many characters contain the name
byte file_type; // tipo del file
char name[1]; // nome dell'entry
};
/*
Use the standard format of linked lists for directories may
become very slow when the number of files starts to grow. `So
incrementre for performance using a hash index that helps
enhance the performance of research
*/
/*
Index structure
The root of the tree index is located in block 0 of the file. Space for
second tree level indicated (for file system with 4KB block)
is located in blocks 1 to 511. The blocks of the directory tree are leaf
located from block 512, so the tail of the file directory
looks like a standard directory tree and can be processed with EXT2
ext2_readdir. For directory tree with less than 90K file there is a hole running from
block 1 to block 511, so an empty directory has just two blocks, although
its size is approximately 2 mega list of the directory tree.
*/
// --- Prototypes ----------------------------------------------------- //
//bool init_ext2(void);
//char *pwd_ext2();
//void ls_ext2(void);
//void cd_ext2(char *param);
//void cat_ext2(char *stringa);
/** @} */ // end of FSext2
#endif
| animotron/animos | oldtree/kernel/phantom/unix/fs_ext2.h | C | lgpl-3.0 | 11,755 |
/* ****************************************************************************
* eID Middleware Project.
* Copyright (C) 2012 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, see
* http://www.gnu.org/licenses/.
**************************************************************************** */
#ifndef plugin_getreadercount_h
#define plugin_getreadercount_h
#include "common.h"
CK_RV GetTheReaderCount(int* nrofCardReaders, int cardsInserted);
#endif
| yiminyangguang520/eid-mw | installers/quickinstaller/NSIS_Plugins/beidread/getreadercount.h | C | lgpl-3.0 | 1,006 |
/**
*
* Phantom OS multithreading library.
*
* Copyright (C) 2009-2010 Dmitry Zavalishin, [email protected]
*
* Run queues handling.
*
* Licensed under CPL 1.0, see LICENSE file.
*
**/
#include <queue.h>
#include <hal.h>
#include <malloc.h>
#include "thread_private.h"
phantom_thread_t * t_dequeue_highest_prio(queue_head_t *queue)
{
phantom_thread_t *nextt = 0;
#if 0
queue_remove_first(queue, nextt, phantom_thread_t *, chain);
#else
phantom_thread_t *it;
unsigned int max = 0;
queue_iterate(queue, it, phantom_thread_t *, chain)
{
assert(it != GET_CURRENT_THREAD());
if (it->priority > max)
{
max = it->priority;
nextt = it;
}
}
if(nextt != 0)
queue_remove(queue, nextt, phantom_thread_t *, chain);
#endif
return nextt;
}
void
t_queue_check(queue_head_t *queue, phantom_thread_t *test)
{
phantom_thread_t *next;
queue_iterate(queue, next, phantom_thread_t *, chain)
assert(next != test);
}
| kandeshvari/phantomuserland | phantom/threads/t_queues.c | C | lgpl-3.0 | 1,082 |
"""
Default settings for the ``mezzanine.generic`` app. Each of these can be
overridden in your project's settings module, just like regular
Django settings. The ``editable`` argument for each controls whether
the setting is editable via Django's admin.
Thought should be given to how a setting is actually used before
making it editable, as it may be inappropriate - for example settings
that are only read during startup shouldn't be editable, since changing
them would require an application reload.
"""
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
generic_comments = getattr(settings, "COMMENTS_APP", "") == "mezzanine.generic"
if generic_comments:
register_setting(
name="COMMENTS_ACCOUNT_REQUIRED",
label=_("Accounts required for commenting"),
description=_("If ``True``, users must log in to comment."),
editable=True,
default=False,
)
register_setting(
name="COMMENTS_DISQUS_SHORTNAME",
label=_("Disqus shortname"),
description=_("Shortname for the http://disqus.com comments "
"service."),
editable=True,
default="",
)
register_setting(
name="COMMENTS_DISQUS_API_PUBLIC_KEY",
label=_("Disqus public key"),
description=_("Public key for http://disqus.com developer API"),
editable=True,
default="",
)
register_setting(
name="COMMENTS_DISQUS_API_SECRET_KEY",
label=_("Disqus secret key"),
description=_("Secret key for http://disqus.com developer API"),
editable=True,
default="",
)
register_setting(
name="COMMENTS_DEFAULT_APPROVED",
label=_("Auto-approve comments"),
description=_("If ``True``, built-in comments are approved by "
"default."),
editable=True,
default=True,
)
register_setting(
name="COMMENT_FILTER",
description=_("Dotted path to the function to call on a comment's "
"value before it is rendered to the template."),
editable=False,
default=None,
)
register_setting(
name="COMMENTS_NOTIFICATION_EMAILS",
label=_("Comment notification email addresses"),
description=_("A comma separated list of email addresses that "
"will receive an email notification each time a "
"new comment is posted on the site."),
editable=True,
default="",
)
register_setting(
name="COMMENTS_NUM_LATEST",
label=_("Admin comments"),
description=_("Number of latest comments shown in the admin "
"dashboard."),
editable=True,
default=5,
)
register_setting(
name="COMMENTS_UNAPPROVED_VISIBLE",
label=_("Show unapproved comments"),
description=_("If ``True``, comments that have ``is_public`` "
"unchecked will still be displayed, but replaced with a "
"``waiting to be approved`` message."),
editable=True,
default=True,
)
register_setting(
name="COMMENTS_REMOVED_VISIBLE",
label=_("Show removed comments"),
description=_("If ``True``, comments that have ``removed`` "
"checked will still be displayed, but replaced "
"with a ``removed`` message."),
editable=True,
default=True,
)
register_setting(
name="COMMENTS_USE_RATINGS",
description=_("If ``True``, comments can be rated."),
editable=False,
default=True,
)
register_setting(
name="RATINGS_ACCOUNT_REQUIRED",
label=_("Accounts required for rating"),
description=_("If ``True``, users must log in to rate content "
"such as blog posts and comments."),
editable=True,
default=False,
)
register_setting(
name="RATINGS_RANGE",
description=_("A sequence of integers that are valid ratings."),
editable=False,
default=range(getattr(settings, "RATINGS_MIN", 1),
getattr(settings, "RATINGS_MAX", 5) + 1),
)
| orlenko/bccf | src/mezzanine/generic/defaults.py | Python | unlicense | 4,223 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using Mono.Cecil;
namespace MFMetaDataProcessor.Console
{
internal static class MainClass
{
private sealed class MetaDataProcessor
{
private readonly IDictionary<String, String> _loadHints =
new Dictionary<String, String>(StringComparer.Ordinal);
private AssemblyDefinition _assemblyDefinition;
private Boolean _isBigEndianOutput;
public void Parse(String fileName)
{
try
{
_assemblyDefinition = AssemblyDefinition.ReadAssembly(fileName,
new ReaderParameters { AssemblyResolver = new LoadHintsAssemblyResolver(_loadHints)});
}
catch (Exception)
{
System.Console.Error.WriteLine(
"Unable to parse input assembly file '{0}' - check if path and file exists.", fileName);
Environment.Exit(1);
}
}
public void Compile(String fileName)
{
try
{
var builder = new TinyAssemblyBuilder(_assemblyDefinition);
using (var stream = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite))
using (var writer = new BinaryWriter(stream))
{
builder.Write(GetBinaryWriter(writer));
}
using (var writer = XmlWriter.Create(Path.ChangeExtension(fileName, "pdbx")))
{
builder.Write(writer);
}
}
catch (Exception)
{
System.Console.Error.WriteLine(
"Unable to compile output assembly file '{0}' - check parse command results.", fileName);
throw;
}
}
private TinyBinaryWriter GetBinaryWriter(BinaryWriter writer)
{
return (_isBigEndianOutput
? TinyBinaryWriter.CreateBigEndianBinaryWriter(writer)
: TinyBinaryWriter.CreateLittleEndianBinaryWriter(writer));
}
public void SetEndian(String endian)
{
if (endian == "le")
{
_isBigEndianOutput = false;
}
else if (endian == "be")
{
_isBigEndianOutput = true;
}
else
{
System.Console.Error.WriteLine("Unknown endian '{0}' specified ignored.", endian);
}
}
public void AddLoadHint(
String assemblyName,
String assemblyFileName)
{
_loadHints[assemblyName] = assemblyFileName;
}
}
public static void Main(String[] args)
{
var md = new MetaDataProcessor();
for (var i = 0; i < args.Length; ++i)
{
var arg = args[i].ToLower(CultureInfo.InvariantCulture);
if (arg == "-parse" && i + 1 < args.Length)
{
md.Parse(args[++i]);
}
else if (arg == "-compile" && i + 1 < args.Length)
{
md.Compile(args[++i]);
}
else if (arg == "-endian" && i + 1 < args.Length)
{
md.SetEndian(args[++i]);
}
else if (arg == "-loadhints" && i + 2 < args.Length)
{
md.AddLoadHint(args[i + 1], args[i + 2]);
i += 2;
}
else
{
// TODO: More args and commands
System.Console.Error.WriteLine("Unknown command line option '{0}' ignored.", arg);
}
}
}
}
}
| venkatarajasekhar/Monkey.Robotics | Source/Xamarin Studio Microframework Add-in/MFMetaDataProcessor/MFMetaDataProcessor.Console/Program.cs | C# | apache-2.0 | 4,148 |
/*
* Copyright (c) 2015-2017, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated 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.
*/
/*!*****************************************************************************
* @file SPICC32XXDMA.h
*
* @brief SPI driver implementation for a CC32XX SPI controller using the
* micro DMA controller.
*
* The SPI header file should be included in an application as follows:
* @code
* #include <ti/drivers/SPI.h>
* #include <ti/drivers/spi/SPICC32XXDMA.h>
* @endcode
*
* Refer to @ref SPI.h for a complete description of APIs & example of use.
*
* This SPI driver implementation is designed to operate on a CC32XX SPI
* controller using a micro DMA controller.
*
* ## Frame Formats #
* This SPI controller supports 4 phase & polarity formats. Refer to the device
* specific data sheets & technical reference manuals for specifics on each
* format.
*
* ## SPI Chip Select #
* This SPI controller supports a hardware chip select pin. Refer to the
* device's user manual on how this hardware chip select pin behaves in regards
* to the SPI frame format.
*
* <table>
* <tr>
* <th>Chip select type</th>
* <th>SPI_MASTER mode</th>
* <th>SPI_SLAVE mode</th>
* </tr>
* <tr>
* <td>Hardware chip select</td>
* <td>No action is needed by the application to select the peripheral.</td>
* <td>See the device documentation on it's chip select requirements.</td>
* </tr>
* <tr>
* <td>Software chip select</td>
* <td>The application is responsible to ensure that correct SPI slave is
* selected before performing a SPI_transfer().</td>
* <td>See the device documentation on it's chip select requirements.</td>
* </tr>
* </table>
*
* ## SPI data frames #
* SPI data frames can be any size from 4-bits to 32-bits. The SPI data
* frame size is set in ::SPI_Params.dataSize passed to SPI_open.
* The SPICC32XXDMA driver implementation makes assumptions on the element
* size of the ::SPI_Transaction txBuf and rxBuf arrays, based on the data
* frame size. If the data frame size is less than or equal to 8 bits,
* txBuf and rxBuf are assumed to be arrays of 8-bit uint8_t elements.
* If the data frame size is greater than 8 bits, but less than or equal
* to 16 bits, txBuf and rxBuf are assumed to be arrays of 16-bit uint16_t
* elements. Otherwise, txBuf and rxBuf are assumed to point to 32-bit
* uint32_t elements.
*
* data frame size | buffer element size |
* -------------- | ------------------- |
* 4-8 bits | uint8_t |
* 9-16 bits | uint16_t |
* 17-32 bits | uint32_t |
*
* Data buffers in transactions (rxBuf & txBuf) must be address aligned
* according to the data frame size. For example, if data frame is 9-bit
* (driver assumes buffers are uint16_t) rxBuf & txBuf must be aligned
* on a 16-bit address boundary, if data frame is 20-bit (driver assumes
* buffers are uint32_t) rxBuf & txBuf must be aligned on a 32-bit address
* boundary.
*
* ## DMA Interrupts #
* This driver is designed to operate with the micro DMA. The micro DMA
* generates an interrupt on the perpheral's interrupt vector. This
* implementation automatically installs a DMA aware hardware ISR to service
* the assigned micro DMA channels.
*
* ## DMA accessible memory #
* As this driver uses uDMA to transfer data/from data buffers, it is the
* responsibility of the application to ensure that these buffers reside in
* memory that is accessible by the DMA.
*
* ## Scratch Buffers #
* A uint32_t scratch buffer is used to allow SPI_transfers where txBuf or
* rxBuf are NULL. Rather than requiring txBuf or rxBuf to have a dummy buffer
* of size of the transfer count, a single DMA accessible uint32_t scratch
* buffer is used. When rxBuf is NULL, the uDMA will transfer all the SPI data
* receives into the scratch buffer as a "bit-bucket". When txBuf is NULL, the
* scratch buffer is initialized to defaultTxBufValue so the uDMA will send
* some known value. Each SPI driver instance must have its own scratch buffer.
*
* ## Polling SPI transfers #
* When used in blocking mode small SPI transfers are can be done by polling
* the peripheral & sending data frame-by-frame. This will not block the task
* which requested the transfer, but instead immediately perform the transfer
* & return. The minDmaTransferSize field in the hardware attributes is
* the threshold; if the transaction count is below the threshold a polling
* transfer is performed; otherwise a DMA transfer is done. This is intended
* to reduce the overhead of setting up a DMA transfer to only send a few
* data frames. Keep in mind that during polling transfers the current task
* is still being executed; there is no context switch to another task.
*******************************************************************************
*/
#ifndef ti_drivers_spi_SPICC32XXDMA__include
#define ti_drivers_spi_SPICC32XXDMA__include
#ifdef __cplusplus
extern "C" {
#endif
#include <ti/drivers/dpl/HwiP.h>
#include <ti/drivers/dpl/SemaphoreP.h>
#include <ti/drivers/Power.h>
#include <ti/drivers/SPI.h>
#include <ti/drivers/dma/UDMACC32XX.h>
/**
* @addtogroup SPI_STATUS
* SPICC32XXDMA_STATUS_* macros are command codes only defined in the
* SPICC32XXDMA.h driver implementation and need to:
* @code
* #include <ti/drivers/sdspi/SPICC32XXDMA.h>
* @endcode
* @{
*/
/* Add SPICC32XXDMA_STATUS_* macros here */
/** @}*/
/**
* @addtogroup SPI_CMD
* SPICC32XXDMA_CMD_* macros are command codes only defined in the
* SPICC32XXDMA.h driver implementation and need to:
* @code
* #include <ti/drivers/sdspi/SPICC32XXDMA.h>
* @endcode
* @{
*/
/* Add SPICC32XXDMA_CMD_* macros here */
/** @}*/
/*
* Macros defining possible SPI signal pin mux options
*
* The lower 8 bits of the macro refer to the pin, offset by 1, to match
* driverlib pin defines. For example, SPICC32XXDMA_PIN_05_CLK & 0xff = 4,
* which equals PIN_05 in driverlib pin.h. By matching the PIN_xx defines in
* driverlib pin.h, we can pass the pin directly to the driverlib functions.
* The upper 8 bits of the macro correspond to the pin mux confg mode
* value for the pin to operate in the SPI mode.
*
* PIN_62 is special for the SDSPI driver when using an SD Boosterpack,
* as PIN_62 doesn't have an assigned SPI function yet the SD Boosterpack
* has it tied to the CS signal.
*/
#define SPICC32XXDMA_PIN_05_CLK 0x0704 /*!< PIN 5 is used for SPI CLK */
#define SPICC32XXDMA_PIN_06_MISO 0x0705 /*!< PIN 6 is used for MISO */
#define SPICC32XXDMA_PIN_07_MOSI 0x0706 /*!< PIN 7 is used for MOSI */
#define SPICC32XXDMA_PIN_08_CS 0x0707 /*!< PIN 8 is used for CS */
#define SPICC32XXDMA_PIN_45_CLK 0x072C /*!< PIN 45 is used for SPI CLK */
#define SPICC32XXDMA_PIN_50_CS 0x0931 /*!< PIN 50 is used for CS */
#define SPICC32XXDMA_PIN_52_MOSI 0x0833 /*!< PIN 52 is used for MOSI */
#define SPICC32XXDMA_PIN_53_MISO 0x0734 /*!< PIN 53 is used for MISO */
/*!
* @brief Indicates a pin is not to be configured by the SPICC32XXDMA driver.
*/
#define SPICC32XXDMA_PIN_NO_CONFIG 0xFFFF
/* SPI function table pointer */
extern const SPI_FxnTable SPICC32XXDMA_fxnTable;
/*!
* @brief SPICC32XXDMA Hardware attributes
*
* These fields, with the exception of intPriority,
* are used by driverlib APIs and therefore must be populated by
* driverlib macro definitions. For CCWare these definitions are found in:
* - driverlib/prcm.h
* - driverlib/spi.h
* - driverlib/udma.h
* - inc/hw_memmap.h
* - inc/hw_ints.h
*
* intPriority is the SPI peripheral's interrupt priority, as defined by the
* underlying OS. It is passed unmodified to the underlying OS's interrupt
* handler creation code, so you need to refer to the OS documentation
* for usage. For example, for SYS/BIOS applications, refer to the
* ti.sysbios.family.arm.m3.Hwi documentation for SYS/BIOS usage of
* interrupt priorities. If the driver uses the ti.dpl interface
* instead of making OS calls directly, then the HwiP port handles the
* interrupt priority in an OS specific way. In the case of the SYS/BIOS
* port, intPriority is passed unmodified to Hwi_create().
*
* A sample structure is shown below:
* @code
* #if defined(__TI_COMPILER_VERSION__)
* #pragma DATA_ALIGN(scratchBuf, 32)
* #elif defined(__IAR_SYSTEMS_ICC__)
* #pragma data_alignment=32
* #elif defined(__GNUC__)
* __attribute__ ((aligned (32)))
* #endif
* uint32_t scratchBuf;
*
* const SPICC32XXDMA_HWAttrsV1 SPICC32XXDMAHWAttrs[] = {
* {
* .baseAddr = GSPI_BASE,
* .intNum = INT_GSPI,
* .intPriority = (~0),
* .spiPRCM = PRCM_GSPI,
* .csControl = SPI_HW_CTRL_CS,
* .csPolarity = SPI_CS_ACTIVELOW,
* .pinMode = SPI_4PIN_MODE,
* .turboMode = SPI_TURBO_OFF,
* .scratchBufPtr = &scratchBuf,
* .defaultTxBufValue = 0,
* .rxChannelIndex = UDMA_CH6_GSPI_RX,
* .txChannelIndex = UDMA_CH7_GSPI_TX,
* .minDmaTransferSize = 100,
* .mosiPin = SPICC32XXDMA_PIN_07_MOSI,
* .misoPin = SPICC32XXDMA_PIN_06_MISO,
* .clkPin = SPICC32XXDMA_PIN_05_CLK,
* .csPin = SPICC32XXDMA_PIN_08_CS,
* },
* ...
* };
* @endcode
*/
typedef struct SPICC32XXDMA_HWAttrsV1 {
/*! SPICC32XXDMA Peripheral's base address */
uint32_t baseAddr;
/*! SPICC32XXDMA Peripheral's interrupt vector */
uint32_t intNum;
/*! SPICC32XXDMA Peripheral's interrupt priority */
uint32_t intPriority;
/*! SPI PRCM peripheral number */
uint32_t spiPRCM;
/*! Specify if chip select line will be controlled by SW or HW */
uint32_t csControl;
uint32_t csPolarity;
/*! Set peripheral to work in 3-pin or 4-pin mode */
uint32_t pinMode;
/*! Enable or disable SPI TURBO mode */
uint32_t turboMode;
/*! Address of a scratch buffer of size uint32_t */
uint32_t *scratchBufPtr;
/*! Default TX value if txBuf == NULL */
uint32_t defaultTxBufValue;
/*! uDMA RX channel index */
uint32_t rxChannelIndex;
/*! uDMA TX channel index */
uint32_t txChannelIndex;
/*! Minimum amout of data to start a uDMA transfer */
uint32_t minDmaTransferSize;
/*! GSPI MOSI pin assignment */
uint16_t mosiPin;
/*! GSPI MISO pin assignment */
uint16_t misoPin;
/*! GSPI CLK pin assignment */
uint16_t clkPin;
/*! GSPI CS pin assignment */
uint16_t csPin;
} SPICC32XXDMA_HWAttrsV1;
/*!
* @brief SPICC32XXDMA Object
*
* The application must not access any member variables of this structure!
*/
typedef struct SPICC32XXDMA_Object {
HwiP_Handle hwiHandle;
Power_NotifyObj notifyObj;
SemaphoreP_Handle transferComplete;
SPI_CallbackFxn transferCallbackFxn;
SPI_Transaction *transaction;
UDMACC32XX_Handle dmaHandle;
size_t amtDataXferred;
size_t currentXferAmt;
uint32_t bitRate;
uint32_t dataSize;
uint32_t transferTimeout;
SPI_Mode spiMode;
SPI_TransferMode transferMode;
SPI_FrameFormat frameFormat;
bool cancelInProgress;
bool isOpen;
uint8_t rxFifoTrigger;
uint8_t txFifoTrigger;
} SPICC32XXDMA_Object, *SPICC32XXDMA_Handle;
#ifdef __cplusplus
}
#endif
#endif /* ti_drivers_spi_SPICC32XXDMA__include */
| fbsder/zephyr | ext/hal/ti/simplelink/source/ti/drivers/spi/SPICC32XXDMA.h | C | apache-2.0 | 13,197 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.aggregatemetric.aggregations.metrics;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.metrics.InternalMin;
import org.elasticsearch.search.aggregations.metrics.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.support.AggregationInspectionHelper;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.xpack.aggregatemetric.AggregateMetricMapperPlugin;
import org.elasticsearch.xpack.aggregatemetric.aggregations.support.AggregateMetricsValuesSourceType;
import org.elasticsearch.xpack.aggregatemetric.mapper.AggregateDoubleMetricFieldMapper.AggregateDoubleMetricFieldType;
import org.elasticsearch.xpack.aggregatemetric.mapper.AggregateDoubleMetricFieldMapper.Metric;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import static java.util.Collections.singleton;
import static org.elasticsearch.xpack.aggregatemetric.mapper.AggregateDoubleMetricFieldMapper.subfieldName;
public class AggregateMetricBackedMinAggregatorTests extends AggregatorTestCase {
private static final String FIELD_NAME = "aggregate_metric_field";
public void testMatchesNumericDocValues() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(
List.of(
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.max), Double.doubleToLongBits(10)),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.min), Double.doubleToLongBits(2))
)
);
iw.addDocument(
List.of(
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.max), Double.doubleToLongBits(50)),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.min), Double.doubleToLongBits(5))
)
);
}, min -> {
assertEquals(2, min.getValue(), 0d);
assertTrue(AggregationInspectionHelper.hasValue(min));
});
}
public void testNoDocs() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
// Intentionally not writing any docs
}, min -> {
assertEquals(Double.POSITIVE_INFINITY, min.getValue(), 0d);
assertFalse(AggregationInspectionHelper.hasValue(min));
});
}
public void testNoMatchingField() throws IOException {
testCase(new MatchAllDocsQuery(), iw -> {
iw.addDocument(singleton(new NumericDocValuesField("wrong_number", 7)));
iw.addDocument(singleton(new NumericDocValuesField("wrong_number", 1)));
}, min -> {
assertEquals(Double.POSITIVE_INFINITY, min.getValue(), 0d);
assertFalse(AggregationInspectionHelper.hasValue(min));
});
}
public void testQueryFiltering() throws IOException {
testCase(new TermQuery(new Term("match", "yes")), iw -> {
iw.addDocument(
List.of(
new StringField("match", "yes", Field.Store.NO),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.max), Double.doubleToLongBits(10)),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.min), Double.doubleToLongBits(2))
)
);
iw.addDocument(
List.of(
new StringField("match", "yes", Field.Store.NO),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.max), Double.doubleToLongBits(20)),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.min), Double.doubleToLongBits(5))
)
);
iw.addDocument(
List.of(
new StringField("match", "no", Field.Store.NO),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.max), Double.doubleToLongBits(40)),
new NumericDocValuesField(subfieldName(FIELD_NAME, Metric.min), Double.doubleToLongBits(1))
)
);
}, min -> {
assertEquals(2L, min.getValue(), 0d);
assertTrue(AggregationInspectionHelper.hasValue(min));
});
}
/**
* Create a default aggregate_metric_double field type containing min and a max metrics.
*
* @param fieldName the name of the field
* @return the created field type
*/
private AggregateDoubleMetricFieldType createDefaultFieldType(String fieldName) {
AggregateDoubleMetricFieldType fieldType = new AggregateDoubleMetricFieldType(fieldName);
for (Metric m : List.of(Metric.min, Metric.max)) {
String subfieldName = subfieldName(fieldName, m);
NumberFieldMapper.NumberFieldType subfield = new NumberFieldMapper.NumberFieldType(
subfieldName,
NumberFieldMapper.NumberType.DOUBLE
);
fieldType.addMetricField(m, subfield);
}
fieldType.setDefaultMetric(Metric.min);
return fieldType;
}
private void testCase(Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalMin> verify)
throws IOException {
MappedFieldType fieldType = createDefaultFieldType(FIELD_NAME);
AggregationBuilder aggregationBuilder = createAggBuilderForTypeTest(fieldType, FIELD_NAME);
testCase(aggregationBuilder, query, buildIndex, verify, fieldType);
}
@Override
protected List<SearchPlugin> getSearchPlugins() {
return List.of(new AggregateMetricMapperPlugin());
}
@Override
protected AggregationBuilder createAggBuilderForTypeTest(MappedFieldType fieldType, String fieldName) {
return new MinAggregationBuilder("min_agg").field(fieldName);
}
@Override
protected List<ValuesSourceType> getSupportedValuesSourceTypes() {
return List.of(
CoreValuesSourceType.NUMERIC,
CoreValuesSourceType.DATE,
CoreValuesSourceType.BOOLEAN,
AggregateMetricsValuesSourceType.AGGREGATE_METRIC
);
}
}
| robin13/elasticsearch | x-pack/plugin/mapper-aggregate-metric/src/test/java/org/elasticsearch/xpack/aggregatemetric/aggregations/metrics/AggregateMetricBackedMinAggregatorTests.java | Java | apache-2.0 | 7,196 |
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace licenses this file to you 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.fcrepo.kernel.api.exception;
/**
* An invalid memento path constraint has been violated.
*
* @author lsitu
* @since 2018-08-10
*/
public class InvalidMementoPathException extends ConstraintViolationException {
private static final long serialVersionUID = 1L;
/**
* Ordinary constructor.
*
* @param msg the message
*/
public InvalidMementoPathException(final String msg) {
super(msg);
}
/**
* Ordinary constructor.
*
* @param msg the message
* @param rootCause the root cause
*/
public InvalidMementoPathException(final String msg, final Throwable rootCause) {
super(msg, rootCause);
}
}
| fcrepo4/fcrepo4 | fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/exception/InvalidMementoPathException.java | Java | apache-2.0 | 1,477 |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* jrunscript JavaScript built-in functions and objects.
*/
/**
* Creates an object that delegates all method calls on
* it to the 'invoke' method on the given delegate object.<br>
*
* Example:
* <pre>
* <code>
* var x = { invoke: function(name, args) { //code...}
* var y = new JSInvoker(x);
* y.func(3, 3); // calls x.invoke('func', args); where args is array of arguments
* </code>
* </pre>
* @param obj object to be wrapped by JSInvoker
* @constructor
*/
function JSInvoker(obj) {
return new JSAdapter({
__get__ : function(name) {
return function() {
return obj.invoke(name, arguments);
}
}
});
}
/**
* This variable represents OS environment. Environment
* variables can be accessed as fields of this object. For
* example, env.PATH will return PATH value configured.
*/
var env = new JSAdapter({
__get__ : function (name) {
return java.lang.System.getenv(name);
},
__has__ : function (name) {
return java.lang.System.getenv().containsKey(name);
},
__getIds__ : function() {
return java.lang.System.getenv().keySet().toArray();
},
__delete__ : function(name) {
println("can't delete env item");
},
__put__ : function (name, value) {
println("can't change env item");
},
toString: function() {
return java.lang.System.getenv().toString();
}
});
/**
* Creates a convenient script object to deal with java.util.Map instances.
* The result script object's field names are keys of the Map. For example,
* scriptObj.keyName can be used to access value associated with given key.<br>
* Example:
* <pre>
* <code>
* var x = java.lang.SystemProperties();
* var y = jmap(x);
* println(y['java.class.path']); // prints java.class.path System property
* delete y['java.class.path']; // remove java.class.path System property
* </code>
* </pre>
*
* @param map java.util.Map instance that will be wrapped
* @constructor
*/
function jmap(map) {
return new JSAdapter({
__get__ : function(name) {
if (map.containsKey(name)) {
return map.get(name);
} else {
return undefined;
}
},
__has__ : function(name) {
return map.containsKey(name);
},
__delete__ : function (name) {
return map.remove(name);
},
__put__ : function(name, value) {
map.put(name, value);
},
__getIds__ : function() {
return map.keySet().toArray();
},
toString: function() {
return map.toString();
}
});
}
/**
* Creates a convenient script object to deal with java.util.List instances.
* The result script object behaves like an array. For example,
* scriptObj[index] syntax can be used to access values in the List instance.
* 'length' field gives size of the List. <br>
*
* Example:
* <pre>
* <code>
* var x = new java.util.ArrayList(4);
* x.add('Java');
* x.add('JavaScript');
* x.add('SQL');
* x.add('XML');
*
* var y = jlist(x);
* println(y[2]); // prints third element of list
* println(y.length); // prints size of the list
*
* @param map java.util.List instance that will be wrapped
* @constructor
*/
function jlist(list) {
function isValid(index) {
return typeof(index) == 'number' &&
index > -1 && index < list.size();
}
return new JSAdapter({
__get__ : function(name) {
if (isValid(name)) {
return list.get(name);
} else if (name == 'length') {
return list.size();
} else {
return undefined;
}
},
__has__ : function (name) {
return isValid(name) || name == 'length';
},
__delete__ : function(name) {
if (isValid(name)) {
list.remove(name);
}
},
__put__ : function(name, value) {
if (isValid(name)) {
list.set(name, value);
}
},
__getIds__: function() {
var res = new Array(list.size());
for (var i = 0; i < res.length; i++) {
res[i] = i;
}
return res;
},
toString: function() {
return list.toString();
}
});
}
/**
* This is java.lang.System properties wrapped by jmap.
* For eg. to access java.class.path property, you can use
* the syntax sysProps["java.class.path"]
*/
var sysProps = jmap(java.lang.System.getProperties());
// stdout, stderr & stdin
var out = java.lang.System.out;
var err = java.lang.System.err;
// can't use 'in' because it is a JavaScript keyword :-(
var inp = java.lang.System["in"];
// useful imports for often used io, net classes
importPackage(java.io);
importPackage(java.net);
/**
* Generic any object to input stream mapper
* @param str input file name, URL or InputStream
* @return InputStream object
* @private
*/
function inStream(str) {
if (typeof(str) == "string") {
// '-' means standard input
if (str == '-') {
return java.lang.System["in"];
}
// try file first
var file = null;
try {
file = pathToFile(str);
} catch (e) {
}
if (file && file.exists()) {
return new FileInputStream(file);
} else {
try {
// treat the string as URL
return new URL(str).openStream();
} catch (e) {
throw 'file or URL ' + str + ' not found';
}
}
} else {
if (str instanceof InputStream) {
return str;
} else if (str instanceof URL) {
return str.openStream();
} else if (str instanceof File) {
return new FileInputStream(str);
}
}
// everything failed, just give input stream
return java.lang.System["in"];
}
/**
* Generic any object to output stream mapper
*
* @param out output file name or stream
* @return OutputStream object
* @private
*/
function outStream(out) {
if (typeof(out) == "string") {
if (out == '>') {
return java.lang.System.out;
} else {
// treat it as file
return new FileOutputStream(pathToFile(out));
}
} else {
if (out instanceof OutputStream) {
return out;
} else if (out instanceof File) {
return new FileOutputStream(out);
}
}
// everything failed, just return System.out
return java.lang.System.out;
}
/**
* stream close takes care not to close stdin, out & err.
* @private
*/
function streamClose(stream) {
if (stream) {
if (stream != java.lang.System["in"] &&
stream != java.lang.System.out &&
stream != java.lang.System.err) {
try {
stream.close();
} catch (e) {
println(e);
}
}
}
}
/**
* Loads and evaluates JavaScript code from a stream or file or URL<br>
*
* Examples:
* <pre>
* <code>
* load('test.js'); // load script file 'test.js'
* load('http://java.sun.com/foo.js'); // load from a URL
* </code>
* </pre>
*
* @param str input from which script is loaded and evaluated
*/
function load(str) {
var stream = inStream(str);
var bstream = new BufferedInputStream(stream);
var reader = new BufferedReader(new InputStreamReader(bstream));
var oldFilename = engine.get(engine.FILENAME);
engine.put(engine.FILENAME, str);
try {
engine.eval(reader);
} finally {
engine.put(engine.FILENAME, oldFilename);
}
streamClose(stream);
}
// file system utilities
/**
* Creates a Java byte[] of given length
* @param len size of the array to create
* @private
*/
function javaByteArray(len) {
return java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, len);
}
var curDir = new File('.');
/**
* Print present working directory
*/
function pwd() {
println(curDir.getAbsolutePath());
}
/**
* Changes present working directory to given directory
* @param target directory to change to. optional, defaults to user's HOME
*/
function cd(target) {
if (target == undefined) {
target = sysProps["user.home"];
}
if (!(target instanceof File)) {
target = pathToFile(target);
}
if (target.exists() && target.isDirectory()) {
curDir = target;
} else {
println(target + " is not a directory");
}
}
/**
* Converts path to java.io.File taking care of shell present working dir
*
* @param pathname file path to be converted
* @private
*/
function pathToFile(pathname) {
var tmp = pathname;
if (!(tmp instanceof File)) {
tmp = new File(tmp);
}
if (!tmp.isAbsolute()) {
return new File(curDir, pathname);
} else {
return tmp;
}
}
/**
* Copies a file or URL or stream to another file or stream
*
* @param from input file or URL or stream
* @param to output stream or file
*/
function cp(from, to) {
if (from == to) {
println("file " + from + " cannot be copied onto itself!");
return;
}
var inp = inStream(from);
var out = outStream(to);
var binp = new BufferedInputStream(inp);
var bout = new BufferedOutputStream(out);
var buff = javaByteArray(1024);
var len;
while ((len = binp.read(buff)) > 0 )
bout.write(buff, 0, len);
bout.flush();
streamClose(inp);
streamClose(out);
}
/**
* Shows the content of a file or URL or any InputStream<br>
* Examples:
* <pre>
* <code>
* cat('test.txt'); // show test.txt file contents
* cat('http://java.net'); // show the contents from the URL http://java.net
* </code>
* </pre>
* @param obj input to show
* @param pattern optional. show only the lines matching the pattern
*/
function cat(obj, pattern) {
if (obj instanceof File && obj.isDirectory()) {
ls(obj);
return;
}
var inp = null;
if (!(obj instanceof Reader)) {
inp = inStream(obj);
obj = new BufferedReader(new InputStreamReader(inp));
}
var line;
if (pattern) {
var count = 1;
while ((line=obj.readLine()) != null) {
if (line.match(pattern)) {
println(count + "\t: " + line);
}
count++;
}
} else {
while ((line=obj.readLine()) != null) {
println(line);
}
}
}
/**
* Returns directory part of a filename
*
* @param pathname input path name
* @return directory part of the given file name
*/
function dirname(pathname) {
var dirName = ".";
// Normalize '/' to local file separator before work.
var i = pathname.replace('/', File.separatorChar ).lastIndexOf(
File.separator );
if ( i != -1 )
dirName = pathname.substring(0, i);
return dirName;
}
/**
* Creates a new dir of given name
*
* @param dir name of the new directory
*/
function mkdir(dir) {
var dir = pathToFile(dir);
println(dir.mkdir()? "created" : "can not create dir");
}
/**
* Creates the directory named by given pathname, including
* any necessary but nonexistent parent directories.
*
* @param dir input path name
*/
function mkdirs(dir) {
var dir = pathToFile(dir);
println(dir.mkdirs()? "created" : "can not create dirs");
}
/**
* Removes a given file
*
* @param pathname name of the file
*/
function rm(pathname) {
file = pathToFile(pathname);
if (!file.exists()) {
println("file not found: " + pathname);
return false;
}
// note that delete is a keyword in JavaScript!
println(file["delete"]()? "deleted" : "can not delete");
}
/**
* Removes a given directory
*
* @param pathname name of the directory
*/
function rmdir(pathname) {
rm(pathname);
}
/**
* Synonym for 'rm'
*/
function del(pathname) {
rm(pathname);
}
/**
* Moves a file to another
*
* @param from original name of the file
* @param to new name for the file
*/
function mv(from, to) {
println(pathToFile(from).renameTo(pathToFile(to))?
"moved" : "can not move");
}
/**
* Synonym for 'mv'.
*/
function ren(from, to) {
mv(from, to);
}
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
/**
* Helper function called by ls
* @private
*/
function printFile(f) {
var sb = new java.lang.StringBuffer();
sb.append(f.isDirectory()? "d" : "-");
sb.append(f.canRead() ? "r": "-" );
sb.append(f.canWrite() ? "w": "-" );
sb.append(" ");
var d = new java.util.Date(f.lastModified());
var c = new java.util.GregorianCalendar();
c.setTime(d);
var day = c.get(java.util.Calendar.DAY_OF_MONTH);
sb.append(months[c.get(java.util.Calendar.MONTH)]
+ " " + day );
if (day < 10) {
sb.append(" ");
}
// to get fixed length 'length' field
var fieldlen = 8;
var len = new java.lang.StringBuffer();
for(var j=0; j<fieldlen; j++)
len.append(" ");
len.insert(0, java.lang.Long.toString(f.length()));
len.setLength(fieldlen);
// move the spaces to the front
var si = len.toString().indexOf(" ");
if ( si != -1 ) {
var pad = len.toString().substring(si);
len.setLength(si);
len.insert(0, pad);
}
sb.append(len.toString());
sb.append(" ");
sb.append(f.getName());
if (f.isDirectory()) {
sb.append('/');
}
println(sb.toString());
}
/**
* Lists the files in a directory
*
* @param dir directory from which to list the files. optional, default to pwd
* @param filter pattern to filter the files listed. optional, default is '.'.
*/
function ls(dir, filter) {
if (dir) {
dir = pathToFile(dir);
} else {
dir = curDir;
}
if (dir.isDirectory()) {
var files = dir.listFiles();
for (var i in files) {
var f = files[i];
if (filter) {
if(!f.getName().match(filter)) {
continue;
}
}
printFile(f);
}
} else {
printFile(dir);
}
}
/**
* Synonym for 'ls'.
*/
function dir(d, filter) {
ls(d, filter);
}
/**
* Unix-like grep, but accepts JavaScript regex patterns
*
* @param pattern to search in files
* @param files one or more files
*/
function grep(pattern, files /*, one or more files */) {
if (arguments.length < 2) return;
for (var i = 1; i < arguments.length; i++) {
println(arguments[i] + ":");
cat(arguments[i], pattern);
}
}
/**
* Find in files. Calls arbitrary callback function
* for each matching file.<br>
*
* Examples:
* <pre>
* <code>
* find('.')
* find('.', '.*\.class', rm); // remove all .class files
* find('.', '.*\.java'); // print fullpath of each .java file
* find('.', '.*\.java', cat); // print all .java files
* </code>
* </pre>
*
* @param dir directory to search files
* @param pattern to search in the files
* @param callback function to call for matching files
*/
function find(dir, pattern, callback) {
dir = pathToFile(dir);
if (!callback) callback = print;
var files = dir.listFiles();
for (var f in files) {
var file = files[f];
if (file.isDirectory()) {
find(file, pattern, callback);
} else {
if (pattern) {
if (file.getName().match(pattern)) {
callback(file);
}
} else {
callback(file);
}
}
}
}
// process utilities
/**
* Exec's a child process, waits for completion & returns exit code
*
* @param cmd command to execute in child process
*/
function exec(cmd) {
var process = java.lang.Runtime.getRuntime().exec(cmd);
var inp = new DataInputStream(process.getInputStream());
var line = null;
while ((line = inp.readLine()) != null) {
println(line);
}
process.waitFor();
$exit = process.exitValue();
}
/**
* Exit the shell program.
*
* @param exitCode integer code returned to OS shell.
* optional, defaults to 0
*/
function exit(code) {
if (code) {
java.lang.System.exit(code + 0);
} else {
java.lang.System.exit(0);
}
}
/**
* synonym for exit
*/
function quit(code) {
exit(code);
}
// XML utilities
/**
* Converts input to DOM Document object
*
* @param inp file or reader. optional, without this param,
* this function returns a new DOM Document.
* @return returns a DOM Document object
*/
function XMLDocument(inp) {
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
var builder = factory.newDocumentBuilder();
if (inp) {
if (typeof(inp) == "string") {
return builder.parse(pathToFile(inp));
} else {
return builder.parse(inp);
}
} else {
return builder.newDocument();
}
}
/**
* Converts arbitrary stream, file, URL to XMLSource
*
* @param inp input stream or file or URL
* @return XMLSource object
*/
function XMLSource(inp) {
if (inp instanceof javax.xml.transform.Source) {
return inp;
} else if (inp instanceof Packages.org.w3c.dom.Document) {
return new javax.xml.transform.dom.DOMSource(inp);
} else {
inp = new BufferedInputStream(inStream(inp));
return new javax.xml.transform.stream.StreamSource(inp);
}
}
/**
* Converts arbitrary stream, file to XMLResult
*
* @param inp output stream or file
* @return XMLResult object
*/
function XMLResult(out) {
if (out instanceof javax.xml.transform.Result) {
return out;
} else if (out instanceof Packages.org.w3c.dom.Document) {
return new javax.xml.transform.dom.DOMResult(out);
} else {
out = new BufferedOutputStream(outStream(out));
return new javax.xml.transform.stream.StreamResult(out);
}
}
/**
* Perform XSLT transform
*
* @param inp Input XML to transform (URL, File or InputStream)
* @param style XSL Stylesheet to be used (URL, File or InputStream). optional.
* @param out Output XML (File or OutputStream
*/
function XSLTransform(inp, style, out) {
switch (arguments.length) {
case 2:
inp = arguments[0];
out = arguments[1];
break;
case 3:
inp = arguments[0];
style = arguments[1];
out = arguments[2];
break;
default:
println("XSL tranform requires 2 or 3 arguments");
return;
}
var factory = javax.xml.transform.TransformerFactory.newInstance();
var tranformer;
if (style) {
transformer = factory.newTransformer(XMLSource(style));
} else {
transformer = factory.newTransformer();
}
var source = XMLSource(inp);
var result = XMLResult(out);
transformer.transform(source, result);
if (source.getInputStream) {
streamClose(source.getInputStream());
}
if (result.getOutputStream) {
streamClose(result.getOutputStream());
}
}
// miscellaneous utilities
/**
* Prints which command is selected from PATH
*
* @param cmd name of the command searched from PATH
*/
function which(cmd) {
var st = new java.util.StringTokenizer(env.PATH, File.pathSeparator);
while (st.hasMoreTokens()) {
var file = new File(st.nextToken(), cmd);
if (file.exists()) {
println(file.getAbsolutePath());
return;
}
}
}
/**
* Prints IP addresses of given domain name
*
* @param name domain name
*/
function ip(name) {
var addrs = InetAddress.getAllByName(name);
for (var i in addrs) {
println(addrs[i]);
}
}
/**
* Prints current date in current locale
*/
function date() {
println(new Date().toLocaleString());
}
/**
* Echoes the given string arguments
*/
function echo(x) {
for (var i = 0; i < arguments.length; i++) {
println(arguments[i]);
}
}
/**
* This is C-like printf
*
* @param format string to format the rest of the print items
* @param args variadic argument list
*/
function printf(format, args/*, more args*/) {
var array = java.lang.reflect.Array.newInstance(java.lang.Object,
arguments.length - 1);
for (var i = 0; i < array.length; i++) {
array[i] = arguments[i+1];
}
return java.lang.System.out.printf(format, array);
}
/**
* Reads one or more lines from stdin after printing prompt
*
* @param prompt optional, default is '>'
* @param multiline to tell whether to read single line or multiple lines
*/
function read(prompt, multiline) {
if (!prompt) {
prompt = '>';
}
var inp = java.lang.System["in"];
var reader = new BufferedReader(new InputStreamReader(inp));
if (multiline) {
var line = '';
while (true) {
java.lang.System.err.print(prompt);
java.lang.System.err.flush();
var tmp = reader.readLine();
if (tmp == '' || tmp == null) break;
line += tmp + '\n';
}
return line;
} else {
java.lang.System.err.print(prompt);
java.lang.System.err.flush();
return reader.readLine();
}
}
| andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/com/sun/tools/script/shell/init.js | JavaScript | apache-2.0 | 20,463 |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ast/context-slot-cache.h"
#include <stdlib.h>
#include "src/ast/scopes.h"
#include "src/bootstrapper.h"
// FIXME(mstarzinger, marja): This is weird, but required because of the missing
// (disallowed) include: src/factory.h -> src/objects-inl.h
#include "src/objects-inl.h"
// FIXME(mstarzinger, marja): This is weird, but required because of the missing
// (disallowed) include: src/type-feedback-vector.h ->
// src/type-feedback-vector-inl.h
#include "src/type-feedback-vector-inl.h"
namespace v8 {
namespace internal {
int ContextSlotCache::Hash(Object* data, String* name) {
// Uses only lower 32 bits if pointers are larger.
uintptr_t addr_hash =
static_cast<uint32_t>(reinterpret_cast<uintptr_t>(data)) >> 2;
return static_cast<int>((addr_hash ^ name->Hash()) % kLength);
}
int ContextSlotCache::Lookup(Object* data, String* name, VariableMode* mode,
InitializationFlag* init_flag,
MaybeAssignedFlag* maybe_assigned_flag) {
int index = Hash(data, name);
Key& key = keys_[index];
if ((key.data == data) && key.name->Equals(name)) {
Value result(values_[index]);
if (mode != nullptr) *mode = result.mode();
if (init_flag != nullptr) *init_flag = result.initialization_flag();
if (maybe_assigned_flag != nullptr)
*maybe_assigned_flag = result.maybe_assigned_flag();
return result.index() + kNotFound;
}
return kNotFound;
}
void ContextSlotCache::Update(Handle<Object> data, Handle<String> name,
VariableMode mode, InitializationFlag init_flag,
MaybeAssignedFlag maybe_assigned_flag,
int slot_index) {
DisallowHeapAllocation no_gc;
Handle<String> internalized_name;
DCHECK(slot_index > kNotFound);
if (StringTable::InternalizeStringIfExists(name->GetIsolate(), name)
.ToHandle(&internalized_name)) {
int index = Hash(*data, *internalized_name);
Key& key = keys_[index];
key.data = *data;
key.name = *internalized_name;
// Please note value only takes a uint as index.
values_[index] =
Value(mode, init_flag, maybe_assigned_flag, slot_index - kNotFound)
.raw();
#ifdef DEBUG
ValidateEntry(data, name, mode, init_flag, maybe_assigned_flag, slot_index);
#endif
}
}
void ContextSlotCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].data = nullptr;
}
#ifdef DEBUG
void ContextSlotCache::ValidateEntry(Handle<Object> data, Handle<String> name,
VariableMode mode,
InitializationFlag init_flag,
MaybeAssignedFlag maybe_assigned_flag,
int slot_index) {
DisallowHeapAllocation no_gc;
Handle<String> internalized_name;
if (StringTable::InternalizeStringIfExists(name->GetIsolate(), name)
.ToHandle(&internalized_name)) {
int index = Hash(*data, *name);
Key& key = keys_[index];
DCHECK(key.data == *data);
DCHECK(key.name->Equals(*name));
Value result(values_[index]);
DCHECK(result.mode() == mode);
DCHECK(result.initialization_flag() == init_flag);
DCHECK(result.maybe_assigned_flag() == maybe_assigned_flag);
DCHECK(result.index() + kNotFound == slot_index);
}
}
#endif // DEBUG
} // namespace internal
} // namespace v8
| weolar/miniblink49 | v8_5_7/src/ast/context-slot-cache.cc | C++ | apache-2.0 | 3,604 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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 com.siyeh.ig.junit;
import com.intellij.codeInsight.TestFrameworks;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import com.intellij.testIntegration.TestFramework;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.naming.ConventionInspection;
import com.siyeh.ig.psiutils.LibraryUtil;
import com.siyeh.ig.psiutils.MethodUtils;
import com.siyeh.ig.psiutils.TestUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
/**
* @author Bas Leijdekkers
*/
public class JUnit4MethodNamingConventionInspectionBase extends ConventionInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return InspectionGadgetsBundle.message("junit4.method.naming.convention.display.name");
}
@Override
protected String getElementDescription() {
return InspectionGadgetsBundle.message("junit4.method.naming.convention.element.description");
}
@Override
protected String getDefaultRegex() {
return "[a-z][A-Za-z_\\d]*";
}
@Override
protected int getDefaultMinLength() {
return 4;
}
@Override
protected int getDefaultMaxLength() {
return 64;
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new JUnit4MethodNamingConventionVisitor();
}
private class JUnit4MethodNamingConventionVisitor extends BaseInspectionVisitor {
@Override
public void visitMethod(PsiMethod method) {
super.visitMethod(method);
if (!TestUtils.isAnnotatedTestMethod(method)) {
return;
}
final PsiIdentifier nameIdentifier = method.getNameIdentifier();
if (nameIdentifier == null) {
return;
}
final String name = method.getName();
if (isValid(name)) {
return;
}
if (!isOnTheFly() && MethodUtils.hasSuper(method)) {
return;
}
if (LibraryUtil.isOverrideOfLibraryMethod(method)) {
return;
}
registerMethodError(method, name);
}
}
}
| asedunov/intellij-community | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/JUnit4MethodNamingConventionInspectionBase.java | Java | apache-2.0 | 2,676 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Wed Oct 19 15:34:08 PDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.orc.OrcProto.IntegerStatistics.Builder (ORC Core 1.2.1 API)</title>
<meta name="date" content="2016-10-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.orc.OrcProto.IntegerStatistics.Builder (ORC Core 1.2.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/orc/class-use/OrcProto.IntegerStatistics.Builder.html" target="_top">Frames</a></li>
<li><a href="OrcProto.IntegerStatistics.Builder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.orc.OrcProto.IntegerStatistics.Builder" class="title">Uses of Class<br>org.apache.orc.OrcProto.IntegerStatistics.Builder</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.orc">org.apache.orc</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.orc">
<!-- -->
</a>
<h3>Uses of <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a> in <a href="../../../../org/apache/orc/package-summary.html">org.apache.orc</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../org/apache/orc/package-summary.html">org.apache.orc</a> that return <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#clear--">clear</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#clearMaximum--">clearMaximum</a></span>()</code>
<div class="block"><code>optional sint64 maximum = 2;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#clearMinimum--">clearMinimum</a></span>()</code>
<div class="block"><code>optional sint64 minimum = 1;</code></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#clearSum--">clearSum</a></span>()</code>
<div class="block"><code>optional sint64 sum = 3;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#clone--">clone</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.ColumnStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.ColumnStatistics.Builder.html#getIntStatisticsBuilder--">getIntStatisticsBuilder</a></span>()</code>
<div class="block"><code>optional .orc.proto.IntegerStatistics intStatistics = 2;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#mergeFrom-com.google.protobuf.CodedInputStream-com.google.protobuf.ExtensionRegistryLite-">mergeFrom</a></span>(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#mergeFrom-com.google.protobuf.Message-">mergeFrom</a></span>(com.google.protobuf.Message other)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#mergeFrom-org.apache.orc.OrcProto.IntegerStatistics-">mergeFrom</a></span>(<a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html" title="class in org.apache.orc">OrcProto.IntegerStatistics</a> other)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html#newBuilder--">newBuilder</a></span>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html#newBuilder-org.apache.orc.OrcProto.IntegerStatistics-">newBuilder</a></span>(<a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html" title="class in org.apache.orc">OrcProto.IntegerStatistics</a> prototype)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html#newBuilderForType--">newBuilderForType</a></span>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html#newBuilderForType-com.google.protobuf.GeneratedMessage.BuilderParent-">newBuilderForType</a></span>(com.google.protobuf.GeneratedMessage.BuilderParent parent)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#setMaximum-long-">setMaximum</a></span>(long value)</code>
<div class="block"><code>optional sint64 maximum = 2;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#setMinimum-long-">setMinimum</a></span>(long value)</code>
<div class="block"><code>optional sint64 minimum = 1;</code></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html#setSum-long-">setSum</a></span>(long value)</code>
<div class="block"><code>optional sint64 sum = 3;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.IntegerStatistics.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.html#toBuilder--">toBuilder</a></span>()</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../org/apache/orc/package-summary.html">org.apache.orc</a> with parameters of type <a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/orc/OrcProto.ColumnStatistics.Builder.html" title="class in org.apache.orc">OrcProto.ColumnStatistics.Builder</a></code></td>
<td class="colLast"><span class="typeNameLabel">OrcProto.ColumnStatistics.Builder.</span><code><span class="memberNameLink"><a href="../../../../org/apache/orc/OrcProto.ColumnStatistics.Builder.html#setIntStatistics-org.apache.orc.OrcProto.IntegerStatistics.Builder-">setIntStatistics</a></span>(<a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">OrcProto.IntegerStatistics.Builder</a> builderForValue)</code>
<div class="block"><code>optional .orc.proto.IntegerStatistics intStatistics = 2;</code></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/apache/orc/OrcProto.IntegerStatistics.Builder.html" title="class in org.apache.orc">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/orc/class-use/OrcProto.IntegerStatistics.Builder.html" target="_top">Frames</a></li>
<li><a href="OrcProto.IntegerStatistics.Builder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2016 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| pudidic/orc | site/api/orc-core/org/apache/orc/class-use/OrcProto.IntegerStatistics.Builder.html | HTML | apache-2.0 | 16,954 |
/* 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.flowable.admin.app.rest.client;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.flowable.admin.domain.EndpointType;
import org.flowable.admin.domain.ServerConfig;
import org.flowable.admin.service.engine.ContentItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Yvo Swillens
*/
@RestController
public class ContentItemsClientResource extends AbstractClientResource {
@Autowired
protected ContentItemService clientService;
@Autowired
protected ObjectMapper objectMapper;
/**
* GET a list of content items.
*/
@RequestMapping(value = "/rest/admin/content-items", method = RequestMethod.GET, produces = "application/json")
public JsonNode listFormDefinitions(HttpServletRequest request) {
ServerConfig serverConfig = retrieveServerConfig(EndpointType.CONTENT);
Map<String, String[]> parameterMap = getRequestParametersWithoutServerId(request);
return clientService.listContentItems(serverConfig, parameterMap);
}
/**
* GET process instance's list of content items.
*/
@RequestMapping(value = "/rest/admin/process-instance-content-items/{processInstanceId}", method = RequestMethod.GET, produces = "application/json")
public JsonNode getProcessDefinitionForms(@PathVariable String processInstanceId, HttpServletRequest request) {
ServerConfig serverConfig = retrieveServerConfig(EndpointType.CONTENT);
Map<String, String[]> parameterMap = getRequestParametersWithoutServerId(request);
String[] processInstanceIds = { processInstanceId };
parameterMap.put("processInstanceId", processInstanceIds);
return clientService.listContentItems(serverConfig, parameterMap);
}
}
| stephraleigh/flowable-engine | modules/flowable-ui-admin/src/main/java/org/flowable/admin/app/rest/client/ContentItemsClientResource.java | Java | apache-2.0 | 2,700 |
##
# Announcements get made by Instructors and Autolab Admins, and get displayed
# to everyone who uses the site, until they expire.
#
class Announcement < ActiveRecord::Base
belongs_to :course
trim_field :title
end
| anusornc/Autolab | app/models/announcement.rb | Ruby | apache-2.0 | 220 |
import glob
import logging
import os
from typing import Any, Dict, List, Optional
from django.conf import settings
from zerver.lib.storage import static_path
# See https://jackstromberg.com/2013/01/useraccountcontrol-attributeflag-values/
# for docs on what these values mean.
LDAP_USER_ACCOUNT_CONTROL_NORMAL = "512"
LDAP_USER_ACCOUNT_CONTROL_DISABLED = "514"
def generate_dev_ldap_dir(mode: str, num_users: int = 8) -> Dict[str, Dict[str, Any]]:
mode = mode.lower()
ldap_data = []
for i in range(1, num_users + 1):
name = f"LDAP User {i}"
email = f"ldapuser{i}@zulip.com"
phone_number = f"999999999{i}"
birthdate = f"19{i:02}-{i:02}-{i:02}"
ldap_data.append((name, email, phone_number, birthdate))
profile_images = []
for path in glob.glob(os.path.join(static_path("images/team"), "*")):
with open(path, "rb") as f:
profile_images.append(f.read())
ldap_dir = {}
for i, user_data in enumerate(ldap_data):
email = user_data[1].lower()
email_username = email.split("@")[0]
common_data = {
"cn": [user_data[0]],
"userPassword": [email_username],
"phoneNumber": [user_data[2]],
"birthDate": [user_data[3]],
}
if mode == "a":
ldap_dir["uid=" + email + ",ou=users,dc=zulip,dc=com"] = dict(
uid=[email],
thumbnailPhoto=[profile_images[i % len(profile_images)]],
userAccountControl=[LDAP_USER_ACCOUNT_CONTROL_NORMAL],
**common_data,
)
elif mode == "b":
ldap_dir["uid=" + email_username + ",ou=users,dc=zulip,dc=com"] = dict(
uid=[email_username],
jpegPhoto=[profile_images[i % len(profile_images)]],
**common_data,
)
elif mode == "c":
ldap_dir["uid=" + email_username + ",ou=users,dc=zulip,dc=com"] = dict(
uid=[email_username], email=[email], **common_data
)
return ldap_dir
def init_fakeldap(
directory: Optional[Dict[str, Dict[str, List[str]]]] = None
) -> None: # nocoverage
# We only use this in development. Importing mock inside
# this function is an import time optimization, which
# avoids the expensive import of the mock module (slow
# because its dependency pbr uses pkgresources, which is
# really slow to import.)
from unittest import mock
from fakeldap import MockLDAP
# Silent `django_auth_ldap` logger in dev mode to avoid
# spammy user not found log messages.
ldap_auth_logger = logging.getLogger("django_auth_ldap")
ldap_auth_logger.setLevel(logging.CRITICAL)
fakeldap_logger = logging.getLogger("fakeldap")
fakeldap_logger.setLevel(logging.CRITICAL)
ldap_patcher = mock.patch("django_auth_ldap.config.ldap.initialize")
mock_initialize = ldap_patcher.start()
mock_ldap = MockLDAP()
mock_initialize.return_value = mock_ldap
mock_ldap.directory = directory or generate_dev_ldap_dir(
settings.FAKE_LDAP_MODE, settings.FAKE_LDAP_NUM_USERS
)
| rht/zulip | zerver/lib/dev_ldap_directory.py | Python | apache-2.0 | 3,149 |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.utils.Pool;
public class CollisionJNI {
public final static native void delete_btDiscreteCollisionDetectorInterface_Result(long jarg1);
public final static native void btDiscreteCollisionDetectorInterface_Result_setShapeIdentifiersA(long jarg1, btDiscreteCollisionDetectorInterface.Result jarg1_, int jarg2, int jarg3);
public final static native void btDiscreteCollisionDetectorInterface_Result_setShapeIdentifiersB(long jarg1, btDiscreteCollisionDetectorInterface.Result jarg1_, int jarg2, int jarg3);
public final static native void btDiscreteCollisionDetectorInterface_Result_addContactPoint(long jarg1, btDiscreteCollisionDetectorInterface.Result jarg1_, Vector3 jarg2, Vector3 jarg3, float jarg4);
public final static native long new_btDiscreteCollisionDetectorInterface_ClosestPointInput();
public final static native void btDiscreteCollisionDetectorInterface_ClosestPointInput_transformA_set(long jarg1, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg1_, long jarg2, btTransform jarg2_);
public final static native long btDiscreteCollisionDetectorInterface_ClosestPointInput_transformA_get(long jarg1, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg1_);
public final static native void btDiscreteCollisionDetectorInterface_ClosestPointInput_transformB_set(long jarg1, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg1_, long jarg2, btTransform jarg2_);
public final static native long btDiscreteCollisionDetectorInterface_ClosestPointInput_transformB_get(long jarg1, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg1_);
public final static native void btDiscreteCollisionDetectorInterface_ClosestPointInput_maximumDistanceSquared_set(long jarg1, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg1_, float jarg2);
public final static native float btDiscreteCollisionDetectorInterface_ClosestPointInput_maximumDistanceSquared_get(long jarg1, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg1_);
public final static native void delete_btDiscreteCollisionDetectorInterface_ClosestPointInput(long jarg1);
public final static native void delete_btDiscreteCollisionDetectorInterface(long jarg1);
public final static native void btDiscreteCollisionDetectorInterface_getClosestPoints__SWIG_0(long jarg1, btDiscreteCollisionDetectorInterface jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_, boolean jarg5);
public final static native void btDiscreteCollisionDetectorInterface_getClosestPoints__SWIG_1(long jarg1, btDiscreteCollisionDetectorInterface jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_);
public final static native void btStorageResult_normalOnSurfaceB_set(long jarg1, btStorageResult jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btStorageResult_normalOnSurfaceB_get(long jarg1, btStorageResult jarg1_);
public final static native void btStorageResult_closestPointInB_set(long jarg1, btStorageResult jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btStorageResult_closestPointInB_get(long jarg1, btStorageResult jarg1_);
public final static native void btStorageResult_distance_set(long jarg1, btStorageResult jarg1_, float jarg2);
public final static native float btStorageResult_distance_get(long jarg1, btStorageResult jarg1_);
public final static native void delete_btStorageResult(long jarg1);
public final static native void btBroadphaseProxy_clientObject_set(long jarg1, btBroadphaseProxy jarg1_, long jarg2);
public final static native long btBroadphaseProxy_clientObject_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native void btBroadphaseProxy_collisionFilterGroup_set(long jarg1, btBroadphaseProxy jarg1_, short jarg2);
public final static native short btBroadphaseProxy_collisionFilterGroup_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native void btBroadphaseProxy_collisionFilterMask_set(long jarg1, btBroadphaseProxy jarg1_, short jarg2);
public final static native short btBroadphaseProxy_collisionFilterMask_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native void btBroadphaseProxy_multiSapParentProxy_set(long jarg1, btBroadphaseProxy jarg1_, long jarg2);
public final static native long btBroadphaseProxy_multiSapParentProxy_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native void btBroadphaseProxy_uniqueId_set(long jarg1, btBroadphaseProxy jarg1_, int jarg2);
public final static native int btBroadphaseProxy_uniqueId_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native void btBroadphaseProxy_aabbMin_set(long jarg1, btBroadphaseProxy jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btBroadphaseProxy_aabbMin_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native void btBroadphaseProxy_aabbMax_set(long jarg1, btBroadphaseProxy jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btBroadphaseProxy_aabbMax_get(long jarg1, btBroadphaseProxy jarg1_);
public final static native int btBroadphaseProxy_getUid(long jarg1, btBroadphaseProxy jarg1_);
public final static native long new_btBroadphaseProxy__SWIG_0();
public final static native long new_btBroadphaseProxy__SWIG_1(Vector3 jarg1, Vector3 jarg2, long jarg3, short jarg4, short jarg5, long jarg6);
public final static native long new_btBroadphaseProxy__SWIG_2(Vector3 jarg1, Vector3 jarg2, long jarg3, short jarg4, short jarg5);
public final static native boolean btBroadphaseProxy_isPolyhedral(int jarg1);
public final static native boolean btBroadphaseProxy_isConvex(int jarg1);
public final static native boolean btBroadphaseProxy_isNonMoving(int jarg1);
public final static native boolean btBroadphaseProxy_isConcave(int jarg1);
public final static native boolean btBroadphaseProxy_isCompound(int jarg1);
public final static native boolean btBroadphaseProxy_isSoftBody(int jarg1);
public final static native boolean btBroadphaseProxy_isInfinite(int jarg1);
public final static native boolean btBroadphaseProxy_isConvex2d(int jarg1);
public final static native void delete_btBroadphaseProxy(long jarg1);
public final static native long new_btBroadphasePair__SWIG_0();
public final static native long new_btBroadphasePair__SWIG_1(btBroadphasePair jarg1);
public final static native long new_btBroadphasePair__SWIG_2(btBroadphaseProxy jarg1, btBroadphaseProxy jarg2);
public final static native void btBroadphasePair_pProxy0_set(long jarg1, btBroadphasePair jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native long btBroadphasePair_pProxy0_get(long jarg1, btBroadphasePair jarg1_);
public final static native void btBroadphasePair_pProxy1_set(long jarg1, btBroadphasePair jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native long btBroadphasePair_pProxy1_get(long jarg1, btBroadphasePair jarg1_);
public final static native void btBroadphasePair_algorithm_set(long jarg1, btBroadphasePair jarg1_, long jarg2, btCollisionAlgorithm jarg2_);
public final static native long btBroadphasePair_algorithm_get(long jarg1, btBroadphasePair jarg1_);
public final static native void btBroadphasePair_internalInfo1_set(long jarg1, btBroadphasePair jarg1_, long jarg2);
public final static native long btBroadphasePair_internalInfo1_get(long jarg1, btBroadphasePair jarg1_);
public final static native void btBroadphasePair_internalTmpValue_set(long jarg1, btBroadphasePair jarg1_, int jarg2);
public final static native int btBroadphasePair_internalTmpValue_get(long jarg1, btBroadphasePair jarg1_);
public final static native void delete_btBroadphasePair(long jarg1);
public final static native long new_btBroadphasePairSortPredicate();
public final static native void delete_btBroadphasePairSortPredicate(long jarg1);
public final static native void delete_btBroadphaseAabbCallback(long jarg1);
public final static native boolean btBroadphaseAabbCallback_process(long jarg1, btBroadphaseAabbCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native long new_btBroadphaseAabbCallback();
public final static native void btBroadphaseAabbCallback_director_connect(btBroadphaseAabbCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btBroadphaseAabbCallback_change_ownership(btBroadphaseAabbCallback obj, long cptr, boolean take_or_release);
public final static native void btBroadphaseRayCallback_rayDirectionInverse_set(long jarg1, btBroadphaseRayCallback jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btBroadphaseRayCallback_rayDirectionInverse_get(long jarg1, btBroadphaseRayCallback jarg1_);
public final static native void btBroadphaseRayCallback_signs_set(long jarg1, btBroadphaseRayCallback jarg1_, long[] jarg2);
public final static native long[] btBroadphaseRayCallback_signs_get(long jarg1, btBroadphaseRayCallback jarg1_);
public final static native void btBroadphaseRayCallback_lambda_max_set(long jarg1, btBroadphaseRayCallback jarg1_, float jarg2);
public final static native float btBroadphaseRayCallback_lambda_max_get(long jarg1, btBroadphaseRayCallback jarg1_);
public final static native void delete_btBroadphaseRayCallback(long jarg1);
public final static native long new_btBroadphaseRayCallback();
public final static native void btBroadphaseRayCallback_director_connect(btBroadphaseRayCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btBroadphaseRayCallback_change_ownership(btBroadphaseRayCallback obj, long cptr, boolean take_or_release);
public final static native void delete_btBroadphaseInterface(long jarg1);
public final static native long btBroadphaseInterface_createProxy(long jarg1, btBroadphaseInterface jarg1_, Vector3 jarg2, Vector3 jarg3, int jarg4, long jarg5, short jarg6, short jarg7, long jarg8, btDispatcher jarg8_, long jarg9);
public final static native void btBroadphaseInterface_destroyProxy(long jarg1, btBroadphaseInterface jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native void btBroadphaseInterface_setAabb(long jarg1, btBroadphaseInterface jarg1_, long jarg2, btBroadphaseProxy jarg2_, Vector3 jarg3, Vector3 jarg4, long jarg5, btDispatcher jarg5_);
public final static native void btBroadphaseInterface_getAabb(long jarg1, btBroadphaseInterface jarg1_, long jarg2, btBroadphaseProxy jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btBroadphaseInterface_rayTest__SWIG_0(long jarg1, btBroadphaseInterface jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5, Vector3 jarg6);
public final static native void btBroadphaseInterface_rayTest__SWIG_1(long jarg1, btBroadphaseInterface jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5);
public final static native void btBroadphaseInterface_rayTest__SWIG_2(long jarg1, btBroadphaseInterface jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_);
public final static native void btBroadphaseInterface_aabbTest(long jarg1, btBroadphaseInterface jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseAabbCallback jarg4_);
public final static native void btBroadphaseInterface_calculateOverlappingPairs(long jarg1, btBroadphaseInterface jarg1_, long jarg2, btDispatcher jarg2_);
public final static native long btBroadphaseInterface_getOverlappingPairCache__SWIG_0(long jarg1, btBroadphaseInterface jarg1_);
public final static native void btBroadphaseInterface_getBroadphaseAabb(long jarg1, btBroadphaseInterface jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btBroadphaseInterface_resetPool(long jarg1, btBroadphaseInterface jarg1_, long jarg2, btDispatcher jarg2_);
public final static native void btBroadphaseInterface_printStats(long jarg1, btBroadphaseInterface jarg1_);
public final static native Vector3 btDbvtAabbMm_Center(long jarg1, btDbvtAabbMm jarg1_);
public final static native Vector3 btDbvtAabbMm_Lengths(long jarg1, btDbvtAabbMm jarg1_);
public final static native Vector3 btDbvtAabbMm_Extents(long jarg1, btDbvtAabbMm jarg1_);
public final static native Vector3 btDbvtAabbMm_Mins(long jarg1, btDbvtAabbMm jarg1_);
public final static native Vector3 btDbvtAabbMm_Maxs(long jarg1, btDbvtAabbMm jarg1_);
public final static native long btDbvtAabbMm_FromCE(Vector3 jarg1, Vector3 jarg2);
public final static native long btDbvtAabbMm_FromCR(Vector3 jarg1, float jarg2);
public final static native long btDbvtAabbMm_FromMM(Vector3 jarg1, Vector3 jarg2);
public final static native long btDbvtAabbMm_FromPoints__SWIG_0(long jarg1, btVector3 jarg1_, int jarg2);
public final static native long btDbvtAabbMm_FromPoints__SWIG_1(long jarg1, int jarg2);
public final static native void btDbvtAabbMm_Expand(long jarg1, btDbvtAabbMm jarg1_, Vector3 jarg2);
public final static native void btDbvtAabbMm_SignedExpand(long jarg1, btDbvtAabbMm jarg1_, Vector3 jarg2);
public final static native boolean btDbvtAabbMm_Contain(long jarg1, btDbvtAabbMm jarg1_, long jarg2, btDbvtAabbMm jarg2_);
public final static native int btDbvtAabbMm_Classify(long jarg1, btDbvtAabbMm jarg1_, Vector3 jarg2, float jarg3, int jarg4);
public final static native float btDbvtAabbMm_ProjectMinimum(long jarg1, btDbvtAabbMm jarg1_, Vector3 jarg2, long jarg3);
public final static native boolean Intersect__SWIG_0(long jarg1, btDbvtAabbMm jarg1_, long jarg2, btDbvtAabbMm jarg2_);
public final static native boolean Intersect__SWIG_1(long jarg1, btDbvtAabbMm jarg1_, Vector3 jarg2);
public final static native float Proximity(long jarg1, btDbvtAabbMm jarg1_, long jarg2, btDbvtAabbMm jarg2_);
public final static native int Select(long jarg1, btDbvtAabbMm jarg1_, long jarg2, btDbvtAabbMm jarg2_, long jarg3, btDbvtAabbMm jarg3_);
public final static native void Merge(long jarg1, btDbvtAabbMm jarg1_, long jarg2, btDbvtAabbMm jarg2_, long jarg3, btDbvtAabbMm jarg3_);
public final static native boolean NotEqual(long jarg1, btDbvtAabbMm jarg1_, long jarg2, btDbvtAabbMm jarg2_);
public final static native Vector3 btDbvtAabbMm_tMins(long jarg1, btDbvtAabbMm jarg1_);
public final static native Vector3 btDbvtAabbMm_tMaxs(long jarg1, btDbvtAabbMm jarg1_);
public final static native long new_btDbvtAabbMm();
public final static native void delete_btDbvtAabbMm(long jarg1);
public final static native void btDbvtNode_volume_set(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvtAabbMm jarg2_);
public final static native long btDbvtNode_volume_get(long jarg1, btDbvtNode jarg1_);
public final static native void btDbvtNode_parent_set(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvtNode_parent_get(long jarg1, btDbvtNode jarg1_);
public final static native boolean btDbvtNode_isleaf(long jarg1, btDbvtNode jarg1_);
public final static native boolean btDbvtNode_isinternal(long jarg1, btDbvtNode jarg1_);
public final static native void btDbvtNode_childs_set(long jarg1, btDbvtNode jarg1_, long jarg2);
public final static native long btDbvtNode_childs_get(long jarg1, btDbvtNode jarg1_);
public final static native void btDbvtNode_data_set(long jarg1, btDbvtNode jarg1_, long jarg2);
public final static native long btDbvtNode_data_get(long jarg1, btDbvtNode jarg1_);
public final static native void btDbvtNode_dataAsInt_set(long jarg1, btDbvtNode jarg1_, int jarg2);
public final static native int btDbvtNode_dataAsInt_get(long jarg1, btDbvtNode jarg1_);
public final static native long new_btDbvtNode();
public final static native void delete_btDbvtNode(long jarg1);
public final static native void btDbvt_sStkNN_a_set(long jarg1, btDbvt.sStkNN jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_sStkNN_a_get(long jarg1, btDbvt.sStkNN jarg1_);
public final static native void btDbvt_sStkNN_b_set(long jarg1, btDbvt.sStkNN jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_sStkNN_b_get(long jarg1, btDbvt.sStkNN jarg1_);
public final static native long new_btDbvt_sStkNN__SWIG_0();
public final static native long new_btDbvt_sStkNN__SWIG_1(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native void delete_btDbvt_sStkNN(long jarg1);
public final static native void btDbvt_sStkNP_node_set(long jarg1, btDbvt.sStkNP jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_sStkNP_node_get(long jarg1, btDbvt.sStkNP jarg1_);
public final static native void btDbvt_sStkNP_mask_set(long jarg1, btDbvt.sStkNP jarg1_, int jarg2);
public final static native int btDbvt_sStkNP_mask_get(long jarg1, btDbvt.sStkNP jarg1_);
public final static native long new_btDbvt_sStkNP(long jarg1, btDbvtNode jarg1_, long jarg2);
public final static native void delete_btDbvt_sStkNP(long jarg1);
public final static native void btDbvt_sStkNPS_node_set(long jarg1, btDbvt.sStkNPS jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_sStkNPS_node_get(long jarg1, btDbvt.sStkNPS jarg1_);
public final static native void btDbvt_sStkNPS_mask_set(long jarg1, btDbvt.sStkNPS jarg1_, int jarg2);
public final static native int btDbvt_sStkNPS_mask_get(long jarg1, btDbvt.sStkNPS jarg1_);
public final static native void btDbvt_sStkNPS_value_set(long jarg1, btDbvt.sStkNPS jarg1_, float jarg2);
public final static native float btDbvt_sStkNPS_value_get(long jarg1, btDbvt.sStkNPS jarg1_);
public final static native long new_btDbvt_sStkNPS__SWIG_0();
public final static native long new_btDbvt_sStkNPS__SWIG_1(long jarg1, btDbvtNode jarg1_, long jarg2, float jarg3);
public final static native void delete_btDbvt_sStkNPS(long jarg1);
public final static native void btDbvt_sStkCLN_node_set(long jarg1, btDbvt.sStkCLN jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_sStkCLN_node_get(long jarg1, btDbvt.sStkCLN jarg1_);
public final static native void btDbvt_sStkCLN_parent_set(long jarg1, btDbvt.sStkCLN jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_sStkCLN_parent_get(long jarg1, btDbvt.sStkCLN jarg1_);
public final static native long new_btDbvt_sStkCLN(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native void delete_btDbvt_sStkCLN(long jarg1);
public final static native void delete_btDbvt_ICollide(long jarg1);
public final static native void btDbvt_ICollide_Process__SWIG_0(long jarg1, btDbvt.ICollide jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtNode jarg3_);
public final static native void btDbvt_ICollide_Process__SWIG_1(long jarg1, btDbvt.ICollide jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native void btDbvt_ICollide_Process__SWIG_2(long jarg1, btDbvt.ICollide jarg1_, long jarg2, btDbvtNode jarg2_, float jarg3);
public final static native boolean btDbvt_ICollide_Descent(long jarg1, btDbvt.ICollide jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native boolean btDbvt_ICollide_AllLeaves(long jarg1, btDbvt.ICollide jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long new_btDbvt_ICollide();
public final static native void delete_btDbvt_IWriter(long jarg1);
public final static native void btDbvt_IWriter_Prepare(long jarg1, btDbvt.IWriter jarg1_, long jarg2, btDbvtNode jarg2_, int jarg3);
public final static native void btDbvt_IWriter_WriteNode(long jarg1, btDbvt.IWriter jarg1_, long jarg2, btDbvtNode jarg2_, int jarg3, int jarg4, int jarg5, int jarg6);
public final static native void btDbvt_IWriter_WriteLeaf(long jarg1, btDbvt.IWriter jarg1_, long jarg2, btDbvtNode jarg2_, int jarg3, int jarg4);
public final static native void delete_btDbvt_IClone(long jarg1);
public final static native void btDbvt_IClone_CloneLeaf(long jarg1, btDbvt.IClone jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long new_btDbvt_IClone();
public final static native void btDbvt_root_set(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_root_get(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_free_set(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvt_free_get(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_lkhd_set(long jarg1, btDbvt jarg1_, int jarg2);
public final static native int btDbvt_lkhd_get(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_leaves_set(long jarg1, btDbvt jarg1_, int jarg2);
public final static native int btDbvt_leaves_get(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_opath_set(long jarg1, btDbvt jarg1_, long jarg2);
public final static native long btDbvt_opath_get(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_stkStack_set(long jarg1, btDbvt jarg1_, long jarg2);
public final static native long btDbvt_stkStack_get(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_rayTestStack_set(long jarg1, btDbvt jarg1_, long jarg2);
public final static native long btDbvt_rayTestStack_get(long jarg1, btDbvt jarg1_);
public final static native long new_btDbvt();
public final static native void delete_btDbvt(long jarg1);
public final static native void btDbvt_clear(long jarg1, btDbvt jarg1_);
public final static native boolean btDbvt_empty(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_optimizeBottomUp(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_optimizeTopDown__SWIG_0(long jarg1, btDbvt jarg1_, int jarg2);
public final static native void btDbvt_optimizeTopDown__SWIG_1(long jarg1, btDbvt jarg1_);
public final static native void btDbvt_optimizeIncremental(long jarg1, btDbvt jarg1_, int jarg2);
public final static native long btDbvt_insert(long jarg1, btDbvt jarg1_, long jarg2, btDbvtAabbMm jarg2_, long jarg3);
public final static native void btDbvt_update__SWIG_0(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, int jarg3);
public final static native void btDbvt_update__SWIG_1(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native void btDbvt_update__SWIG_2(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtAabbMm jarg3_);
public final static native boolean btDbvt_update__SWIG_3(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtAabbMm jarg3_, Vector3 jarg4, float jarg5);
public final static native boolean btDbvt_update__SWIG_4(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtAabbMm jarg3_, Vector3 jarg4);
public final static native boolean btDbvt_update__SWIG_5(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtAabbMm jarg3_, float jarg4);
public final static native void btDbvt_remove(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native void btDbvt_write(long jarg1, btDbvt jarg1_, long jarg2, btDbvt.IWriter jarg2_);
public final static native void btDbvt_clone__SWIG_0(long jarg1, btDbvt jarg1_, long jarg2, btDbvt jarg2_, long jarg3, btDbvt.IClone jarg3_);
public final static native void btDbvt_clone__SWIG_1(long jarg1, btDbvt jarg1_, long jarg2, btDbvt jarg2_);
public final static native int btDbvt_maxdepth(long jarg1, btDbvtNode jarg1_);
public final static native int btDbvt_countLeaves(long jarg1, btDbvtNode jarg1_);
public final static native void btDbvt_extractLeaves(long jarg1, btDbvtNode jarg1_, long jarg2);
public final static native void btDbvt_benchmark();
public final static native void btDbvt_enumNodes(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvt.ICollide jarg2_);
public final static native void btDbvt_enumLeaves(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvt.ICollide jarg2_);
public final static native void btDbvt_collideTT(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtNode jarg3_, long jarg4, btDbvt.ICollide jarg4_);
public final static native void btDbvt_collideTTpersistentStack(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtNode jarg3_, long jarg4, btDbvt.ICollide jarg4_);
public final static native void btDbvt_collideTV(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, long jarg3, btDbvtAabbMm jarg3_, long jarg4, btDbvt.ICollide jarg4_);
public final static native void btDbvt_rayTest(long jarg1, btDbvtNode jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btDbvt.ICollide jarg4_);
public final static native void btDbvt_rayTestInternal(long jarg1, btDbvt jarg1_, long jarg2, btDbvtNode jarg2_, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, long[] jarg6, float jarg7, Vector3 jarg8, Vector3 jarg9, long jarg10, btDbvt.ICollide jarg10_);
public final static native void btDbvt_collideKDOP(long jarg1, btDbvtNode jarg1_, long jarg2, btVector3 jarg2_, java.nio.FloatBuffer jarg3, int jarg4, long jarg5, btDbvt.ICollide jarg5_);
public final static native void btDbvt_collideOCL__SWIG_0(long jarg1, btDbvtNode jarg1_, long jarg2, btVector3 jarg2_, java.nio.FloatBuffer jarg3, Vector3 jarg4, int jarg5, long jarg6, btDbvt.ICollide jarg6_, boolean jarg7);
public final static native void btDbvt_collideOCL__SWIG_1(long jarg1, btDbvtNode jarg1_, long jarg2, btVector3 jarg2_, java.nio.FloatBuffer jarg3, Vector3 jarg4, int jarg5, long jarg6, btDbvt.ICollide jarg6_);
public final static native void btDbvt_collideTU(long jarg1, btDbvtNode jarg1_, long jarg2, btDbvt.ICollide jarg2_);
public final static native int btDbvt_nearest(java.nio.IntBuffer jarg1, long jarg2, btDbvt.sStkNPS jarg2_, float jarg3, int jarg4, int jarg5);
public final static native int btDbvt_allocate(long jarg1, long jarg2, long jarg3, btDbvt.sStkNPS jarg3_);
public final static native void btQuantizedBvhNode_quantizedAabbMin_set(long jarg1, btQuantizedBvhNode jarg1_, int[] jarg2);
public final static native int[] btQuantizedBvhNode_quantizedAabbMin_get(long jarg1, btQuantizedBvhNode jarg1_);
public final static native void btQuantizedBvhNode_quantizedAabbMax_set(long jarg1, btQuantizedBvhNode jarg1_, int[] jarg2);
public final static native int[] btQuantizedBvhNode_quantizedAabbMax_get(long jarg1, btQuantizedBvhNode jarg1_);
public final static native void btQuantizedBvhNode_escapeIndexOrTriangleIndex_set(long jarg1, btQuantizedBvhNode jarg1_, int jarg2);
public final static native int btQuantizedBvhNode_escapeIndexOrTriangleIndex_get(long jarg1, btQuantizedBvhNode jarg1_);
public final static native boolean btQuantizedBvhNode_isLeafNode(long jarg1, btQuantizedBvhNode jarg1_);
public final static native int btQuantizedBvhNode_getEscapeIndex(long jarg1, btQuantizedBvhNode jarg1_);
public final static native int btQuantizedBvhNode_getTriangleIndex(long jarg1, btQuantizedBvhNode jarg1_);
public final static native int btQuantizedBvhNode_getPartId(long jarg1, btQuantizedBvhNode jarg1_);
public final static native long new_btQuantizedBvhNode();
public final static native void delete_btQuantizedBvhNode(long jarg1);
public final static native void btOptimizedBvhNode_aabbMinOrg_set(long jarg1, btOptimizedBvhNode jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btOptimizedBvhNode_aabbMinOrg_get(long jarg1, btOptimizedBvhNode jarg1_);
public final static native void btOptimizedBvhNode_aabbMaxOrg_set(long jarg1, btOptimizedBvhNode jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btOptimizedBvhNode_aabbMaxOrg_get(long jarg1, btOptimizedBvhNode jarg1_);
public final static native void btOptimizedBvhNode_escapeIndex_set(long jarg1, btOptimizedBvhNode jarg1_, int jarg2);
public final static native int btOptimizedBvhNode_escapeIndex_get(long jarg1, btOptimizedBvhNode jarg1_);
public final static native void btOptimizedBvhNode_subPart_set(long jarg1, btOptimizedBvhNode jarg1_, int jarg2);
public final static native int btOptimizedBvhNode_subPart_get(long jarg1, btOptimizedBvhNode jarg1_);
public final static native void btOptimizedBvhNode_triangleIndex_set(long jarg1, btOptimizedBvhNode jarg1_, int jarg2);
public final static native int btOptimizedBvhNode_triangleIndex_get(long jarg1, btOptimizedBvhNode jarg1_);
public final static native void btOptimizedBvhNode_padding_set(long jarg1, btOptimizedBvhNode jarg1_, String jarg2);
public final static native String btOptimizedBvhNode_padding_get(long jarg1, btOptimizedBvhNode jarg1_);
public final static native long new_btOptimizedBvhNode();
public final static native void delete_btOptimizedBvhNode(long jarg1);
public final static native void btBvhSubtreeInfo_quantizedAabbMin_set(long jarg1, btBvhSubtreeInfo jarg1_, int[] jarg2);
public final static native int[] btBvhSubtreeInfo_quantizedAabbMin_get(long jarg1, btBvhSubtreeInfo jarg1_);
public final static native void btBvhSubtreeInfo_quantizedAabbMax_set(long jarg1, btBvhSubtreeInfo jarg1_, int[] jarg2);
public final static native int[] btBvhSubtreeInfo_quantizedAabbMax_get(long jarg1, btBvhSubtreeInfo jarg1_);
public final static native void btBvhSubtreeInfo_rootNodeIndex_set(long jarg1, btBvhSubtreeInfo jarg1_, int jarg2);
public final static native int btBvhSubtreeInfo_rootNodeIndex_get(long jarg1, btBvhSubtreeInfo jarg1_);
public final static native void btBvhSubtreeInfo_subtreeSize_set(long jarg1, btBvhSubtreeInfo jarg1_, int jarg2);
public final static native int btBvhSubtreeInfo_subtreeSize_get(long jarg1, btBvhSubtreeInfo jarg1_);
public final static native void btBvhSubtreeInfo_padding_set(long jarg1, btBvhSubtreeInfo jarg1_, int[] jarg2);
public final static native int[] btBvhSubtreeInfo_padding_get(long jarg1, btBvhSubtreeInfo jarg1_);
public final static native long new_btBvhSubtreeInfo();
public final static native void btBvhSubtreeInfo_setAabbFromQuantizeNode(long jarg1, btBvhSubtreeInfo jarg1_, long jarg2, btQuantizedBvhNode jarg2_);
public final static native void delete_btBvhSubtreeInfo(long jarg1);
public final static native void delete_btNodeOverlapCallback(long jarg1);
public final static native void btNodeOverlapCallback_processNode(long jarg1, btNodeOverlapCallback jarg1_, int jarg2, int jarg3);
public final static native long new_btNodeOverlapCallback();
public final static native void btNodeOverlapCallback_director_connect(btNodeOverlapCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btNodeOverlapCallback_change_ownership(btNodeOverlapCallback obj, long cptr, boolean take_or_release);
public final static native long new_btQuantizedBvh();
public final static native void delete_btQuantizedBvh(long jarg1);
public final static native void btQuantizedBvh_setQuantizationValues__SWIG_0(long jarg1, btQuantizedBvh jarg1_, Vector3 jarg2, Vector3 jarg3, float jarg4);
public final static native void btQuantizedBvh_setQuantizationValues__SWIG_1(long jarg1, btQuantizedBvh jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native long btQuantizedBvh_getLeafNodeArray(long jarg1, btQuantizedBvh jarg1_);
public final static native void btQuantizedBvh_buildInternal(long jarg1, btQuantizedBvh jarg1_);
public final static native void btQuantizedBvh_reportAabbOverlappingNodex(long jarg1, btQuantizedBvh jarg1_, long jarg2, btNodeOverlapCallback jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btQuantizedBvh_reportRayOverlappingNodex(long jarg1, btQuantizedBvh jarg1_, long jarg2, btNodeOverlapCallback jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btQuantizedBvh_reportBoxCastOverlappingNodex(long jarg1, btQuantizedBvh jarg1_, long jarg2, btNodeOverlapCallback jarg2_, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, Vector3 jarg6);
public final static native void btQuantizedBvh_quantize(long jarg1, btQuantizedBvh jarg1_, java.nio.IntBuffer jarg2, Vector3 jarg3, int jarg4);
public final static native void btQuantizedBvh_quantizeWithClamp(long jarg1, btQuantizedBvh jarg1_, java.nio.IntBuffer jarg2, Vector3 jarg3, int jarg4);
public final static native Vector3 btQuantizedBvh_unQuantize(long jarg1, btQuantizedBvh jarg1_, java.nio.IntBuffer jarg2);
public final static native void btQuantizedBvh_setTraversalMode(long jarg1, btQuantizedBvh jarg1_, int jarg2);
public final static native long btQuantizedBvh_getQuantizedNodeArray(long jarg1, btQuantizedBvh jarg1_);
public final static native long btQuantizedBvh_getSubtreeInfoArray(long jarg1, btQuantizedBvh jarg1_);
public final static native long btQuantizedBvh_calculateSerializeBufferSize(long jarg1, btQuantizedBvh jarg1_);
public final static native boolean btQuantizedBvh_serialize__SWIG_0(long jarg1, btQuantizedBvh jarg1_, long jarg2, long jarg3, boolean jarg4);
public final static native long btQuantizedBvh_deSerializeInPlace(long jarg1, long jarg2, boolean jarg3);
public final static native long btQuantizedBvh_getAlignmentSerializationPadding();
public final static native int btQuantizedBvh_calculateSerializeBufferSizeNew(long jarg1, btQuantizedBvh jarg1_);
public final static native String btQuantizedBvh_serialize__SWIG_1(long jarg1, btQuantizedBvh jarg1_, long jarg2, long jarg3);
public final static native void btQuantizedBvh_deSerializeFloat(long jarg1, btQuantizedBvh jarg1_, long jarg2, btQuantizedBvhFloatData jarg2_);
public final static native void btQuantizedBvh_deSerializeDouble(long jarg1, btQuantizedBvh jarg1_, long jarg2, btQuantizedBvhDoubleData jarg2_);
public final static native boolean btQuantizedBvh_isQuantized(long jarg1, btQuantizedBvh jarg1_);
public final static native void btBvhSubtreeInfoData_rootNodeIndex_set(long jarg1, btBvhSubtreeInfoData jarg1_, int jarg2);
public final static native int btBvhSubtreeInfoData_rootNodeIndex_get(long jarg1, btBvhSubtreeInfoData jarg1_);
public final static native void btBvhSubtreeInfoData_subtreeSize_set(long jarg1, btBvhSubtreeInfoData jarg1_, int jarg2);
public final static native int btBvhSubtreeInfoData_subtreeSize_get(long jarg1, btBvhSubtreeInfoData jarg1_);
public final static native void btBvhSubtreeInfoData_quantizedAabbMin_set(long jarg1, btBvhSubtreeInfoData jarg1_, int[] jarg2);
public final static native int[] btBvhSubtreeInfoData_quantizedAabbMin_get(long jarg1, btBvhSubtreeInfoData jarg1_);
public final static native void btBvhSubtreeInfoData_quantizedAabbMax_set(long jarg1, btBvhSubtreeInfoData jarg1_, int[] jarg2);
public final static native int[] btBvhSubtreeInfoData_quantizedAabbMax_get(long jarg1, btBvhSubtreeInfoData jarg1_);
public final static native long new_btBvhSubtreeInfoData();
public final static native void delete_btBvhSubtreeInfoData(long jarg1);
public final static native void btOptimizedBvhNodeFloatData_aabbMinOrg_set(long jarg1, btOptimizedBvhNodeFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btOptimizedBvhNodeFloatData_aabbMinOrg_get(long jarg1, btOptimizedBvhNodeFloatData jarg1_);
public final static native void btOptimizedBvhNodeFloatData_aabbMaxOrg_set(long jarg1, btOptimizedBvhNodeFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btOptimizedBvhNodeFloatData_aabbMaxOrg_get(long jarg1, btOptimizedBvhNodeFloatData jarg1_);
public final static native void btOptimizedBvhNodeFloatData_escapeIndex_set(long jarg1, btOptimizedBvhNodeFloatData jarg1_, int jarg2);
public final static native int btOptimizedBvhNodeFloatData_escapeIndex_get(long jarg1, btOptimizedBvhNodeFloatData jarg1_);
public final static native void btOptimizedBvhNodeFloatData_subPart_set(long jarg1, btOptimizedBvhNodeFloatData jarg1_, int jarg2);
public final static native int btOptimizedBvhNodeFloatData_subPart_get(long jarg1, btOptimizedBvhNodeFloatData jarg1_);
public final static native void btOptimizedBvhNodeFloatData_triangleIndex_set(long jarg1, btOptimizedBvhNodeFloatData jarg1_, int jarg2);
public final static native int btOptimizedBvhNodeFloatData_triangleIndex_get(long jarg1, btOptimizedBvhNodeFloatData jarg1_);
public final static native void btOptimizedBvhNodeFloatData_pad_set(long jarg1, btOptimizedBvhNodeFloatData jarg1_, String jarg2);
public final static native String btOptimizedBvhNodeFloatData_pad_get(long jarg1, btOptimizedBvhNodeFloatData jarg1_);
public final static native long new_btOptimizedBvhNodeFloatData();
public final static native void delete_btOptimizedBvhNodeFloatData(long jarg1);
public final static native void btOptimizedBvhNodeDoubleData_aabbMinOrg_set(long jarg1, btOptimizedBvhNodeDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btOptimizedBvhNodeDoubleData_aabbMinOrg_get(long jarg1, btOptimizedBvhNodeDoubleData jarg1_);
public final static native void btOptimizedBvhNodeDoubleData_aabbMaxOrg_set(long jarg1, btOptimizedBvhNodeDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btOptimizedBvhNodeDoubleData_aabbMaxOrg_get(long jarg1, btOptimizedBvhNodeDoubleData jarg1_);
public final static native void btOptimizedBvhNodeDoubleData_escapeIndex_set(long jarg1, btOptimizedBvhNodeDoubleData jarg1_, int jarg2);
public final static native int btOptimizedBvhNodeDoubleData_escapeIndex_get(long jarg1, btOptimizedBvhNodeDoubleData jarg1_);
public final static native void btOptimizedBvhNodeDoubleData_subPart_set(long jarg1, btOptimizedBvhNodeDoubleData jarg1_, int jarg2);
public final static native int btOptimizedBvhNodeDoubleData_subPart_get(long jarg1, btOptimizedBvhNodeDoubleData jarg1_);
public final static native void btOptimizedBvhNodeDoubleData_triangleIndex_set(long jarg1, btOptimizedBvhNodeDoubleData jarg1_, int jarg2);
public final static native int btOptimizedBvhNodeDoubleData_triangleIndex_get(long jarg1, btOptimizedBvhNodeDoubleData jarg1_);
public final static native void btOptimizedBvhNodeDoubleData_pad_set(long jarg1, btOptimizedBvhNodeDoubleData jarg1_, String jarg2);
public final static native String btOptimizedBvhNodeDoubleData_pad_get(long jarg1, btOptimizedBvhNodeDoubleData jarg1_);
public final static native long new_btOptimizedBvhNodeDoubleData();
public final static native void delete_btOptimizedBvhNodeDoubleData(long jarg1);
public final static native void btQuantizedBvhNodeData_quantizedAabbMin_set(long jarg1, btQuantizedBvhNodeData jarg1_, int[] jarg2);
public final static native int[] btQuantizedBvhNodeData_quantizedAabbMin_get(long jarg1, btQuantizedBvhNodeData jarg1_);
public final static native void btQuantizedBvhNodeData_quantizedAabbMax_set(long jarg1, btQuantizedBvhNodeData jarg1_, int[] jarg2);
public final static native int[] btQuantizedBvhNodeData_quantizedAabbMax_get(long jarg1, btQuantizedBvhNodeData jarg1_);
public final static native void btQuantizedBvhNodeData_escapeIndexOrTriangleIndex_set(long jarg1, btQuantizedBvhNodeData jarg1_, int jarg2);
public final static native int btQuantizedBvhNodeData_escapeIndexOrTriangleIndex_get(long jarg1, btQuantizedBvhNodeData jarg1_);
public final static native long new_btQuantizedBvhNodeData();
public final static native void delete_btQuantizedBvhNodeData(long jarg1);
public final static native void btQuantizedBvhFloatData_bvhAabbMin_set(long jarg1, btQuantizedBvhFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btQuantizedBvhFloatData_bvhAabbMin_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_bvhAabbMax_set(long jarg1, btQuantizedBvhFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btQuantizedBvhFloatData_bvhAabbMax_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_bvhQuantization_set(long jarg1, btQuantizedBvhFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btQuantizedBvhFloatData_bvhQuantization_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_curNodeIndex_set(long jarg1, btQuantizedBvhFloatData jarg1_, int jarg2);
public final static native int btQuantizedBvhFloatData_curNodeIndex_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_useQuantization_set(long jarg1, btQuantizedBvhFloatData jarg1_, int jarg2);
public final static native int btQuantizedBvhFloatData_useQuantization_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_numContiguousLeafNodes_set(long jarg1, btQuantizedBvhFloatData jarg1_, int jarg2);
public final static native int btQuantizedBvhFloatData_numContiguousLeafNodes_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_numQuantizedContiguousNodes_set(long jarg1, btQuantizedBvhFloatData jarg1_, int jarg2);
public final static native int btQuantizedBvhFloatData_numQuantizedContiguousNodes_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_contiguousNodesPtr_set(long jarg1, btQuantizedBvhFloatData jarg1_, long jarg2, btOptimizedBvhNodeFloatData jarg2_);
public final static native long btQuantizedBvhFloatData_contiguousNodesPtr_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_quantizedContiguousNodesPtr_set(long jarg1, btQuantizedBvhFloatData jarg1_, long jarg2, btQuantizedBvhNodeData jarg2_);
public final static native long btQuantizedBvhFloatData_quantizedContiguousNodesPtr_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_subTreeInfoPtr_set(long jarg1, btQuantizedBvhFloatData jarg1_, long jarg2, btBvhSubtreeInfoData jarg2_);
public final static native long btQuantizedBvhFloatData_subTreeInfoPtr_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_traversalMode_set(long jarg1, btQuantizedBvhFloatData jarg1_, int jarg2);
public final static native int btQuantizedBvhFloatData_traversalMode_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native void btQuantizedBvhFloatData_numSubtreeHeaders_set(long jarg1, btQuantizedBvhFloatData jarg1_, int jarg2);
public final static native int btQuantizedBvhFloatData_numSubtreeHeaders_get(long jarg1, btQuantizedBvhFloatData jarg1_);
public final static native long new_btQuantizedBvhFloatData();
public final static native void delete_btQuantizedBvhFloatData(long jarg1);
public final static native void btQuantizedBvhDoubleData_bvhAabbMin_set(long jarg1, btQuantizedBvhDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btQuantizedBvhDoubleData_bvhAabbMin_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_bvhAabbMax_set(long jarg1, btQuantizedBvhDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btQuantizedBvhDoubleData_bvhAabbMax_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_bvhQuantization_set(long jarg1, btQuantizedBvhDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btQuantizedBvhDoubleData_bvhQuantization_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_curNodeIndex_set(long jarg1, btQuantizedBvhDoubleData jarg1_, int jarg2);
public final static native int btQuantizedBvhDoubleData_curNodeIndex_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_useQuantization_set(long jarg1, btQuantizedBvhDoubleData jarg1_, int jarg2);
public final static native int btQuantizedBvhDoubleData_useQuantization_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_numContiguousLeafNodes_set(long jarg1, btQuantizedBvhDoubleData jarg1_, int jarg2);
public final static native int btQuantizedBvhDoubleData_numContiguousLeafNodes_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_numQuantizedContiguousNodes_set(long jarg1, btQuantizedBvhDoubleData jarg1_, int jarg2);
public final static native int btQuantizedBvhDoubleData_numQuantizedContiguousNodes_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_contiguousNodesPtr_set(long jarg1, btQuantizedBvhDoubleData jarg1_, long jarg2, btOptimizedBvhNodeDoubleData jarg2_);
public final static native long btQuantizedBvhDoubleData_contiguousNodesPtr_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_quantizedContiguousNodesPtr_set(long jarg1, btQuantizedBvhDoubleData jarg1_, long jarg2, btQuantizedBvhNodeData jarg2_);
public final static native long btQuantizedBvhDoubleData_quantizedContiguousNodesPtr_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_traversalMode_set(long jarg1, btQuantizedBvhDoubleData jarg1_, int jarg2);
public final static native int btQuantizedBvhDoubleData_traversalMode_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_numSubtreeHeaders_set(long jarg1, btQuantizedBvhDoubleData jarg1_, int jarg2);
public final static native int btQuantizedBvhDoubleData_numSubtreeHeaders_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native void btQuantizedBvhDoubleData_subTreeInfoPtr_set(long jarg1, btQuantizedBvhDoubleData jarg1_, long jarg2, btBvhSubtreeInfoData jarg2_);
public final static native long btQuantizedBvhDoubleData_subTreeInfoPtr_get(long jarg1, btQuantizedBvhDoubleData jarg1_);
public final static native long new_btQuantizedBvhDoubleData();
public final static native void delete_btQuantizedBvhDoubleData(long jarg1);
public final static native void btDbvtProxy_leaf_set(long jarg1, btDbvtProxy jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btDbvtProxy_leaf_get(long jarg1, btDbvtProxy jarg1_);
public final static native void btDbvtProxy_links_set(long jarg1, btDbvtProxy jarg1_, long jarg2);
public final static native long btDbvtProxy_links_get(long jarg1, btDbvtProxy jarg1_);
public final static native void btDbvtProxy_stage_set(long jarg1, btDbvtProxy jarg1_, int jarg2);
public final static native int btDbvtProxy_stage_get(long jarg1, btDbvtProxy jarg1_);
public final static native long new_btDbvtProxy(Vector3 jarg1, Vector3 jarg2, long jarg3, short jarg4, short jarg5);
public final static native void delete_btDbvtProxy(long jarg1);
public final static native void btDbvtBroadphase_sets_set(long jarg1, btDbvtBroadphase jarg1_, long jarg2, btDbvt jarg2_);
public final static native long btDbvtBroadphase_sets_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_stageRoots_set(long jarg1, btDbvtBroadphase jarg1_, long jarg2);
public final static native long btDbvtBroadphase_stageRoots_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_paircache_set(long jarg1, btDbvtBroadphase jarg1_, long jarg2, btOverlappingPairCache jarg2_);
public final static native long btDbvtBroadphase_paircache_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_prediction_set(long jarg1, btDbvtBroadphase jarg1_, float jarg2);
public final static native float btDbvtBroadphase_prediction_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_stageCurrent_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_stageCurrent_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_fupdates_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_fupdates_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_dupdates_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_dupdates_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_cupdates_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_cupdates_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_newpairs_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_newpairs_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_fixedleft_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_fixedleft_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_updates_call_set(long jarg1, btDbvtBroadphase jarg1_, long jarg2);
public final static native long btDbvtBroadphase_updates_call_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_updates_done_set(long jarg1, btDbvtBroadphase jarg1_, long jarg2);
public final static native long btDbvtBroadphase_updates_done_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_updates_ratio_set(long jarg1, btDbvtBroadphase jarg1_, float jarg2);
public final static native float btDbvtBroadphase_updates_ratio_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_pid_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_pid_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_cid_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_cid_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_gid_set(long jarg1, btDbvtBroadphase jarg1_, int jarg2);
public final static native int btDbvtBroadphase_gid_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_releasepaircache_set(long jarg1, btDbvtBroadphase jarg1_, boolean jarg2);
public final static native boolean btDbvtBroadphase_releasepaircache_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_deferedcollide_set(long jarg1, btDbvtBroadphase jarg1_, boolean jarg2);
public final static native boolean btDbvtBroadphase_deferedcollide_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_needcleanup_set(long jarg1, btDbvtBroadphase jarg1_, boolean jarg2);
public final static native boolean btDbvtBroadphase_needcleanup_get(long jarg1, btDbvtBroadphase jarg1_);
public final static native long new_btDbvtBroadphase__SWIG_0(long jarg1, btOverlappingPairCache jarg1_);
public final static native long new_btDbvtBroadphase__SWIG_1();
public final static native void delete_btDbvtBroadphase(long jarg1);
public final static native void btDbvtBroadphase_collide(long jarg1, btDbvtBroadphase jarg1_, long jarg2, btDispatcher jarg2_);
public final static native void btDbvtBroadphase_optimize(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_rayTest__SWIG_0(long jarg1, btDbvtBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5, Vector3 jarg6);
public final static native void btDbvtBroadphase_rayTest__SWIG_1(long jarg1, btDbvtBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5);
public final static native void btDbvtBroadphase_rayTest__SWIG_2(long jarg1, btDbvtBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_);
public final static native long btDbvtBroadphase_getOverlappingPairCache__SWIG_0(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_performDeferredRemoval(long jarg1, btDbvtBroadphase jarg1_, long jarg2, btDispatcher jarg2_);
public final static native void btDbvtBroadphase_setVelocityPrediction(long jarg1, btDbvtBroadphase jarg1_, float jarg2);
public final static native float btDbvtBroadphase_getVelocityPrediction(long jarg1, btDbvtBroadphase jarg1_);
public final static native void btDbvtBroadphase_setAabbForceUpdate(long jarg1, btDbvtBroadphase jarg1_, long jarg2, btBroadphaseProxy jarg2_, Vector3 jarg3, Vector3 jarg4, long jarg5, btDispatcher jarg5_);
public final static native void btDbvtBroadphase_benchmark(long jarg1, btBroadphaseInterface jarg1_);
public final static native void btSimpleBroadphaseProxy_nextFree_set(long jarg1, btSimpleBroadphaseProxy jarg1_, int jarg2);
public final static native int btSimpleBroadphaseProxy_nextFree_get(long jarg1, btSimpleBroadphaseProxy jarg1_);
public final static native long new_btSimpleBroadphaseProxy__SWIG_0();
public final static native long new_btSimpleBroadphaseProxy__SWIG_1(Vector3 jarg1, Vector3 jarg2, int jarg3, long jarg4, short jarg5, short jarg6, long jarg7);
public final static native void btSimpleBroadphaseProxy_SetNextFree(long jarg1, btSimpleBroadphaseProxy jarg1_, int jarg2);
public final static native int btSimpleBroadphaseProxy_GetNextFree(long jarg1, btSimpleBroadphaseProxy jarg1_);
public final static native void delete_btSimpleBroadphaseProxy(long jarg1);
public final static native long new_btSimpleBroadphase__SWIG_0(int jarg1, long jarg2, btOverlappingPairCache jarg2_);
public final static native long new_btSimpleBroadphase__SWIG_1(int jarg1);
public final static native long new_btSimpleBroadphase__SWIG_2();
public final static native void delete_btSimpleBroadphase(long jarg1);
public final static native boolean btSimpleBroadphase_aabbOverlap(long jarg1, btSimpleBroadphaseProxy jarg1_, long jarg2, btSimpleBroadphaseProxy jarg2_);
public final static native void btSimpleBroadphase_rayTest__SWIG_0(long jarg1, btSimpleBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5, Vector3 jarg6);
public final static native void btSimpleBroadphase_rayTest__SWIG_1(long jarg1, btSimpleBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5);
public final static native void btSimpleBroadphase_rayTest__SWIG_2(long jarg1, btSimpleBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_);
public final static native long btSimpleBroadphase_getOverlappingPairCache__SWIG_0(long jarg1, btSimpleBroadphase jarg1_);
public final static native boolean btSimpleBroadphase_testAabbOverlap(long jarg1, btSimpleBroadphase jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native void btMultiSapBroadphase_btMultiSapProxy_aabbMin_set(long jarg1, btMultiSapBroadphase.btMultiSapProxy jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btMultiSapBroadphase_btMultiSapProxy_aabbMin_get(long jarg1, btMultiSapBroadphase.btMultiSapProxy jarg1_);
public final static native void btMultiSapBroadphase_btMultiSapProxy_aabbMax_set(long jarg1, btMultiSapBroadphase.btMultiSapProxy jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btMultiSapBroadphase_btMultiSapProxy_aabbMax_get(long jarg1, btMultiSapBroadphase.btMultiSapProxy jarg1_);
public final static native void btMultiSapBroadphase_btMultiSapProxy_shapeType_set(long jarg1, btMultiSapBroadphase.btMultiSapProxy jarg1_, int jarg2);
public final static native int btMultiSapBroadphase_btMultiSapProxy_shapeType_get(long jarg1, btMultiSapBroadphase.btMultiSapProxy jarg1_);
public final static native long new_btMultiSapBroadphase_btMultiSapProxy(Vector3 jarg1, Vector3 jarg2, int jarg3, long jarg4, short jarg5, short jarg6);
public final static native void delete_btMultiSapBroadphase_btMultiSapProxy(long jarg1);
public final static native long btMultiSapBroadphase_getBroadphaseArray__SWIG_0(long jarg1, btMultiSapBroadphase jarg1_);
public final static native void delete_btMultiSapBroadphase(long jarg1);
public final static native void btMultiSapBroadphase_rayTest__SWIG_0(long jarg1, btMultiSapBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5, Vector3 jarg6);
public final static native void btMultiSapBroadphase_rayTest__SWIG_1(long jarg1, btMultiSapBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5);
public final static native void btMultiSapBroadphase_rayTest__SWIG_2(long jarg1, btMultiSapBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_);
public final static native void btMultiSapBroadphase_addToChildBroadphase(long jarg1, btMultiSapBroadphase jarg1_, long jarg2, btMultiSapBroadphase.btMultiSapProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_, long jarg4, btBroadphaseInterface jarg4_);
public final static native boolean btMultiSapBroadphase_testAabbOverlap(long jarg1, btMultiSapBroadphase jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btMultiSapBroadphase_getOverlappingPairCache__SWIG_0(long jarg1, btMultiSapBroadphase jarg1_);
public final static native void btMultiSapBroadphase_buildTree(long jarg1, btMultiSapBroadphase jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btMultiSapBroadphase_quicksort(long jarg1, btMultiSapBroadphase jarg1_, long jarg2, btBroadphasePairArray jarg2_, int jarg3, int jarg4);
public final static native long new_btCollisionAlgorithmConstructionInfo__SWIG_0();
public final static native long new_btCollisionAlgorithmConstructionInfo__SWIG_1(long jarg1, btDispatcher jarg1_, int jarg2);
public final static native void btCollisionAlgorithmConstructionInfo_dispatcher1_set(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_, long jarg2, btDispatcher jarg2_);
public final static native long btCollisionAlgorithmConstructionInfo_dispatcher1_get(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native void btCollisionAlgorithmConstructionInfo_manifold_set(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native long btCollisionAlgorithmConstructionInfo_manifold_get(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native void delete_btCollisionAlgorithmConstructionInfo(long jarg1);
public final static native void delete_btCollisionAlgorithm(long jarg1);
public final static native void btCollisionAlgorithm_processCollision(long jarg1, btCollisionAlgorithm jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btDispatcherInfo jarg4_, long jarg5, btManifoldResult jarg5_);
public final static native float btCollisionAlgorithm_calculateTimeOfImpact(long jarg1, btCollisionAlgorithm jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_, long jarg4, btDispatcherInfo jarg4_, long jarg5, btManifoldResult jarg5_);
public final static native void btCollisionAlgorithm_getAllContactManifolds(long jarg1, btCollisionAlgorithm jarg1_, long jarg2, btPersistentManifoldArray jarg2_);
public final static native void delete_btOverlappingPairCallback(long jarg1);
public final static native long btOverlappingPairCallback_addOverlappingPair(long jarg1, btOverlappingPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btOverlappingPairCallback_removeOverlappingPair(long jarg1, btOverlappingPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_, long jarg4, btDispatcher jarg4_);
public final static native void btOverlappingPairCallback_removeOverlappingPairsContainingProxy(long jarg1, btOverlappingPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native long new_btOverlappingPairCallback();
public final static native void btOverlappingPairCallback_director_connect(btOverlappingPairCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btOverlappingPairCallback_change_ownership(btOverlappingPairCallback obj, long cptr, boolean take_or_release);
public final static native void gOverlappingPairs_set(int jarg1);
public final static native int gOverlappingPairs_get();
public final static native void btAxisSweep3InternalShort_Edge_pos_set(long jarg1, btAxisSweep3InternalShort.Edge jarg1_, int jarg2);
public final static native int btAxisSweep3InternalShort_Edge_pos_get(long jarg1, btAxisSweep3InternalShort.Edge jarg1_);
public final static native void btAxisSweep3InternalShort_Edge_handle_set(long jarg1, btAxisSweep3InternalShort.Edge jarg1_, int jarg2);
public final static native int btAxisSweep3InternalShort_Edge_handle_get(long jarg1, btAxisSweep3InternalShort.Edge jarg1_);
public final static native int btAxisSweep3InternalShort_Edge_IsMax(long jarg1, btAxisSweep3InternalShort.Edge jarg1_);
public final static native long new_btAxisSweep3InternalShort_Edge();
public final static native void delete_btAxisSweep3InternalShort_Edge(long jarg1);
public final static native void btAxisSweep3InternalShort_Handle_minEdges_set(long jarg1, btAxisSweep3InternalShort.Handle jarg1_, int[] jarg2);
public final static native int[] btAxisSweep3InternalShort_Handle_minEdges_get(long jarg1, btAxisSweep3InternalShort.Handle jarg1_);
public final static native void btAxisSweep3InternalShort_Handle_maxEdges_set(long jarg1, btAxisSweep3InternalShort.Handle jarg1_, int[] jarg2);
public final static native int[] btAxisSweep3InternalShort_Handle_maxEdges_get(long jarg1, btAxisSweep3InternalShort.Handle jarg1_);
public final static native void btAxisSweep3InternalShort_Handle_dbvtProxy_set(long jarg1, btAxisSweep3InternalShort.Handle jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native long btAxisSweep3InternalShort_Handle_dbvtProxy_get(long jarg1, btAxisSweep3InternalShort.Handle jarg1_);
public final static native void btAxisSweep3InternalShort_Handle_SetNextFree(long jarg1, btAxisSweep3InternalShort.Handle jarg1_, int jarg2);
public final static native int btAxisSweep3InternalShort_Handle_GetNextFree(long jarg1, btAxisSweep3InternalShort.Handle jarg1_);
public final static native long new_btAxisSweep3InternalShort_Handle();
public final static native void delete_btAxisSweep3InternalShort_Handle(long jarg1);
public final static native long new_btAxisSweep3InternalShort__SWIG_0(Vector3 jarg1, Vector3 jarg2, int jarg3, int jarg4, int jarg5, long jarg6, btOverlappingPairCache jarg6_, boolean jarg7);
public final static native long new_btAxisSweep3InternalShort__SWIG_1(Vector3 jarg1, Vector3 jarg2, int jarg3, int jarg4, int jarg5, long jarg6, btOverlappingPairCache jarg6_);
public final static native long new_btAxisSweep3InternalShort__SWIG_2(Vector3 jarg1, Vector3 jarg2, int jarg3, int jarg4, int jarg5);
public final static native long new_btAxisSweep3InternalShort__SWIG_3(Vector3 jarg1, Vector3 jarg2, int jarg3, int jarg4);
public final static native void delete_btAxisSweep3InternalShort(long jarg1);
public final static native int btAxisSweep3InternalShort_getNumHandles(long jarg1, btAxisSweep3InternalShort jarg1_);
public final static native int btAxisSweep3InternalShort_addHandle(long jarg1, btAxisSweep3InternalShort jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, short jarg5, short jarg6, long jarg7, btDispatcher jarg7_, long jarg8);
public final static native void btAxisSweep3InternalShort_removeHandle(long jarg1, btAxisSweep3InternalShort jarg1_, int jarg2, long jarg3, btDispatcher jarg3_);
public final static native void btAxisSweep3InternalShort_updateHandle(long jarg1, btAxisSweep3InternalShort jarg1_, int jarg2, Vector3 jarg3, Vector3 jarg4, long jarg5, btDispatcher jarg5_);
public final static native long btAxisSweep3InternalShort_getHandle(long jarg1, btAxisSweep3InternalShort jarg1_, int jarg2);
public final static native void btAxisSweep3InternalShort_rayTest__SWIG_0(long jarg1, btAxisSweep3InternalShort jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5, Vector3 jarg6);
public final static native void btAxisSweep3InternalShort_rayTest__SWIG_1(long jarg1, btAxisSweep3InternalShort jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5);
public final static native void btAxisSweep3InternalShort_rayTest__SWIG_2(long jarg1, btAxisSweep3InternalShort jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_);
public final static native void btAxisSweep3InternalShort_quantize(long jarg1, btAxisSweep3InternalShort jarg1_, java.nio.IntBuffer jarg2, Vector3 jarg3, int jarg4);
public final static native void btAxisSweep3InternalShort_unQuantize(long jarg1, btAxisSweep3InternalShort jarg1_, long jarg2, btBroadphaseProxy jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native boolean btAxisSweep3InternalShort_testAabbOverlap(long jarg1, btAxisSweep3InternalShort jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btAxisSweep3InternalShort_getOverlappingPairCache__SWIG_0(long jarg1, btAxisSweep3InternalShort jarg1_);
public final static native void btAxisSweep3InternalShort_setOverlappingPairUserCallback(long jarg1, btAxisSweep3InternalShort jarg1_, long jarg2, btOverlappingPairCallback jarg2_);
public final static native long btAxisSweep3InternalShort_getOverlappingPairUserCallback(long jarg1, btAxisSweep3InternalShort jarg1_);
public final static native void btAxisSweep3InternalInt_Edge_pos_set(long jarg1, btAxisSweep3InternalInt.Edge jarg1_, long jarg2);
public final static native long btAxisSweep3InternalInt_Edge_pos_get(long jarg1, btAxisSweep3InternalInt.Edge jarg1_);
public final static native void btAxisSweep3InternalInt_Edge_handle_set(long jarg1, btAxisSweep3InternalInt.Edge jarg1_, long jarg2);
public final static native long btAxisSweep3InternalInt_Edge_handle_get(long jarg1, btAxisSweep3InternalInt.Edge jarg1_);
public final static native long btAxisSweep3InternalInt_Edge_IsMax(long jarg1, btAxisSweep3InternalInt.Edge jarg1_);
public final static native long new_btAxisSweep3InternalInt_Edge();
public final static native void delete_btAxisSweep3InternalInt_Edge(long jarg1);
public final static native void btAxisSweep3InternalInt_Handle_minEdges_set(long jarg1, btAxisSweep3InternalInt.Handle jarg1_, long[] jarg2);
public final static native long[] btAxisSweep3InternalInt_Handle_minEdges_get(long jarg1, btAxisSweep3InternalInt.Handle jarg1_);
public final static native void btAxisSweep3InternalInt_Handle_maxEdges_set(long jarg1, btAxisSweep3InternalInt.Handle jarg1_, long[] jarg2);
public final static native long[] btAxisSweep3InternalInt_Handle_maxEdges_get(long jarg1, btAxisSweep3InternalInt.Handle jarg1_);
public final static native void btAxisSweep3InternalInt_Handle_dbvtProxy_set(long jarg1, btAxisSweep3InternalInt.Handle jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native long btAxisSweep3InternalInt_Handle_dbvtProxy_get(long jarg1, btAxisSweep3InternalInt.Handle jarg1_);
public final static native void btAxisSweep3InternalInt_Handle_SetNextFree(long jarg1, btAxisSweep3InternalInt.Handle jarg1_, long jarg2);
public final static native long btAxisSweep3InternalInt_Handle_GetNextFree(long jarg1, btAxisSweep3InternalInt.Handle jarg1_);
public final static native long new_btAxisSweep3InternalInt_Handle();
public final static native void delete_btAxisSweep3InternalInt_Handle(long jarg1);
public final static native long new_btAxisSweep3InternalInt__SWIG_0(Vector3 jarg1, Vector3 jarg2, long jarg3, long jarg4, long jarg5, long jarg6, btOverlappingPairCache jarg6_, boolean jarg7);
public final static native long new_btAxisSweep3InternalInt__SWIG_1(Vector3 jarg1, Vector3 jarg2, long jarg3, long jarg4, long jarg5, long jarg6, btOverlappingPairCache jarg6_);
public final static native long new_btAxisSweep3InternalInt__SWIG_2(Vector3 jarg1, Vector3 jarg2, long jarg3, long jarg4, long jarg5);
public final static native long new_btAxisSweep3InternalInt__SWIG_3(Vector3 jarg1, Vector3 jarg2, long jarg3, long jarg4);
public final static native void delete_btAxisSweep3InternalInt(long jarg1);
public final static native long btAxisSweep3InternalInt_getNumHandles(long jarg1, btAxisSweep3InternalInt jarg1_);
public final static native long btAxisSweep3InternalInt_addHandle(long jarg1, btAxisSweep3InternalInt jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, short jarg5, short jarg6, long jarg7, btDispatcher jarg7_, long jarg8);
public final static native void btAxisSweep3InternalInt_removeHandle(long jarg1, btAxisSweep3InternalInt jarg1_, long jarg2, long jarg3, btDispatcher jarg3_);
public final static native void btAxisSweep3InternalInt_updateHandle(long jarg1, btAxisSweep3InternalInt jarg1_, long jarg2, Vector3 jarg3, Vector3 jarg4, long jarg5, btDispatcher jarg5_);
public final static native long btAxisSweep3InternalInt_getHandle(long jarg1, btAxisSweep3InternalInt jarg1_, long jarg2);
public final static native void btAxisSweep3InternalInt_rayTest__SWIG_0(long jarg1, btAxisSweep3InternalInt jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5, Vector3 jarg6);
public final static native void btAxisSweep3InternalInt_rayTest__SWIG_1(long jarg1, btAxisSweep3InternalInt jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_, Vector3 jarg5);
public final static native void btAxisSweep3InternalInt_rayTest__SWIG_2(long jarg1, btAxisSweep3InternalInt jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, btBroadphaseRayCallback jarg4_);
public final static native void btAxisSweep3InternalInt_quantize(long jarg1, btAxisSweep3InternalInt jarg1_, java.nio.LongBuffer jarg2, Vector3 jarg3, int jarg4);
public final static native void btAxisSweep3InternalInt_unQuantize(long jarg1, btAxisSweep3InternalInt jarg1_, long jarg2, btBroadphaseProxy jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native boolean btAxisSweep3InternalInt_testAabbOverlap(long jarg1, btAxisSweep3InternalInt jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btAxisSweep3InternalInt_getOverlappingPairCache__SWIG_0(long jarg1, btAxisSweep3InternalInt jarg1_);
public final static native void btAxisSweep3InternalInt_setOverlappingPairUserCallback(long jarg1, btAxisSweep3InternalInt jarg1_, long jarg2, btOverlappingPairCallback jarg2_);
public final static native long btAxisSweep3InternalInt_getOverlappingPairUserCallback(long jarg1, btAxisSweep3InternalInt jarg1_);
public final static native long new_btAxisSweep3__SWIG_0(Vector3 jarg1, Vector3 jarg2, int jarg3, long jarg4, btOverlappingPairCache jarg4_, boolean jarg5);
public final static native long new_btAxisSweep3__SWIG_1(Vector3 jarg1, Vector3 jarg2, int jarg3, long jarg4, btOverlappingPairCache jarg4_);
public final static native long new_btAxisSweep3__SWIG_2(Vector3 jarg1, Vector3 jarg2, int jarg3);
public final static native long new_btAxisSweep3__SWIG_3(Vector3 jarg1, Vector3 jarg2);
public final static native void delete_btAxisSweep3(long jarg1);
public final static native long new_bt32BitAxisSweep3__SWIG_0(Vector3 jarg1, Vector3 jarg2, long jarg3, long jarg4, btOverlappingPairCache jarg4_, boolean jarg5);
public final static native long new_bt32BitAxisSweep3__SWIG_1(Vector3 jarg1, Vector3 jarg2, long jarg3, long jarg4, btOverlappingPairCache jarg4_);
public final static native long new_bt32BitAxisSweep3__SWIG_2(Vector3 jarg1, Vector3 jarg2, long jarg3);
public final static native long new_bt32BitAxisSweep3__SWIG_3(Vector3 jarg1, Vector3 jarg2);
public final static native void delete_bt32BitAxisSweep3(long jarg1);
public final static native long new_btDispatcherInfo();
public final static native void btDispatcherInfo_timeStep_set(long jarg1, btDispatcherInfo jarg1_, float jarg2);
public final static native float btDispatcherInfo_timeStep_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_stepCount_set(long jarg1, btDispatcherInfo jarg1_, int jarg2);
public final static native int btDispatcherInfo_stepCount_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_dispatchFunc_set(long jarg1, btDispatcherInfo jarg1_, int jarg2);
public final static native int btDispatcherInfo_dispatchFunc_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_timeOfImpact_set(long jarg1, btDispatcherInfo jarg1_, float jarg2);
public final static native float btDispatcherInfo_timeOfImpact_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_useContinuous_set(long jarg1, btDispatcherInfo jarg1_, boolean jarg2);
public final static native boolean btDispatcherInfo_useContinuous_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_debugDraw_set(long jarg1, btDispatcherInfo jarg1_, long jarg2, btIDebugDraw jarg2_);
public final static native long btDispatcherInfo_debugDraw_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_enableSatConvex_set(long jarg1, btDispatcherInfo jarg1_, boolean jarg2);
public final static native boolean btDispatcherInfo_enableSatConvex_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_enableSPU_set(long jarg1, btDispatcherInfo jarg1_, boolean jarg2);
public final static native boolean btDispatcherInfo_enableSPU_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_useEpa_set(long jarg1, btDispatcherInfo jarg1_, boolean jarg2);
public final static native boolean btDispatcherInfo_useEpa_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_allowedCcdPenetration_set(long jarg1, btDispatcherInfo jarg1_, float jarg2);
public final static native float btDispatcherInfo_allowedCcdPenetration_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_useConvexConservativeDistanceUtil_set(long jarg1, btDispatcherInfo jarg1_, boolean jarg2);
public final static native boolean btDispatcherInfo_useConvexConservativeDistanceUtil_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void btDispatcherInfo_convexConservativeDistanceThreshold_set(long jarg1, btDispatcherInfo jarg1_, float jarg2);
public final static native float btDispatcherInfo_convexConservativeDistanceThreshold_get(long jarg1, btDispatcherInfo jarg1_);
public final static native void delete_btDispatcherInfo(long jarg1);
public final static native void delete_btDispatcher(long jarg1);
public final static native long btDispatcher_findAlgorithm__SWIG_0(long jarg1, btDispatcher jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btPersistentManifold jarg4_);
public final static native long btDispatcher_findAlgorithm__SWIG_1(long jarg1, btDispatcher jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_);
public final static native long btDispatcher_getNewManifold(long jarg1, btDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void btDispatcher_releaseManifold(long jarg1, btDispatcher jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native void btDispatcher_clearManifold(long jarg1, btDispatcher jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native boolean btDispatcher_needsCollision(long jarg1, btDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native boolean btDispatcher_needsResponse(long jarg1, btDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void btDispatcher_dispatchAllCollisionPairs(long jarg1, btDispatcher jarg1_, long jarg2, btOverlappingPairCache jarg2_, long jarg3, btDispatcherInfo jarg3_, long jarg4, btDispatcher jarg4_);
public final static native int btDispatcher_getNumManifolds(long jarg1, btDispatcher jarg1_);
public final static native long btDispatcher_getManifoldByIndexInternal(long jarg1, btDispatcher jarg1_, int jarg2);
public final static native long btDispatcher_getInternalManifoldPointer(long jarg1, btDispatcher jarg1_);
public final static native long btDispatcher_getInternalManifoldPool__SWIG_0(long jarg1, btDispatcher jarg1_);
public final static native long btDispatcher_allocateCollisionAlgorithm(long jarg1, btDispatcher jarg1_, int jarg2);
public final static native void btDispatcher_freeCollisionAlgorithm(long jarg1, btDispatcher jarg1_, long jarg2);
public final static native void delete_btOverlapCallback(long jarg1);
public final static native boolean btOverlapCallback_processOverlap(long jarg1, btOverlapCallback jarg1_, btBroadphasePair jarg2);
public final static native long new_btOverlapCallback();
public final static native void btOverlapCallback_director_connect(btOverlapCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btOverlapCallback_change_ownership(btOverlapCallback obj, long cptr, boolean take_or_release);
public final static native void delete_btOverlapFilterCallback(long jarg1);
public final static native boolean btOverlapFilterCallback_needBroadphaseCollision(long jarg1, btOverlapFilterCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long new_btOverlapFilterCallback();
public final static native void btOverlapFilterCallback_director_connect(btOverlapFilterCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btOverlapFilterCallback_change_ownership(btOverlapFilterCallback obj, long cptr, boolean take_or_release);
public final static native void gRemovePairs_set(int jarg1);
public final static native int gRemovePairs_get();
public final static native void gAddedPairs_set(int jarg1);
public final static native int gAddedPairs_get();
public final static native void gFindPairs_set(int jarg1);
public final static native int gFindPairs_get();
public final static native int BT_NULL_PAIR_get();
public final static native void delete_btOverlappingPairCache(long jarg1);
public final static native long btOverlappingPairCache_getOverlappingPairArrayPtr__SWIG_0(long jarg1, btOverlappingPairCache jarg1_);
public final static native long btOverlappingPairCache_getOverlappingPairArray(long jarg1, btOverlappingPairCache jarg1_);
public final static native void btOverlappingPairCache_cleanOverlappingPair(long jarg1, btOverlappingPairCache jarg1_, btBroadphasePair jarg2, long jarg3, btDispatcher jarg3_);
public final static native int btOverlappingPairCache_getNumOverlappingPairs(long jarg1, btOverlappingPairCache jarg1_);
public final static native void btOverlappingPairCache_cleanProxyFromPairs(long jarg1, btOverlappingPairCache jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native void btOverlappingPairCache_setOverlapFilterCallback(long jarg1, btOverlappingPairCache jarg1_, long jarg2, btOverlapFilterCallback jarg2_);
public final static native void btOverlappingPairCache_processAllOverlappingPairs(long jarg1, btOverlappingPairCache jarg1_, long jarg2, btOverlapCallback jarg2_, long jarg3, btDispatcher jarg3_);
public final static native long btOverlappingPairCache_findPair(long jarg1, btOverlappingPairCache jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native boolean btOverlappingPairCache_hasDeferredRemoval(long jarg1, btOverlappingPairCache jarg1_);
public final static native void btOverlappingPairCache_setInternalGhostPairCallback(long jarg1, btOverlappingPairCache jarg1_, long jarg2, btOverlappingPairCallback jarg2_);
public final static native void btOverlappingPairCache_sortOverlappingPairs(long jarg1, btOverlappingPairCache jarg1_, long jarg2, btDispatcher jarg2_);
public final static native long new_btHashedOverlappingPairCache();
public final static native void delete_btHashedOverlappingPairCache(long jarg1);
public final static native boolean btHashedOverlappingPairCache_needsBroadphaseCollision(long jarg1, btHashedOverlappingPairCache jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btHashedOverlappingPairCache_getOverlappingPairArrayPtr__SWIG_0(long jarg1, btHashedOverlappingPairCache jarg1_);
public final static native long btHashedOverlappingPairCache_getOverlappingPairArray__SWIG_0(long jarg1, btHashedOverlappingPairCache jarg1_);
public final static native int btHashedOverlappingPairCache_GetCount(long jarg1, btHashedOverlappingPairCache jarg1_);
public final static native long btHashedOverlappingPairCache_getOverlapFilterCallback(long jarg1, btHashedOverlappingPairCache jarg1_);
public final static native long new_btSortedOverlappingPairCache();
public final static native void delete_btSortedOverlappingPairCache(long jarg1);
public final static native boolean btSortedOverlappingPairCache_needsBroadphaseCollision(long jarg1, btSortedOverlappingPairCache jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btSortedOverlappingPairCache_getOverlappingPairArray__SWIG_0(long jarg1, btSortedOverlappingPairCache jarg1_);
public final static native long btSortedOverlappingPairCache_getOverlappingPairArrayPtr__SWIG_0(long jarg1, btSortedOverlappingPairCache jarg1_);
public final static native long btSortedOverlappingPairCache_getOverlapFilterCallback(long jarg1, btSortedOverlappingPairCache jarg1_);
public final static native long btNullPairCache_getOverlappingPairArrayPtr__SWIG_0(long jarg1, btNullPairCache jarg1_);
public final static native long new_btNullPairCache();
public final static native void delete_btNullPairCache(long jarg1);
public final static native void delete_btCollisionShape(long jarg1);
public final static native void btCollisionShape_getAabb(long jarg1, btCollisionShape jarg1_, Matrix4 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native void btCollisionShape_getBoundingSphere(long jarg1, btCollisionShape jarg1_, Vector3 jarg2, long jarg3);
public final static native float btCollisionShape_getAngularMotionDisc(long jarg1, btCollisionShape jarg1_);
public final static native float btCollisionShape_getContactBreakingThreshold(long jarg1, btCollisionShape jarg1_, float jarg2);
public final static native void btCollisionShape_calculateTemporalAabb(long jarg1, btCollisionShape jarg1_, Matrix4 jarg2, Vector3 jarg3, Vector3 jarg4, float jarg5, Vector3 jarg6, Vector3 jarg7);
public final static native boolean btCollisionShape_isPolyhedral(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isConvex2d(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isConvex(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isNonMoving(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isConcave(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isCompound(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isSoftBody(long jarg1, btCollisionShape jarg1_);
public final static native boolean btCollisionShape_isInfinite(long jarg1, btCollisionShape jarg1_);
public final static native void btCollisionShape_setLocalScaling(long jarg1, btCollisionShape jarg1_, Vector3 jarg2);
public final static native Vector3 btCollisionShape_getLocalScaling(long jarg1, btCollisionShape jarg1_);
public final static native void btCollisionShape_calculateLocalInertia(long jarg1, btCollisionShape jarg1_, float jarg2, Vector3 jarg3);
public final static native String btCollisionShape_getName(long jarg1, btCollisionShape jarg1_);
public final static native int btCollisionShape_getShapeType(long jarg1, btCollisionShape jarg1_);
public final static native Vector3 btCollisionShape_getAnisotropicRollingFrictionDirection(long jarg1, btCollisionShape jarg1_);
public final static native void btCollisionShape_setMargin(long jarg1, btCollisionShape jarg1_, float jarg2);
public final static native float btCollisionShape_getMargin(long jarg1, btCollisionShape jarg1_);
public final static native void btCollisionShape_setUserPointer(long jarg1, btCollisionShape jarg1_, long jarg2);
public final static native long btCollisionShape_getUserPointer(long jarg1, btCollisionShape jarg1_);
public final static native int btCollisionShape_calculateSerializeBufferSize(long jarg1, btCollisionShape jarg1_);
public final static native String btCollisionShape_serialize(long jarg1, btCollisionShape jarg1_, long jarg2, long jarg3);
public final static native void btCollisionShape_serializeSingleShape(long jarg1, btCollisionShape jarg1_, long jarg2);
public final static native void btCollisionShapeData_name_set(long jarg1, btCollisionShapeData jarg1_, String jarg2);
public final static native String btCollisionShapeData_name_get(long jarg1, btCollisionShapeData jarg1_);
public final static native void btCollisionShapeData_shapeType_set(long jarg1, btCollisionShapeData jarg1_, int jarg2);
public final static native int btCollisionShapeData_shapeType_get(long jarg1, btCollisionShapeData jarg1_);
public final static native void btCollisionShapeData_padding_set(long jarg1, btCollisionShapeData jarg1_, String jarg2);
public final static native String btCollisionShapeData_padding_get(long jarg1, btCollisionShapeData jarg1_);
public final static native long new_btCollisionShapeData();
public final static native void delete_btCollisionShapeData(long jarg1);
public final static native void delete_btConvexShape(long jarg1);
public final static native Vector3 btConvexShape_localGetSupportingVertex(long jarg1, btConvexShape jarg1_, Vector3 jarg2);
public final static native Vector3 btConvexShape_localGetSupportingVertexWithoutMargin(long jarg1, btConvexShape jarg1_, Vector3 jarg2);
public final static native Vector3 btConvexShape_localGetSupportVertexWithoutMarginNonVirtual(long jarg1, btConvexShape jarg1_, Vector3 jarg2);
public final static native Vector3 btConvexShape_localGetSupportVertexNonVirtual(long jarg1, btConvexShape jarg1_, Vector3 jarg2);
public final static native float btConvexShape_getMarginNonVirtual(long jarg1, btConvexShape jarg1_);
public final static native void btConvexShape_getAabbNonVirtual(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native void btConvexShape_project(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, Vector3 jarg3, long jarg4, long jarg5);
public final static native void btConvexShape_batchedUnitVectorGetSupportingVertexWithoutMargin(long jarg1, btConvexShape jarg1_, long jarg2, btVector3 jarg2_, long jarg3, btVector3 jarg3_, int jarg4);
public final static native void btConvexShape_getAabbSlow(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native int btConvexShape_getNumPreferredPenetrationDirections(long jarg1, btConvexShape jarg1_);
public final static native void btConvexShape_getPreferredPenetrationDirection(long jarg1, btConvexShape jarg1_, int jarg2, Vector3 jarg3);
public final static native void delete_btConvexInternalShape(long jarg1);
public final static native Vector3 btConvexInternalShape_getImplicitShapeDimensions(long jarg1, btConvexInternalShape jarg1_);
public final static native void btConvexInternalShape_setImplicitShapeDimensions(long jarg1, btConvexInternalShape jarg1_, Vector3 jarg2);
public final static native void btConvexInternalShape_setSafeMargin__SWIG_0(long jarg1, btConvexInternalShape jarg1_, float jarg2, float jarg3);
public final static native void btConvexInternalShape_setSafeMargin__SWIG_1(long jarg1, btConvexInternalShape jarg1_, float jarg2);
public final static native void btConvexInternalShape_setSafeMargin__SWIG_2(long jarg1, btConvexInternalShape jarg1_, Vector3 jarg2, float jarg3);
public final static native void btConvexInternalShape_setSafeMargin__SWIG_3(long jarg1, btConvexInternalShape jarg1_, Vector3 jarg2);
public final static native Vector3 btConvexInternalShape_getLocalScalingNV(long jarg1, btConvexInternalShape jarg1_);
public final static native float btConvexInternalShape_getMarginNV(long jarg1, btConvexInternalShape jarg1_);
public final static native void btConvexInternalShapeData_collisionShapeData_set(long jarg1, btConvexInternalShapeData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btConvexInternalShapeData_collisionShapeData_get(long jarg1, btConvexInternalShapeData jarg1_);
public final static native void btConvexInternalShapeData_localScaling_set(long jarg1, btConvexInternalShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btConvexInternalShapeData_localScaling_get(long jarg1, btConvexInternalShapeData jarg1_);
public final static native void btConvexInternalShapeData_implicitShapeDimensions_set(long jarg1, btConvexInternalShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btConvexInternalShapeData_implicitShapeDimensions_get(long jarg1, btConvexInternalShapeData jarg1_);
public final static native void btConvexInternalShapeData_collisionMargin_set(long jarg1, btConvexInternalShapeData jarg1_, float jarg2);
public final static native float btConvexInternalShapeData_collisionMargin_get(long jarg1, btConvexInternalShapeData jarg1_);
public final static native void btConvexInternalShapeData_padding_set(long jarg1, btConvexInternalShapeData jarg1_, int jarg2);
public final static native int btConvexInternalShapeData_padding_get(long jarg1, btConvexInternalShapeData jarg1_);
public final static native long new_btConvexInternalShapeData();
public final static native void delete_btConvexInternalShapeData(long jarg1);
public final static native void btConvexInternalAabbCachingShape_recalcLocalAabb(long jarg1, btConvexInternalAabbCachingShape jarg1_);
public final static native void delete_btConvexInternalAabbCachingShape(long jarg1);
public final static native void delete_btPolyhedralConvexShape(long jarg1);
public final static native boolean btPolyhedralConvexShape_initializePolyhedralFeatures__SWIG_0(long jarg1, btPolyhedralConvexShape jarg1_, int jarg2);
public final static native boolean btPolyhedralConvexShape_initializePolyhedralFeatures__SWIG_1(long jarg1, btPolyhedralConvexShape jarg1_);
public final static native long btPolyhedralConvexShape_getConvexPolyhedron(long jarg1, btPolyhedralConvexShape jarg1_);
public final static native int btPolyhedralConvexShape_getNumVertices(long jarg1, btPolyhedralConvexShape jarg1_);
public final static native int btPolyhedralConvexShape_getNumEdges(long jarg1, btPolyhedralConvexShape jarg1_);
public final static native void btPolyhedralConvexShape_getEdge(long jarg1, btPolyhedralConvexShape jarg1_, int jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native void btPolyhedralConvexShape_getVertex(long jarg1, btPolyhedralConvexShape jarg1_, int jarg2, Vector3 jarg3);
public final static native int btPolyhedralConvexShape_getNumPlanes(long jarg1, btPolyhedralConvexShape jarg1_);
public final static native void btPolyhedralConvexShape_getPlane(long jarg1, btPolyhedralConvexShape jarg1_, Vector3 jarg2, Vector3 jarg3, int jarg4);
public final static native boolean btPolyhedralConvexShape_isInside(long jarg1, btPolyhedralConvexShape jarg1_, Vector3 jarg2, float jarg3);
public final static native void btPolyhedralConvexAabbCachingShape_getNonvirtualAabb(long jarg1, btPolyhedralConvexAabbCachingShape jarg1_, Matrix4 jarg2, Vector3 jarg3, Vector3 jarg4, float jarg5);
public final static native void btPolyhedralConvexAabbCachingShape_recalcLocalAabb(long jarg1, btPolyhedralConvexAabbCachingShape jarg1_);
public final static native void delete_btPolyhedralConvexAabbCachingShape(long jarg1);
public final static native void delete_btConcaveShape(long jarg1);
public final static native void btConcaveShape_processAllTriangles(long jarg1, btConcaveShape jarg1_, long jarg2, btTriangleCallback jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void delete_btTriangleCallback(long jarg1);
public final static native void btTriangleCallback_processTriangle(long jarg1, btTriangleCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native long new_btTriangleCallback();
public final static native void btTriangleCallback_director_connect(btTriangleCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btTriangleCallback_change_ownership(btTriangleCallback obj, long cptr, boolean take_or_release);
public final static native void delete_btInternalTriangleIndexCallback(long jarg1);
public final static native void btInternalTriangleIndexCallback_internalProcessTriangleIndex(long jarg1, btInternalTriangleIndexCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native long new_btInternalTriangleIndexCallback();
public final static native void btInternalTriangleIndexCallback_director_connect(btInternalTriangleIndexCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btInternalTriangleIndexCallback_change_ownership(btInternalTriangleIndexCallback obj, long cptr, boolean take_or_release);
public final static native long new_btTriangleInfo();
public final static native void btTriangleInfo_flags_set(long jarg1, btTriangleInfo jarg1_, int jarg2);
public final static native int btTriangleInfo_flags_get(long jarg1, btTriangleInfo jarg1_);
public final static native void btTriangleInfo_edgeV0V1Angle_set(long jarg1, btTriangleInfo jarg1_, float jarg2);
public final static native float btTriangleInfo_edgeV0V1Angle_get(long jarg1, btTriangleInfo jarg1_);
public final static native void btTriangleInfo_edgeV1V2Angle_set(long jarg1, btTriangleInfo jarg1_, float jarg2);
public final static native float btTriangleInfo_edgeV1V2Angle_get(long jarg1, btTriangleInfo jarg1_);
public final static native void btTriangleInfo_edgeV2V0Angle_set(long jarg1, btTriangleInfo jarg1_, float jarg2);
public final static native float btTriangleInfo_edgeV2V0Angle_get(long jarg1, btTriangleInfo jarg1_);
public final static native void delete_btTriangleInfo(long jarg1);
public final static native void btTriangleInfoMap_convexEpsilon_set(long jarg1, btTriangleInfoMap jarg1_, float jarg2);
public final static native float btTriangleInfoMap_convexEpsilon_get(long jarg1, btTriangleInfoMap jarg1_);
public final static native void btTriangleInfoMap_planarEpsilon_set(long jarg1, btTriangleInfoMap jarg1_, float jarg2);
public final static native float btTriangleInfoMap_planarEpsilon_get(long jarg1, btTriangleInfoMap jarg1_);
public final static native void btTriangleInfoMap_equalVertexThreshold_set(long jarg1, btTriangleInfoMap jarg1_, float jarg2);
public final static native float btTriangleInfoMap_equalVertexThreshold_get(long jarg1, btTriangleInfoMap jarg1_);
public final static native void btTriangleInfoMap_edgeDistanceThreshold_set(long jarg1, btTriangleInfoMap jarg1_, float jarg2);
public final static native float btTriangleInfoMap_edgeDistanceThreshold_get(long jarg1, btTriangleInfoMap jarg1_);
public final static native void btTriangleInfoMap_maxEdgeAngleThreshold_set(long jarg1, btTriangleInfoMap jarg1_, float jarg2);
public final static native float btTriangleInfoMap_maxEdgeAngleThreshold_get(long jarg1, btTriangleInfoMap jarg1_);
public final static native void btTriangleInfoMap_zeroAreaThreshold_set(long jarg1, btTriangleInfoMap jarg1_, float jarg2);
public final static native float btTriangleInfoMap_zeroAreaThreshold_get(long jarg1, btTriangleInfoMap jarg1_);
public final static native long new_btTriangleInfoMap();
public final static native void delete_btTriangleInfoMap(long jarg1);
public final static native int btTriangleInfoMap_calculateSerializeBufferSize(long jarg1, btTriangleInfoMap jarg1_);
public final static native String btTriangleInfoMap_serialize(long jarg1, btTriangleInfoMap jarg1_, long jarg2, long jarg3);
public final static native void btTriangleInfoMap_deSerialize(long jarg1, btTriangleInfoMap jarg1_, long jarg2, btTriangleInfoMapData jarg2_);
public final static native void btTriangleInfoData_flags_set(long jarg1, btTriangleInfoData jarg1_, int jarg2);
public final static native int btTriangleInfoData_flags_get(long jarg1, btTriangleInfoData jarg1_);
public final static native void btTriangleInfoData_edgeV0V1Angle_set(long jarg1, btTriangleInfoData jarg1_, float jarg2);
public final static native float btTriangleInfoData_edgeV0V1Angle_get(long jarg1, btTriangleInfoData jarg1_);
public final static native void btTriangleInfoData_edgeV1V2Angle_set(long jarg1, btTriangleInfoData jarg1_, float jarg2);
public final static native float btTriangleInfoData_edgeV1V2Angle_get(long jarg1, btTriangleInfoData jarg1_);
public final static native void btTriangleInfoData_edgeV2V0Angle_set(long jarg1, btTriangleInfoData jarg1_, float jarg2);
public final static native float btTriangleInfoData_edgeV2V0Angle_get(long jarg1, btTriangleInfoData jarg1_);
public final static native long new_btTriangleInfoData();
public final static native void delete_btTriangleInfoData(long jarg1);
public final static native void btTriangleInfoMapData_hashTablePtr_set(long jarg1, btTriangleInfoMapData jarg1_, java.nio.IntBuffer jarg2);
public final static native java.nio.IntBuffer btTriangleInfoMapData_hashTablePtr_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_nextPtr_set(long jarg1, btTriangleInfoMapData jarg1_, java.nio.IntBuffer jarg2);
public final static native java.nio.IntBuffer btTriangleInfoMapData_nextPtr_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_valueArrayPtr_set(long jarg1, btTriangleInfoMapData jarg1_, long jarg2, btTriangleInfoData jarg2_);
public final static native long btTriangleInfoMapData_valueArrayPtr_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_keyArrayPtr_set(long jarg1, btTriangleInfoMapData jarg1_, java.nio.IntBuffer jarg2);
public final static native java.nio.IntBuffer btTriangleInfoMapData_keyArrayPtr_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_convexEpsilon_set(long jarg1, btTriangleInfoMapData jarg1_, float jarg2);
public final static native float btTriangleInfoMapData_convexEpsilon_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_planarEpsilon_set(long jarg1, btTriangleInfoMapData jarg1_, float jarg2);
public final static native float btTriangleInfoMapData_planarEpsilon_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_equalVertexThreshold_set(long jarg1, btTriangleInfoMapData jarg1_, float jarg2);
public final static native float btTriangleInfoMapData_equalVertexThreshold_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_edgeDistanceThreshold_set(long jarg1, btTriangleInfoMapData jarg1_, float jarg2);
public final static native float btTriangleInfoMapData_edgeDistanceThreshold_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_zeroAreaThreshold_set(long jarg1, btTriangleInfoMapData jarg1_, float jarg2);
public final static native float btTriangleInfoMapData_zeroAreaThreshold_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_nextSize_set(long jarg1, btTriangleInfoMapData jarg1_, int jarg2);
public final static native int btTriangleInfoMapData_nextSize_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_hashTableSize_set(long jarg1, btTriangleInfoMapData jarg1_, int jarg2);
public final static native int btTriangleInfoMapData_hashTableSize_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_numValues_set(long jarg1, btTriangleInfoMapData jarg1_, int jarg2);
public final static native int btTriangleInfoMapData_numValues_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_numKeys_set(long jarg1, btTriangleInfoMapData jarg1_, int jarg2);
public final static native int btTriangleInfoMapData_numKeys_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native void btTriangleInfoMapData_padding_set(long jarg1, btTriangleInfoMapData jarg1_, String jarg2);
public final static native String btTriangleInfoMapData_padding_get(long jarg1, btTriangleInfoMapData jarg1_);
public final static native long new_btTriangleInfoMapData();
public final static native void delete_btTriangleInfoMapData(long jarg1);
public final static native long new_btStaticPlaneShape(Vector3 jarg1, float jarg2);
public final static native void delete_btStaticPlaneShape(long jarg1);
public final static native Vector3 btStaticPlaneShape_getPlaneNormal(long jarg1, btStaticPlaneShape jarg1_);
public final static native float btStaticPlaneShape_getPlaneConstant(long jarg1, btStaticPlaneShape jarg1_);
public final static native void btStaticPlaneShapeData_collisionShapeData_set(long jarg1, btStaticPlaneShapeData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btStaticPlaneShapeData_collisionShapeData_get(long jarg1, btStaticPlaneShapeData jarg1_);
public final static native void btStaticPlaneShapeData_localScaling_set(long jarg1, btStaticPlaneShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btStaticPlaneShapeData_localScaling_get(long jarg1, btStaticPlaneShapeData jarg1_);
public final static native void btStaticPlaneShapeData_planeNormal_set(long jarg1, btStaticPlaneShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btStaticPlaneShapeData_planeNormal_get(long jarg1, btStaticPlaneShapeData jarg1_);
public final static native void btStaticPlaneShapeData_planeConstant_set(long jarg1, btStaticPlaneShapeData jarg1_, float jarg2);
public final static native float btStaticPlaneShapeData_planeConstant_get(long jarg1, btStaticPlaneShapeData jarg1_);
public final static native void btStaticPlaneShapeData_pad_set(long jarg1, btStaticPlaneShapeData jarg1_, String jarg2);
public final static native String btStaticPlaneShapeData_pad_get(long jarg1, btStaticPlaneShapeData jarg1_);
public final static native long new_btStaticPlaneShapeData();
public final static native void delete_btStaticPlaneShapeData(long jarg1);
public final static native void delete_btHeightfieldTerrainShape(long jarg1);
public final static native void btHeightfieldTerrainShape_setUseDiamondSubdivision__SWIG_0(long jarg1, btHeightfieldTerrainShape jarg1_, boolean jarg2);
public final static native void btHeightfieldTerrainShape_setUseDiamondSubdivision__SWIG_1(long jarg1, btHeightfieldTerrainShape jarg1_);
public final static native void btHeightfieldTerrainShape_setUseZigzagSubdivision__SWIG_0(long jarg1, btHeightfieldTerrainShape jarg1_, boolean jarg2);
public final static native void btHeightfieldTerrainShape_setUseZigzagSubdivision__SWIG_1(long jarg1, btHeightfieldTerrainShape jarg1_);
public final static native long new_btHeightfieldTerrainShape__SWIG_0(int jarg1, int jarg2, java.nio.FloatBuffer jarg3, float jarg4, float jarg5, float jarg6, int jarg7, boolean jarg8);
public final static native long new_btHeightfieldTerrainShape__SWIG_1(int jarg1, int jarg2, java.nio.ShortBuffer jarg3, float jarg4, float jarg5, float jarg6, int jarg7, boolean jarg8);
public final static native void delete_btTriangleMeshShape(long jarg1);
public final static native Vector3 btTriangleMeshShape_localGetSupportingVertex(long jarg1, btTriangleMeshShape jarg1_, Vector3 jarg2);
public final static native Vector3 btTriangleMeshShape_localGetSupportingVertexWithoutMargin(long jarg1, btTriangleMeshShape jarg1_, Vector3 jarg2);
public final static native void btTriangleMeshShape_recalcLocalAabb(long jarg1, btTriangleMeshShape jarg1_);
public final static native long btTriangleMeshShape_getMeshInterface__SWIG_0(long jarg1, btTriangleMeshShape jarg1_);
public final static native Vector3 btTriangleMeshShape_getLocalAabbMin(long jarg1, btTriangleMeshShape jarg1_);
public final static native Vector3 btTriangleMeshShape_getLocalAabbMax(long jarg1, btTriangleMeshShape jarg1_);
public final static native void delete_btBvhTriangleMeshShape(long jarg1);
public final static native boolean btBvhTriangleMeshShape_getOwnsBvh(long jarg1, btBvhTriangleMeshShape jarg1_);
public final static native void btBvhTriangleMeshShape_performRaycast(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2, btTriangleCallback jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btBvhTriangleMeshShape_performConvexcast(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2, btTriangleCallback jarg2_, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, Vector3 jarg6);
public final static native void btBvhTriangleMeshShape_refitTree(long jarg1, btBvhTriangleMeshShape jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btBvhTriangleMeshShape_partialRefitTree(long jarg1, btBvhTriangleMeshShape jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native long btBvhTriangleMeshShape_getOptimizedBvh(long jarg1, btBvhTriangleMeshShape jarg1_);
public final static native void btBvhTriangleMeshShape_setOptimizedBvh__SWIG_0(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2, btOptimizedBvh jarg2_, Vector3 jarg3);
public final static native void btBvhTriangleMeshShape_setOptimizedBvh__SWIG_1(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2, btOptimizedBvh jarg2_);
public final static native void btBvhTriangleMeshShape_buildOptimizedBvh(long jarg1, btBvhTriangleMeshShape jarg1_);
public final static native boolean btBvhTriangleMeshShape_usesQuantizedAabbCompression(long jarg1, btBvhTriangleMeshShape jarg1_);
public final static native void btBvhTriangleMeshShape_setTriangleInfoMap(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2, btTriangleInfoMap jarg2_);
public final static native long btBvhTriangleMeshShape_getTriangleInfoMap__SWIG_0(long jarg1, btBvhTriangleMeshShape jarg1_);
public final static native void btBvhTriangleMeshShape_serializeSingleBvh(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2);
public final static native void btBvhTriangleMeshShape_serializeSingleTriangleInfoMap(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2);
public final static native long new_btBvhTriangleMeshShape__SWIG_0(boolean jarg1, long jarg2, btStridingMeshInterface jarg2_, boolean jarg3, boolean jarg4);
public final static native long new_btBvhTriangleMeshShape__SWIG_1(boolean jarg1, long jarg2, btStridingMeshInterface jarg2_, boolean jarg3);
public final static native long new_btBvhTriangleMeshShape__SWIG_2(boolean jarg1, long jarg2, btStridingMeshInterface jarg2_, boolean jarg3, Vector3 jarg4, Vector3 jarg5, boolean jarg6);
public final static native long new_btBvhTriangleMeshShape__SWIG_3(boolean jarg1, long jarg2, btStridingMeshInterface jarg2_, boolean jarg3, Vector3 jarg4, Vector3 jarg5);
public final static native void btTriangleMeshShapeData_collisionShapeData_set(long jarg1, btTriangleMeshShapeData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btTriangleMeshShapeData_collisionShapeData_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native void btTriangleMeshShapeData_meshInterface_set(long jarg1, btTriangleMeshShapeData jarg1_, long jarg2, btStridingMeshInterfaceData jarg2_);
public final static native long btTriangleMeshShapeData_meshInterface_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native void btTriangleMeshShapeData_quantizedFloatBvh_set(long jarg1, btTriangleMeshShapeData jarg1_, long jarg2, btQuantizedBvhFloatData jarg2_);
public final static native long btTriangleMeshShapeData_quantizedFloatBvh_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native void btTriangleMeshShapeData_quantizedDoubleBvh_set(long jarg1, btTriangleMeshShapeData jarg1_, long jarg2, btQuantizedBvhDoubleData jarg2_);
public final static native long btTriangleMeshShapeData_quantizedDoubleBvh_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native void btTriangleMeshShapeData_triangleInfoMap_set(long jarg1, btTriangleMeshShapeData jarg1_, long jarg2, btTriangleInfoMapData jarg2_);
public final static native long btTriangleMeshShapeData_triangleInfoMap_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native void btTriangleMeshShapeData_collisionMargin_set(long jarg1, btTriangleMeshShapeData jarg1_, float jarg2);
public final static native float btTriangleMeshShapeData_collisionMargin_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native void btTriangleMeshShapeData_pad3_set(long jarg1, btTriangleMeshShapeData jarg1_, String jarg2);
public final static native String btTriangleMeshShapeData_pad3_get(long jarg1, btTriangleMeshShapeData jarg1_);
public final static native long new_btTriangleMeshShapeData();
public final static native void delete_btTriangleMeshShapeData(long jarg1);
public final static native Vector3 btBoxShape_getHalfExtentsWithMargin(long jarg1, btBoxShape jarg1_);
public final static native Vector3 btBoxShape_getHalfExtentsWithoutMargin(long jarg1, btBoxShape jarg1_);
public final static native long new_btBoxShape(Vector3 jarg1);
public final static native void btBoxShape_getPlaneEquation(long jarg1, btBoxShape jarg1_, long jarg2, btVector4 jarg2_, int jarg3);
public final static native void delete_btBoxShape(long jarg1);
public final static native long new_btCapsuleShape__SWIG_1(float jarg1, float jarg2);
public final static native int btCapsuleShape_getUpAxis(long jarg1, btCapsuleShape jarg1_);
public final static native float btCapsuleShape_getRadius(long jarg1, btCapsuleShape jarg1_);
public final static native float btCapsuleShape_getHalfHeight(long jarg1, btCapsuleShape jarg1_);
public final static native void delete_btCapsuleShape(long jarg1);
public final static native long new_btCapsuleShapeX(float jarg1, float jarg2);
public final static native void delete_btCapsuleShapeX(long jarg1);
public final static native long new_btCapsuleShapeZ(float jarg1, float jarg2);
public final static native void delete_btCapsuleShapeZ(long jarg1);
public final static native void btCapsuleShapeData_convexInternalShapeData_set(long jarg1, btCapsuleShapeData jarg1_, long jarg2, btConvexInternalShapeData jarg2_);
public final static native long btCapsuleShapeData_convexInternalShapeData_get(long jarg1, btCapsuleShapeData jarg1_);
public final static native void btCapsuleShapeData_upAxis_set(long jarg1, btCapsuleShapeData jarg1_, int jarg2);
public final static native int btCapsuleShapeData_upAxis_get(long jarg1, btCapsuleShapeData jarg1_);
public final static native void btCapsuleShapeData_padding_set(long jarg1, btCapsuleShapeData jarg1_, String jarg2);
public final static native String btCapsuleShapeData_padding_get(long jarg1, btCapsuleShapeData jarg1_);
public final static native long new_btCapsuleShapeData();
public final static native void delete_btCapsuleShapeData(long jarg1);
public final static native Vector3 btBox2dShape_getHalfExtentsWithMargin(long jarg1, btBox2dShape jarg1_);
public final static native Vector3 btBox2dShape_getHalfExtentsWithoutMargin(long jarg1, btBox2dShape jarg1_);
public final static native long new_btBox2dShape(Vector3 jarg1);
public final static native int btBox2dShape_getVertexCount(long jarg1, btBox2dShape jarg1_);
public final static native long btBox2dShape_getVertices(long jarg1, btBox2dShape jarg1_);
public final static native long btBox2dShape_getNormals(long jarg1, btBox2dShape jarg1_);
public final static native Vector3 btBox2dShape_getCentroid(long jarg1, btBox2dShape jarg1_);
public final static native void btBox2dShape_getPlaneEquation(long jarg1, btBox2dShape jarg1_, long jarg2, btVector4 jarg2_, int jarg3);
public final static native void delete_btBox2dShape(long jarg1);
public final static native void btTriangleShape_vertices1_set(long jarg1, btTriangleShape jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btTriangleShape_vertices1_get(long jarg1, btTriangleShape jarg1_);
public final static native Vector3 btTriangleShape_getVertexPtr__SWIG_0(long jarg1, btTriangleShape jarg1_, int jarg2);
public final static native long new_btTriangleShape__SWIG_0();
public final static native long new_btTriangleShape__SWIG_1(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3);
public final static native void btTriangleShape_calcNormal(long jarg1, btTriangleShape jarg1_, Vector3 jarg2);
public final static native void btTriangleShape_getPlaneEquation(long jarg1, btTriangleShape jarg1_, int jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native void delete_btTriangleShape(long jarg1);
public final static native long new_btSphereShape(float jarg1);
public final static native float btSphereShape_getRadius(long jarg1, btSphereShape jarg1_);
public final static native void btSphereShape_setUnscaledRadius(long jarg1, btSphereShape jarg1_, float jarg2);
public final static native void delete_btSphereShape(long jarg1);
public final static native void delete_btStridingMeshInterface(long jarg1);
public final static native void btStridingMeshInterface_InternalProcessAllTriangles(long jarg1, btStridingMeshInterface jarg1_, long jarg2, btInternalTriangleIndexCallback jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btStridingMeshInterface_calculateAabbBruteForce(long jarg1, btStridingMeshInterface jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btStridingMeshInterface_getLockedVertexIndexBase__SWIG_0(long jarg1, btStridingMeshInterface jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9, int jarg10);
public final static native void btStridingMeshInterface_getLockedVertexIndexBase__SWIG_1(long jarg1, btStridingMeshInterface jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9);
public final static native void btStridingMeshInterface_getLockedReadOnlyVertexIndexBase__SWIG_0(long jarg1, btStridingMeshInterface jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9, int jarg10);
public final static native void btStridingMeshInterface_getLockedReadOnlyVertexIndexBase__SWIG_1(long jarg1, btStridingMeshInterface jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9);
public final static native void btStridingMeshInterface_unLockVertexBase(long jarg1, btStridingMeshInterface jarg1_, int jarg2);
public final static native void btStridingMeshInterface_unLockReadOnlyVertexBase(long jarg1, btStridingMeshInterface jarg1_, int jarg2);
public final static native int btStridingMeshInterface_getNumSubParts(long jarg1, btStridingMeshInterface jarg1_);
public final static native void btStridingMeshInterface_preallocateVertices(long jarg1, btStridingMeshInterface jarg1_, int jarg2);
public final static native void btStridingMeshInterface_preallocateIndices(long jarg1, btStridingMeshInterface jarg1_, int jarg2);
public final static native boolean btStridingMeshInterface_hasPremadeAabb(long jarg1, btStridingMeshInterface jarg1_);
public final static native void btStridingMeshInterface_setPremadeAabb(long jarg1, btStridingMeshInterface jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btStridingMeshInterface_getPremadeAabb(long jarg1, btStridingMeshInterface jarg1_, long jarg2, btVector3 jarg2_, long jarg3, btVector3 jarg3_);
public final static native Vector3 btStridingMeshInterface_getScaling(long jarg1, btStridingMeshInterface jarg1_);
public final static native void btStridingMeshInterface_setScaling(long jarg1, btStridingMeshInterface jarg1_, Vector3 jarg2);
public final static native int btStridingMeshInterface_calculateSerializeBufferSize(long jarg1, btStridingMeshInterface jarg1_);
public final static native String btStridingMeshInterface_serialize(long jarg1, btStridingMeshInterface jarg1_, long jarg2, long jarg3);
public final static native void btIntIndexData_value_set(long jarg1, btIntIndexData jarg1_, int jarg2);
public final static native int btIntIndexData_value_get(long jarg1, btIntIndexData jarg1_);
public final static native long new_btIntIndexData();
public final static native void delete_btIntIndexData(long jarg1);
public final static native void btShortIntIndexData_value_set(long jarg1, btShortIntIndexData jarg1_, short jarg2);
public final static native short btShortIntIndexData_value_get(long jarg1, btShortIntIndexData jarg1_);
public final static native void btShortIntIndexData_pad_set(long jarg1, btShortIntIndexData jarg1_, String jarg2);
public final static native String btShortIntIndexData_pad_get(long jarg1, btShortIntIndexData jarg1_);
public final static native long new_btShortIntIndexData();
public final static native void delete_btShortIntIndexData(long jarg1);
public final static native void btShortIntIndexTripletData_values_set(long jarg1, btShortIntIndexTripletData jarg1_, short[] jarg2);
public final static native short[] btShortIntIndexTripletData_values_get(long jarg1, btShortIntIndexTripletData jarg1_);
public final static native void btShortIntIndexTripletData_pad_set(long jarg1, btShortIntIndexTripletData jarg1_, String jarg2);
public final static native String btShortIntIndexTripletData_pad_get(long jarg1, btShortIntIndexTripletData jarg1_);
public final static native long new_btShortIntIndexTripletData();
public final static native void delete_btShortIntIndexTripletData(long jarg1);
public final static native void btCharIndexTripletData_values_set(long jarg1, btCharIndexTripletData jarg1_, short[] jarg2);
public final static native short[] btCharIndexTripletData_values_get(long jarg1, btCharIndexTripletData jarg1_);
public final static native void btCharIndexTripletData_pad_set(long jarg1, btCharIndexTripletData jarg1_, char jarg2);
public final static native char btCharIndexTripletData_pad_get(long jarg1, btCharIndexTripletData jarg1_);
public final static native long new_btCharIndexTripletData();
public final static native void delete_btCharIndexTripletData(long jarg1);
public final static native void btMeshPartData_vertices3f_set(long jarg1, btMeshPartData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btMeshPartData_vertices3f_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_vertices3d_set(long jarg1, btMeshPartData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btMeshPartData_vertices3d_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_indices32_set(long jarg1, btMeshPartData jarg1_, long jarg2, btIntIndexData jarg2_);
public final static native long btMeshPartData_indices32_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_3indices16_set(long jarg1, btMeshPartData jarg1_, long jarg2, btShortIntIndexTripletData jarg2_);
public final static native long btMeshPartData_3indices16_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_3indices8_set(long jarg1, btMeshPartData jarg1_, long jarg2, btCharIndexTripletData jarg2_);
public final static native long btMeshPartData_3indices8_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_indices16_set(long jarg1, btMeshPartData jarg1_, long jarg2, btShortIntIndexData jarg2_);
public final static native long btMeshPartData_indices16_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_numTriangles_set(long jarg1, btMeshPartData jarg1_, int jarg2);
public final static native int btMeshPartData_numTriangles_get(long jarg1, btMeshPartData jarg1_);
public final static native void btMeshPartData_numVertices_set(long jarg1, btMeshPartData jarg1_, int jarg2);
public final static native int btMeshPartData_numVertices_get(long jarg1, btMeshPartData jarg1_);
public final static native long new_btMeshPartData();
public final static native void delete_btMeshPartData(long jarg1);
public final static native void btStridingMeshInterfaceData_meshPartsPtr_set(long jarg1, btStridingMeshInterfaceData jarg1_, long jarg2, btMeshPartData jarg2_);
public final static native long btStridingMeshInterfaceData_meshPartsPtr_get(long jarg1, btStridingMeshInterfaceData jarg1_);
public final static native void btStridingMeshInterfaceData_scaling_set(long jarg1, btStridingMeshInterfaceData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btStridingMeshInterfaceData_scaling_get(long jarg1, btStridingMeshInterfaceData jarg1_);
public final static native void btStridingMeshInterfaceData_numMeshParts_set(long jarg1, btStridingMeshInterfaceData jarg1_, int jarg2);
public final static native int btStridingMeshInterfaceData_numMeshParts_get(long jarg1, btStridingMeshInterfaceData jarg1_);
public final static native void btStridingMeshInterfaceData_padding_set(long jarg1, btStridingMeshInterfaceData jarg1_, String jarg2);
public final static native String btStridingMeshInterfaceData_padding_get(long jarg1, btStridingMeshInterfaceData jarg1_);
public final static native long new_btStridingMeshInterfaceData();
public final static native void delete_btStridingMeshInterfaceData(long jarg1);
public final static native long new_btMinkowskiSumShape(long jarg1, btConvexShape jarg1_, long jarg2, btConvexShape jarg2_);
public final static native void btMinkowskiSumShape_setTransformA(long jarg1, btMinkowskiSumShape jarg1_, Matrix4 jarg2);
public final static native void btMinkowskiSumShape_setTransformB(long jarg1, btMinkowskiSumShape jarg1_, Matrix4 jarg2);
public final static native Matrix4 btMinkowskiSumShape_getTransformA(long jarg1, btMinkowskiSumShape jarg1_);
public final static native Matrix4 btMinkowskiSumShape_GetTransformB(long jarg1, btMinkowskiSumShape jarg1_);
public final static native long btMinkowskiSumShape_getShapeA(long jarg1, btMinkowskiSumShape jarg1_);
public final static native long btMinkowskiSumShape_getShapeB(long jarg1, btMinkowskiSumShape jarg1_);
public final static native void delete_btMinkowskiSumShape(long jarg1);
public final static native void btFace_indices_set(long jarg1, btFace jarg1_, long jarg2);
public final static native long btFace_indices_get(long jarg1, btFace jarg1_);
public final static native void btFace_plane_set(long jarg1, btFace jarg1_, float[] jarg2);
public final static native float[] btFace_plane_get(long jarg1, btFace jarg1_);
public final static native long new_btFace();
public final static native void delete_btFace(long jarg1);
public final static native long new_btConvexPolyhedron();
public final static native void delete_btConvexPolyhedron(long jarg1);
public final static native void btConvexPolyhedron_vertices_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btVector3Array jarg2_);
public final static native long btConvexPolyhedron_vertices_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_faces_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2);
public final static native long btConvexPolyhedron_faces_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_uniqueEdges_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btVector3Array jarg2_);
public final static native long btConvexPolyhedron_uniqueEdges_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_localCenter_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btConvexPolyhedron_localCenter_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_extents_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btConvexPolyhedron_extents_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_radius_set(long jarg1, btConvexPolyhedron jarg1_, float jarg2);
public final static native float btConvexPolyhedron_radius_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_mC_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btConvexPolyhedron_mC_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_mE_set(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btConvexPolyhedron_mE_get(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_initialize(long jarg1, btConvexPolyhedron jarg1_);
public final static native boolean btConvexPolyhedron_testContainment(long jarg1, btConvexPolyhedron jarg1_);
public final static native void btConvexPolyhedron_project(long jarg1, btConvexPolyhedron jarg1_, Matrix4 jarg2, Vector3 jarg3, long jarg4, long jarg5, Vector3 jarg6, Vector3 jarg7);
public final static native long new_btOptimizedBvh();
public final static native void delete_btOptimizedBvh(long jarg1);
public final static native void btOptimizedBvh_build(long jarg1, btOptimizedBvh jarg1_, long jarg2, btStridingMeshInterface jarg2_, boolean jarg3, Vector3 jarg4, Vector3 jarg5);
public final static native void btOptimizedBvh_refit(long jarg1, btOptimizedBvh jarg1_, long jarg2, btStridingMeshInterface jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btOptimizedBvh_refitPartial(long jarg1, btOptimizedBvh jarg1_, long jarg2, btStridingMeshInterface jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void btOptimizedBvh_updateBvhNodes(long jarg1, btOptimizedBvh jarg1_, long jarg2, btStridingMeshInterface jarg2_, int jarg3, int jarg4, int jarg5);
public final static native boolean btOptimizedBvh_serializeInPlace(long jarg1, btOptimizedBvh jarg1_, long jarg2, long jarg3, boolean jarg4);
public final static native long btOptimizedBvh_deSerializeInPlace(long jarg1, long jarg2, boolean jarg3);
public final static native void btTriangle_vertex0_set(long jarg1, btTriangle jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btTriangle_vertex0_get(long jarg1, btTriangle jarg1_);
public final static native void btTriangle_vertex1_set(long jarg1, btTriangle jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btTriangle_vertex1_get(long jarg1, btTriangle jarg1_);
public final static native void btTriangle_vertex2_set(long jarg1, btTriangle jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btTriangle_vertex2_get(long jarg1, btTriangle jarg1_);
public final static native void btTriangle_partId_set(long jarg1, btTriangle jarg1_, int jarg2);
public final static native int btTriangle_partId_get(long jarg1, btTriangle jarg1_);
public final static native void btTriangle_triangleIndex_set(long jarg1, btTriangle jarg1_, int jarg2);
public final static native int btTriangle_triangleIndex_get(long jarg1, btTriangle jarg1_);
public final static native long new_btTriangle();
public final static native void delete_btTriangle(long jarg1);
public final static native int btTriangleBuffer_getNumTriangles(long jarg1, btTriangleBuffer jarg1_);
public final static native long btTriangleBuffer_getTriangle(long jarg1, btTriangleBuffer jarg1_, int jarg2);
public final static native void btTriangleBuffer_clearBuffer(long jarg1, btTriangleBuffer jarg1_);
public final static native long new_btTriangleBuffer();
public final static native void delete_btTriangleBuffer(long jarg1);
public final static native void btIndexedMesh_numTriangles_set(long jarg1, btIndexedMesh jarg1_, int jarg2);
public final static native int btIndexedMesh_numTriangles_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_triangleIndexBase_set(long jarg1, btIndexedMesh jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btIndexedMesh_triangleIndexBase_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_triangleIndexStride_set(long jarg1, btIndexedMesh jarg1_, int jarg2);
public final static native int btIndexedMesh_triangleIndexStride_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_numVertices_set(long jarg1, btIndexedMesh jarg1_, int jarg2);
public final static native int btIndexedMesh_numVertices_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_vertexBase_set(long jarg1, btIndexedMesh jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btIndexedMesh_vertexBase_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_vertexStride_set(long jarg1, btIndexedMesh jarg1_, int jarg2);
public final static native int btIndexedMesh_vertexStride_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_indexType_set(long jarg1, btIndexedMesh jarg1_, int jarg2);
public final static native int btIndexedMesh_indexType_get(long jarg1, btIndexedMesh jarg1_);
public final static native void btIndexedMesh_vertexType_set(long jarg1, btIndexedMesh jarg1_, int jarg2);
public final static native int btIndexedMesh_vertexType_get(long jarg1, btIndexedMesh jarg1_);
public final static native long new_btIndexedMesh();
public final static native void btIndexedMesh_setTriangleIndexBase(long jarg1, btIndexedMesh jarg1_, java.nio.ShortBuffer jarg2);
public final static native void btIndexedMesh_setVertexBase(long jarg1, btIndexedMesh jarg1_, java.nio.FloatBuffer jarg2);
public final static native void btIndexedMesh_setVertices(long jarg1, btIndexedMesh jarg1_, java.nio.FloatBuffer jarg2, int jarg3, int jarg4, int jarg5);
public final static native void btIndexedMesh_setIndices(long jarg1, btIndexedMesh jarg1_, java.nio.ShortBuffer jarg2, int jarg3, int jarg4);
public final static native void delete_btIndexedMesh(long jarg1);
public final static native long new_btTriangleIndexVertexArray();
public final static native void delete_btTriangleIndexVertexArray(long jarg1);
public final static native void btTriangleIndexVertexArray_internalAddIndexedMesh__SWIG_0(long jarg1, btTriangleIndexVertexArray jarg1_, long jarg2, btIndexedMesh jarg2_, int jarg3);
public final static native void btTriangleIndexVertexArray_internalAddIndexedMesh__SWIG_1(long jarg1, btTriangleIndexVertexArray jarg1_, long jarg2, btIndexedMesh jarg2_);
public final static native void btTriangleIndexVertexArray_getLockedVertexIndexBase__SWIG_0(long jarg1, btTriangleIndexVertexArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9, int jarg10);
public final static native void btTriangleIndexVertexArray_getLockedVertexIndexBase__SWIG_1(long jarg1, btTriangleIndexVertexArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9);
public final static native void btTriangleIndexVertexArray_getLockedReadOnlyVertexIndexBase__SWIG_0(long jarg1, btTriangleIndexVertexArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9, int jarg10);
public final static native void btTriangleIndexVertexArray_getLockedReadOnlyVertexIndexBase__SWIG_1(long jarg1, btTriangleIndexVertexArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9);
public final static native long btTriangleIndexVertexArray_getIndexedMeshArray(long jarg1, btTriangleIndexVertexArray jarg1_);
public final static native void btMaterial_friction_set(long jarg1, btMaterial jarg1_, float jarg2);
public final static native float btMaterial_friction_get(long jarg1, btMaterial jarg1_);
public final static native void btMaterial_restitution_set(long jarg1, btMaterial jarg1_, float jarg2);
public final static native float btMaterial_restitution_get(long jarg1, btMaterial jarg1_);
public final static native void btMaterial_pad_set(long jarg1, btMaterial jarg1_, int[] jarg2);
public final static native int[] btMaterial_pad_get(long jarg1, btMaterial jarg1_);
public final static native long new_btMaterial__SWIG_0();
public final static native long new_btMaterial__SWIG_1(float jarg1, float jarg2);
public final static native void delete_btMaterial(long jarg1);
public final static native long new_btScaledBvhTriangleMeshShape(long jarg1, btBvhTriangleMeshShape jarg1_, Vector3 jarg2);
public final static native void delete_btScaledBvhTriangleMeshShape(long jarg1);
public final static native long btScaledBvhTriangleMeshShape_getChildShape__SWIG_0(long jarg1, btScaledBvhTriangleMeshShape jarg1_);
public final static native void btScaledTriangleMeshShapeData_trimeshShapeData_set(long jarg1, btScaledTriangleMeshShapeData jarg1_, long jarg2, btTriangleMeshShapeData jarg2_);
public final static native long btScaledTriangleMeshShapeData_trimeshShapeData_get(long jarg1, btScaledTriangleMeshShapeData jarg1_);
public final static native void btScaledTriangleMeshShapeData_localScaling_set(long jarg1, btScaledTriangleMeshShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btScaledTriangleMeshShapeData_localScaling_get(long jarg1, btScaledTriangleMeshShapeData jarg1_);
public final static native long new_btScaledTriangleMeshShapeData();
public final static native void delete_btScaledTriangleMeshShapeData(long jarg1);
public final static native long new_btShapeHull(long jarg1, btConvexShape jarg1_);
public final static native void delete_btShapeHull(long jarg1);
public final static native boolean btShapeHull_buildHull(long jarg1, btShapeHull jarg1_, float jarg2);
public final static native int btShapeHull_numTriangles(long jarg1, btShapeHull jarg1_);
public final static native int btShapeHull_numVertices(long jarg1, btShapeHull jarg1_);
public final static native int btShapeHull_numIndices(long jarg1, btShapeHull jarg1_);
public final static native long btShapeHull_getVertexPointer(long jarg1, btShapeHull jarg1_);
public final static native java.nio.LongBuffer btShapeHull_getIndexPointer(long jarg1, btShapeHull jarg1_);
public final static native long new_btConvexHullShape__SWIG_0(java.nio.FloatBuffer jarg1, int jarg2, int jarg3);
public final static native long new_btConvexHullShape__SWIG_1(java.nio.FloatBuffer jarg1, int jarg2);
public final static native long new_btConvexHullShape__SWIG_2(java.nio.FloatBuffer jarg1);
public final static native long new_btConvexHullShape__SWIG_3();
public final static native void btConvexHullShape_addPoint__SWIG_0(long jarg1, btConvexHullShape jarg1_, Vector3 jarg2, boolean jarg3);
public final static native void btConvexHullShape_addPoint__SWIG_1(long jarg1, btConvexHullShape jarg1_, Vector3 jarg2);
public final static native long btConvexHullShape_getUnscaledPoints__SWIG_0(long jarg1, btConvexHullShape jarg1_);
public final static native long btConvexHullShape_getPoints(long jarg1, btConvexHullShape jarg1_);
public final static native Vector3 btConvexHullShape_getScaledPoint(long jarg1, btConvexHullShape jarg1_, int jarg2);
public final static native int btConvexHullShape_getNumPoints(long jarg1, btConvexHullShape jarg1_);
public final static native void btConvexHullShape_project(long jarg1, btConvexHullShape jarg1_, Matrix4 jarg2, Vector3 jarg3, long jarg4, long jarg5, Vector3 jarg6, Vector3 jarg7);
public final static native long new_btConvexHullShape__SWIG_4(long jarg1, btShapeHull jarg1_);
public final static native void delete_btConvexHullShape(long jarg1);
public final static native void btConvexHullShapeData_convexInternalShapeData_set(long jarg1, btConvexHullShapeData jarg1_, long jarg2, btConvexInternalShapeData jarg2_);
public final static native long btConvexHullShapeData_convexInternalShapeData_get(long jarg1, btConvexHullShapeData jarg1_);
public final static native void btConvexHullShapeData_unscaledPointsFloatPtr_set(long jarg1, btConvexHullShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btConvexHullShapeData_unscaledPointsFloatPtr_get(long jarg1, btConvexHullShapeData jarg1_);
public final static native void btConvexHullShapeData_unscaledPointsDoublePtr_set(long jarg1, btConvexHullShapeData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btConvexHullShapeData_unscaledPointsDoublePtr_get(long jarg1, btConvexHullShapeData jarg1_);
public final static native void btConvexHullShapeData_numUnscaledPoints_set(long jarg1, btConvexHullShapeData jarg1_, int jarg2);
public final static native int btConvexHullShapeData_numUnscaledPoints_get(long jarg1, btConvexHullShapeData jarg1_);
public final static native void btConvexHullShapeData_padding3_set(long jarg1, btConvexHullShapeData jarg1_, String jarg2);
public final static native String btConvexHullShapeData_padding3_get(long jarg1, btConvexHullShapeData jarg1_);
public final static native long new_btConvexHullShapeData();
public final static native void delete_btConvexHullShapeData(long jarg1);
public final static native void btMaterialProperties_numMaterials_set(long jarg1, btMaterialProperties jarg1_, int jarg2);
public final static native int btMaterialProperties_numMaterials_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_materialBase_set(long jarg1, btMaterialProperties jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btMaterialProperties_materialBase_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_materialStride_set(long jarg1, btMaterialProperties jarg1_, int jarg2);
public final static native int btMaterialProperties_materialStride_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_materialType_set(long jarg1, btMaterialProperties jarg1_, int jarg2);
public final static native int btMaterialProperties_materialType_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_numTriangles_set(long jarg1, btMaterialProperties jarg1_, int jarg2);
public final static native int btMaterialProperties_numTriangles_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_triangleMaterialsBase_set(long jarg1, btMaterialProperties jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btMaterialProperties_triangleMaterialsBase_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_triangleMaterialStride_set(long jarg1, btMaterialProperties jarg1_, int jarg2);
public final static native int btMaterialProperties_triangleMaterialStride_get(long jarg1, btMaterialProperties jarg1_);
public final static native void btMaterialProperties_triangleType_set(long jarg1, btMaterialProperties jarg1_, int jarg2);
public final static native int btMaterialProperties_triangleType_get(long jarg1, btMaterialProperties jarg1_);
public final static native long new_btMaterialProperties();
public final static native void delete_btMaterialProperties(long jarg1);
public final static native long new_btTriangleIndexVertexMaterialArray__SWIG_0();
public final static native long new_btTriangleIndexVertexMaterialArray__SWIG_1(int jarg1, java.nio.IntBuffer jarg2, int jarg3, int jarg4, java.nio.FloatBuffer jarg5, int jarg6, int jarg7, java.nio.ByteBuffer jarg8, int jarg9, java.nio.IntBuffer jarg10, int jarg11);
public final static native void delete_btTriangleIndexVertexMaterialArray(long jarg1);
public final static native void btTriangleIndexVertexMaterialArray_addMaterialProperties__SWIG_0(long jarg1, btTriangleIndexVertexMaterialArray jarg1_, long jarg2, btMaterialProperties jarg2_, int jarg3);
public final static native void btTriangleIndexVertexMaterialArray_addMaterialProperties__SWIG_1(long jarg1, btTriangleIndexVertexMaterialArray jarg1_, long jarg2, btMaterialProperties jarg2_);
public final static native void btTriangleIndexVertexMaterialArray_getLockedMaterialBase__SWIG_0(long jarg1, btTriangleIndexVertexMaterialArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9, int jarg10);
public final static native void btTriangleIndexVertexMaterialArray_getLockedMaterialBase__SWIG_1(long jarg1, btTriangleIndexVertexMaterialArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9);
public final static native void btTriangleIndexVertexMaterialArray_getLockedReadOnlyMaterialBase__SWIG_0(long jarg1, btTriangleIndexVertexMaterialArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9, int jarg10);
public final static native void btTriangleIndexVertexMaterialArray_getLockedReadOnlyMaterialBase__SWIG_1(long jarg1, btTriangleIndexVertexMaterialArray jarg1_, long jarg2, long jarg3, long jarg4, long jarg5, long jarg6, long jarg7, long jarg8, long jarg9);
public final static native Vector3 btCylinderShape_getHalfExtentsWithMargin(long jarg1, btCylinderShape jarg1_);
public final static native Vector3 btCylinderShape_getHalfExtentsWithoutMargin(long jarg1, btCylinderShape jarg1_);
public final static native long new_btCylinderShape(Vector3 jarg1);
public final static native int btCylinderShape_getUpAxis(long jarg1, btCylinderShape jarg1_);
public final static native float btCylinderShape_getRadius(long jarg1, btCylinderShape jarg1_);
public final static native void delete_btCylinderShape(long jarg1);
public final static native long new_btCylinderShapeX(Vector3 jarg1);
public final static native void delete_btCylinderShapeX(long jarg1);
public final static native long new_btCylinderShapeZ(Vector3 jarg1);
public final static native void delete_btCylinderShapeZ(long jarg1);
public final static native void btCylinderShapeData_convexInternalShapeData_set(long jarg1, btCylinderShapeData jarg1_, long jarg2, btConvexInternalShapeData jarg2_);
public final static native long btCylinderShapeData_convexInternalShapeData_get(long jarg1, btCylinderShapeData jarg1_);
public final static native void btCylinderShapeData_upAxis_set(long jarg1, btCylinderShapeData jarg1_, int jarg2);
public final static native int btCylinderShapeData_upAxis_get(long jarg1, btCylinderShapeData jarg1_);
public final static native void btCylinderShapeData_padding_set(long jarg1, btCylinderShapeData jarg1_, String jarg2);
public final static native String btCylinderShapeData_padding_get(long jarg1, btCylinderShapeData jarg1_);
public final static native long new_btCylinderShapeData();
public final static native void delete_btCylinderShapeData(long jarg1);
public final static native void btTriangleMesh_weldingThreshold_set(long jarg1, btTriangleMesh jarg1_, float jarg2);
public final static native float btTriangleMesh_weldingThreshold_get(long jarg1, btTriangleMesh jarg1_);
public final static native long new_btTriangleMesh__SWIG_0(boolean jarg1, boolean jarg2);
public final static native long new_btTriangleMesh__SWIG_1(boolean jarg1);
public final static native long new_btTriangleMesh__SWIG_2();
public final static native boolean btTriangleMesh_getUse32bitIndices(long jarg1, btTriangleMesh jarg1_);
public final static native boolean btTriangleMesh_getUse4componentVertices(long jarg1, btTriangleMesh jarg1_);
public final static native void btTriangleMesh_addTriangle__SWIG_0(long jarg1, btTriangleMesh jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, boolean jarg5);
public final static native void btTriangleMesh_addTriangle__SWIG_1(long jarg1, btTriangleMesh jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native int btTriangleMesh_getNumTriangles(long jarg1, btTriangleMesh jarg1_);
public final static native int btTriangleMesh_findOrAddVertex(long jarg1, btTriangleMesh jarg1_, Vector3 jarg2, boolean jarg3);
public final static native void btTriangleMesh_addIndex(long jarg1, btTriangleMesh jarg1_, int jarg2);
public final static native void delete_btTriangleMesh(long jarg1);
public final static native long new_btConeShape(float jarg1, float jarg2);
public final static native float btConeShape_getRadius(long jarg1, btConeShape jarg1_);
public final static native float btConeShape_getHeight(long jarg1, btConeShape jarg1_);
public final static native void btConeShape_setConeUpIndex(long jarg1, btConeShape jarg1_, int jarg2);
public final static native int btConeShape_getConeUpIndex(long jarg1, btConeShape jarg1_);
public final static native void delete_btConeShape(long jarg1);
public final static native long new_btConeShapeX(float jarg1, float jarg2);
public final static native void delete_btConeShapeX(long jarg1);
public final static native long new_btConeShapeZ(float jarg1, float jarg2);
public final static native void delete_btConeShapeZ(long jarg1);
public final static native void btConeShapeData_convexInternalShapeData_set(long jarg1, btConeShapeData jarg1_, long jarg2, btConvexInternalShapeData jarg2_);
public final static native long btConeShapeData_convexInternalShapeData_get(long jarg1, btConeShapeData jarg1_);
public final static native void btConeShapeData_upIndex_set(long jarg1, btConeShapeData jarg1_, int jarg2);
public final static native int btConeShapeData_upIndex_get(long jarg1, btConeShapeData jarg1_);
public final static native void btConeShapeData_padding_set(long jarg1, btConeShapeData jarg1_, String jarg2);
public final static native String btConeShapeData_padding_get(long jarg1, btConeShapeData jarg1_);
public final static native long new_btConeShapeData();
public final static native void delete_btConeShapeData(long jarg1);
public final static native long new_btConvexTriangleMeshShape__SWIG_0(long jarg1, btStridingMeshInterface jarg1_, boolean jarg2);
public final static native long new_btConvexTriangleMeshShape__SWIG_1(long jarg1, btStridingMeshInterface jarg1_);
public final static native long btConvexTriangleMeshShape_getMeshInterface__SWIG_0(long jarg1, btConvexTriangleMeshShape jarg1_);
public final static native void btConvexTriangleMeshShape_calculatePrincipalAxisTransform(long jarg1, btConvexTriangleMeshShape jarg1_, Matrix4 jarg2, Vector3 jarg3, long jarg4);
public final static native void delete_btConvexTriangleMeshShape(long jarg1);
public final static native long new_btEmptyShape();
public final static native void delete_btEmptyShape(long jarg1);
public final static native long new_btMultimaterialTriangleMeshShape__SWIG_0(long jarg1, btStridingMeshInterface jarg1_, boolean jarg2, boolean jarg3);
public final static native long new_btMultimaterialTriangleMeshShape__SWIG_1(long jarg1, btStridingMeshInterface jarg1_, boolean jarg2);
public final static native long new_btMultimaterialTriangleMeshShape__SWIG_2(long jarg1, btStridingMeshInterface jarg1_, boolean jarg2, Vector3 jarg3, Vector3 jarg4, boolean jarg5);
public final static native long new_btMultimaterialTriangleMeshShape__SWIG_3(long jarg1, btStridingMeshInterface jarg1_, boolean jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native void delete_btMultimaterialTriangleMeshShape(long jarg1);
public final static native long btMultimaterialTriangleMeshShape_getMaterialProperties(long jarg1, btMultimaterialTriangleMeshShape jarg1_, int jarg2, int jarg3);
public final static native long new_btBU_Simplex1to4__SWIG_0();
public final static native long new_btBU_Simplex1to4__SWIG_1(Vector3 jarg1);
public final static native long new_btBU_Simplex1to4__SWIG_2(Vector3 jarg1, Vector3 jarg2);
public final static native long new_btBU_Simplex1to4__SWIG_3(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3);
public final static native long new_btBU_Simplex1to4__SWIG_4(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native void btBU_Simplex1to4_reset(long jarg1, btBU_Simplex1to4 jarg1_);
public final static native void btBU_Simplex1to4_addVertex(long jarg1, btBU_Simplex1to4 jarg1_, Vector3 jarg2);
public final static native int btBU_Simplex1to4_getIndex(long jarg1, btBU_Simplex1to4 jarg1_, int jarg2);
public final static native void delete_btBU_Simplex1to4(long jarg1);
public final static native long new_btUniformScalingShape(long jarg1, btConvexShape jarg1_, float jarg2);
public final static native void delete_btUniformScalingShape(long jarg1);
public final static native float btUniformScalingShape_getUniformScalingFactor(long jarg1, btUniformScalingShape jarg1_);
public final static native long btUniformScalingShape_getChildShape__SWIG_0(long jarg1, btUniformScalingShape jarg1_);
public final static native void btCompoundShapeChild_transform_set(long jarg1, btCompoundShapeChild jarg1_, long jarg2, btTransform jarg2_);
public final static native long btCompoundShapeChild_transform_get(long jarg1, btCompoundShapeChild jarg1_);
public final static native void btCompoundShapeChild_childShape_set(long jarg1, btCompoundShapeChild jarg1_, long jarg2, btCollisionShape jarg2_);
public final static native long btCompoundShapeChild_childShape_get(long jarg1, btCompoundShapeChild jarg1_);
public final static native void btCompoundShapeChild_childShapeType_set(long jarg1, btCompoundShapeChild jarg1_, int jarg2);
public final static native int btCompoundShapeChild_childShapeType_get(long jarg1, btCompoundShapeChild jarg1_);
public final static native void btCompoundShapeChild_childMargin_set(long jarg1, btCompoundShapeChild jarg1_, float jarg2);
public final static native float btCompoundShapeChild_childMargin_get(long jarg1, btCompoundShapeChild jarg1_);
public final static native void btCompoundShapeChild_node_set(long jarg1, btCompoundShapeChild jarg1_, long jarg2, btDbvtNode jarg2_);
public final static native long btCompoundShapeChild_node_get(long jarg1, btCompoundShapeChild jarg1_);
public final static native long new_btCompoundShapeChild();
public final static native void delete_btCompoundShapeChild(long jarg1);
public final static native long new_btCompoundShape__SWIG_0(boolean jarg1);
public final static native long new_btCompoundShape__SWIG_1();
public final static native void delete_btCompoundShape(long jarg1);
public final static native void btCompoundShape_internalAddChildShape(long jarg1, btCompoundShape jarg1_, Matrix4 jarg2, long jarg3, btCollisionShape jarg3_);
public final static native void btCompoundShape_internalRemoveChildShape(long jarg1, btCompoundShape jarg1_, long jarg2, btCollisionShape jarg2_);
public final static native void btCompoundShape_internalRemoveChildShapeByIndex(long jarg1, btCompoundShape jarg1_, int jarg2);
public final static native int btCompoundShape_getNumChildShapes(long jarg1, btCompoundShape jarg1_);
public final static native Matrix4 btCompoundShape_getChildTransform__SWIG_0(long jarg1, btCompoundShape jarg1_, int jarg2);
public final static native void btCompoundShape_updateChildTransform__SWIG_0(long jarg1, btCompoundShape jarg1_, int jarg2, Matrix4 jarg3, boolean jarg4);
public final static native void btCompoundShape_updateChildTransform__SWIG_1(long jarg1, btCompoundShape jarg1_, int jarg2, Matrix4 jarg3);
public final static native long btCompoundShape_getChildList(long jarg1, btCompoundShape jarg1_);
public final static native void btCompoundShape_recalculateLocalAabb(long jarg1, btCompoundShape jarg1_);
public final static native long btCompoundShape_getDynamicAabbTree__SWIG_0(long jarg1, btCompoundShape jarg1_);
public final static native void btCompoundShape_createAabbTreeFromChildren(long jarg1, btCompoundShape jarg1_);
public final static native void btCompoundShape_calculatePrincipalAxisTransform(long jarg1, btCompoundShape jarg1_, java.nio.FloatBuffer jarg2, Matrix4 jarg3, Vector3 jarg4);
public final static native int btCompoundShape_getUpdateRevision(long jarg1, btCompoundShape jarg1_);
public final static native void btCompoundShapeChildData_transform_set(long jarg1, btCompoundShapeChildData jarg1_, long jarg2, btTransformFloatData jarg2_);
public final static native long btCompoundShapeChildData_transform_get(long jarg1, btCompoundShapeChildData jarg1_);
public final static native void btCompoundShapeChildData_childShape_set(long jarg1, btCompoundShapeChildData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btCompoundShapeChildData_childShape_get(long jarg1, btCompoundShapeChildData jarg1_);
public final static native void btCompoundShapeChildData_childShapeType_set(long jarg1, btCompoundShapeChildData jarg1_, int jarg2);
public final static native int btCompoundShapeChildData_childShapeType_get(long jarg1, btCompoundShapeChildData jarg1_);
public final static native void btCompoundShapeChildData_childMargin_set(long jarg1, btCompoundShapeChildData jarg1_, float jarg2);
public final static native float btCompoundShapeChildData_childMargin_get(long jarg1, btCompoundShapeChildData jarg1_);
public final static native long new_btCompoundShapeChildData();
public final static native void delete_btCompoundShapeChildData(long jarg1);
public final static native void btCompoundShapeData_collisionShapeData_set(long jarg1, btCompoundShapeData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btCompoundShapeData_collisionShapeData_get(long jarg1, btCompoundShapeData jarg1_);
public final static native void btCompoundShapeData_childShapePtr_set(long jarg1, btCompoundShapeData jarg1_, long jarg2, btCompoundShapeChildData jarg2_);
public final static native long btCompoundShapeData_childShapePtr_get(long jarg1, btCompoundShapeData jarg1_);
public final static native void btCompoundShapeData_numChildShapes_set(long jarg1, btCompoundShapeData jarg1_, int jarg2);
public final static native int btCompoundShapeData_numChildShapes_get(long jarg1, btCompoundShapeData jarg1_);
public final static native void btCompoundShapeData_collisionMargin_set(long jarg1, btCompoundShapeData jarg1_, float jarg2);
public final static native float btCompoundShapeData_collisionMargin_get(long jarg1, btCompoundShapeData jarg1_);
public final static native long new_btCompoundShapeData();
public final static native void delete_btCompoundShapeData(long jarg1);
public final static native long new_btConvexPointCloudShape__SWIG_0();
public final static native long new_btConvexPointCloudShape__SWIG_1(long jarg1, btVector3 jarg1_, int jarg2, Vector3 jarg3, boolean jarg4);
public final static native long new_btConvexPointCloudShape__SWIG_2(long jarg1, btVector3 jarg1_, int jarg2, Vector3 jarg3);
public final static native void btConvexPointCloudShape_setPoints__SWIG_0(long jarg1, btConvexPointCloudShape jarg1_, long jarg2, btVector3 jarg2_, int jarg3, boolean jarg4, Vector3 jarg5);
public final static native void btConvexPointCloudShape_setPoints__SWIG_1(long jarg1, btConvexPointCloudShape jarg1_, long jarg2, btVector3 jarg2_, int jarg3, boolean jarg4);
public final static native void btConvexPointCloudShape_setPoints__SWIG_2(long jarg1, btConvexPointCloudShape jarg1_, long jarg2, btVector3 jarg2_, int jarg3);
public final static native long btConvexPointCloudShape_getUnscaledPoints__SWIG_0(long jarg1, btConvexPointCloudShape jarg1_);
public final static native int btConvexPointCloudShape_getNumPoints(long jarg1, btConvexPointCloudShape jarg1_);
public final static native Vector3 btConvexPointCloudShape_getScaledPoint(long jarg1, btConvexPointCloudShape jarg1_, int jarg2);
public final static native void delete_btConvexPointCloudShape(long jarg1);
public final static native long new_btConvex2dShape(long jarg1, btConvexShape jarg1_);
public final static native void delete_btConvex2dShape(long jarg1);
public final static native long btConvex2dShape_getChildShape__SWIG_0(long jarg1, btConvex2dShape jarg1_);
public final static native boolean btCollisionObject_mergesSimulationIslands(long jarg1, btCollisionObject jarg1_);
public final static native Vector3 btCollisionObject_getAnisotropicFriction__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setAnisotropicFriction__SWIG_0(long jarg1, btCollisionObject jarg1_, Vector3 jarg2, int jarg3);
public final static native void btCollisionObject_setAnisotropicFriction__SWIG_1(long jarg1, btCollisionObject jarg1_, Vector3 jarg2);
public final static native boolean btCollisionObject_hasAnisotropicFriction__SWIG_0(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native boolean btCollisionObject_hasAnisotropicFriction__SWIG_1(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setContactProcessingThreshold(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native float btCollisionObject_getContactProcessingThreshold(long jarg1, btCollisionObject jarg1_);
public final static native boolean btCollisionObject_isStaticObject(long jarg1, btCollisionObject jarg1_);
public final static native boolean btCollisionObject_isKinematicObject(long jarg1, btCollisionObject jarg1_);
public final static native boolean btCollisionObject_isStaticOrKinematicObject(long jarg1, btCollisionObject jarg1_);
public final static native boolean btCollisionObject_hasContactResponse(long jarg1, btCollisionObject jarg1_);
public final static native long new_btCollisionObject();
public final static native void delete_btCollisionObject(long jarg1);
public final static native void btCollisionObject_internalSetCollisionShape(long jarg1, btCollisionObject jarg1_, long jarg2, btCollisionShape jarg2_);
public final static native long btCollisionObject_internalGetCollisionShape__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native long btCollisionObject_internalGetExtensionPointer(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_internalSetExtensionPointer(long jarg1, btCollisionObject jarg1_, long jarg2);
public final static native int btCollisionObject_getActivationState(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setActivationState(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native void btCollisionObject_setDeactivationTime(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native float btCollisionObject_getDeactivationTime(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_forceActivationState(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native void btCollisionObject_activate__SWIG_0(long jarg1, btCollisionObject jarg1_, boolean jarg2);
public final static native void btCollisionObject_activate__SWIG_1(long jarg1, btCollisionObject jarg1_);
public final static native boolean btCollisionObject_isActive(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setRestitution(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native float btCollisionObject_getRestitution(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setFriction(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native float btCollisionObject_getFriction(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setRollingFriction(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native float btCollisionObject_getRollingFriction(long jarg1, btCollisionObject jarg1_);
public final static native int btCollisionObject_getInternalType(long jarg1, btCollisionObject jarg1_);
public final static native Matrix4 btCollisionObject_getWorldTransform__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setWorldTransform(long jarg1, btCollisionObject jarg1_, Matrix4 jarg2);
public final static native long btCollisionObject_getBroadphaseHandle__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setBroadphaseHandle(long jarg1, btCollisionObject jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native Matrix4 btCollisionObject_getInterpolationWorldTransform__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setInterpolationWorldTransform(long jarg1, btCollisionObject jarg1_, Matrix4 jarg2);
public final static native void btCollisionObject_setInterpolationLinearVelocity(long jarg1, btCollisionObject jarg1_, Vector3 jarg2);
public final static native void btCollisionObject_setInterpolationAngularVelocity(long jarg1, btCollisionObject jarg1_, Vector3 jarg2);
public final static native Vector3 btCollisionObject_getInterpolationLinearVelocity__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native Vector3 btCollisionObject_getInterpolationAngularVelocity__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native int btCollisionObject_getIslandTag(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setIslandTag(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native int btCollisionObject_getCompanionId(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setCompanionId(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native float btCollisionObject_getHitFraction(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setHitFraction(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native int btCollisionObject_getCollisionFlags(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setCollisionFlags(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native float btCollisionObject_getCcdSweptSphereRadius(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setCcdSweptSphereRadius(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native float btCollisionObject_getCcdMotionThreshold(long jarg1, btCollisionObject jarg1_);
public final static native float btCollisionObject_getCcdSquareMotionThreshold(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setCcdMotionThreshold(long jarg1, btCollisionObject jarg1_, float jarg2);
public final static native long btCollisionObject_getUserPointer(long jarg1, btCollisionObject jarg1_);
public final static native int btCollisionObject_getUserIndex(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_setUserPointer(long jarg1, btCollisionObject jarg1_, long jarg2);
public final static native void btCollisionObject_setUserIndex(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native int btCollisionObject_getUpdateRevisionInternal(long jarg1, btCollisionObject jarg1_);
public final static native boolean btCollisionObject_checkCollideWith(long jarg1, btCollisionObject jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native int btCollisionObject_calculateSerializeBufferSize(long jarg1, btCollisionObject jarg1_);
public final static native String btCollisionObject_serialize(long jarg1, btCollisionObject jarg1_, long jarg2, long jarg3);
public final static native void btCollisionObject_serializeSingleObject(long jarg1, btCollisionObject jarg1_, long jarg2);
public final static native void btCollisionObject_internalSetGdxBridge(long jarg1, btCollisionObject jarg1_, long jarg2, GdxCollisionObjectBridge jarg2_);
public final static native long btCollisionObject_internalGetGdxBridge(long jarg1, btCollisionObject jarg1_);
public final static native void btCollisionObject_getAnisotropicFriction__SWIG_1(long jarg1, btCollisionObject jarg1_, Vector3 jarg2);
public final static native void btCollisionObject_getWorldTransform__SWIG_2(long jarg1, btCollisionObject jarg1_, Matrix4 jarg2);
public final static native void btCollisionObject_getInterpolationWorldTransform__SWIG_2(long jarg1, btCollisionObject jarg1_, Matrix4 jarg2);
public final static native void btCollisionObject_getInterpolationLinearVelocity__SWIG_1(long jarg1, btCollisionObject jarg1_, Vector3 jarg2);
public final static native void btCollisionObject_getInterpolationAngularVelocity__SWIG_1(long jarg1, btCollisionObject jarg1_, Vector3 jarg2);
public final static native void btCollisionObjectDoubleData_broadphaseHandle_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2);
public final static native long btCollisionObjectDoubleData_broadphaseHandle_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_collisionShape_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2);
public final static native long btCollisionObjectDoubleData_collisionShape_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_rootCollisionShape_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btCollisionObjectDoubleData_rootCollisionShape_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_name_set(long jarg1, btCollisionObjectDoubleData jarg1_, String jarg2);
public final static native String btCollisionObjectDoubleData_name_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_worldTransform_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2, btTransformDoubleData jarg2_);
public final static native long btCollisionObjectDoubleData_worldTransform_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_interpolationWorldTransform_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2, btTransformDoubleData jarg2_);
public final static native long btCollisionObjectDoubleData_interpolationWorldTransform_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_interpolationLinearVelocity_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btCollisionObjectDoubleData_interpolationLinearVelocity_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_interpolationAngularVelocity_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btCollisionObjectDoubleData_interpolationAngularVelocity_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_anisotropicFriction_set(long jarg1, btCollisionObjectDoubleData jarg1_, long jarg2, btVector3DoubleData jarg2_);
public final static native long btCollisionObjectDoubleData_anisotropicFriction_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_contactProcessingThreshold_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_contactProcessingThreshold_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_deactivationTime_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_deactivationTime_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_friction_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_friction_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_rollingFriction_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_rollingFriction_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_restitution_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_restitution_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_hitFraction_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_hitFraction_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_ccdSweptSphereRadius_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_ccdSweptSphereRadius_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_ccdMotionThreshold_set(long jarg1, btCollisionObjectDoubleData jarg1_, double jarg2);
public final static native double btCollisionObjectDoubleData_ccdMotionThreshold_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_hasAnisotropicFriction_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_hasAnisotropicFriction_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_collisionFlags_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_collisionFlags_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_islandTag1_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_islandTag1_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_companionId_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_companionId_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_activationState1_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_activationState1_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_internalType_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_internalType_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_checkCollideWith_set(long jarg1, btCollisionObjectDoubleData jarg1_, int jarg2);
public final static native int btCollisionObjectDoubleData_checkCollideWith_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native void btCollisionObjectDoubleData_padding_set(long jarg1, btCollisionObjectDoubleData jarg1_, String jarg2);
public final static native String btCollisionObjectDoubleData_padding_get(long jarg1, btCollisionObjectDoubleData jarg1_);
public final static native long new_btCollisionObjectDoubleData();
public final static native void delete_btCollisionObjectDoubleData(long jarg1);
public final static native void btCollisionObjectFloatData_broadphaseHandle_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2);
public final static native long btCollisionObjectFloatData_broadphaseHandle_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_collisionShape_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2);
public final static native long btCollisionObjectFloatData_collisionShape_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_rootCollisionShape_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btCollisionObjectFloatData_rootCollisionShape_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_name_set(long jarg1, btCollisionObjectFloatData jarg1_, String jarg2);
public final static native String btCollisionObjectFloatData_name_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_worldTransform_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2, btTransformFloatData jarg2_);
public final static native long btCollisionObjectFloatData_worldTransform_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_interpolationWorldTransform_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2, btTransformFloatData jarg2_);
public final static native long btCollisionObjectFloatData_interpolationWorldTransform_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_interpolationLinearVelocity_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btCollisionObjectFloatData_interpolationLinearVelocity_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_interpolationAngularVelocity_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btCollisionObjectFloatData_interpolationAngularVelocity_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_anisotropicFriction_set(long jarg1, btCollisionObjectFloatData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btCollisionObjectFloatData_anisotropicFriction_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_contactProcessingThreshold_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_contactProcessingThreshold_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_deactivationTime_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_deactivationTime_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_friction_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_friction_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_rollingFriction_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_rollingFriction_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_restitution_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_restitution_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_hitFraction_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_hitFraction_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_ccdSweptSphereRadius_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_ccdSweptSphereRadius_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_ccdMotionThreshold_set(long jarg1, btCollisionObjectFloatData jarg1_, float jarg2);
public final static native float btCollisionObjectFloatData_ccdMotionThreshold_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_hasAnisotropicFriction_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_hasAnisotropicFriction_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_collisionFlags_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_collisionFlags_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_islandTag1_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_islandTag1_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_companionId_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_companionId_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_activationState1_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_activationState1_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_internalType_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_internalType_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_checkCollideWith_set(long jarg1, btCollisionObjectFloatData jarg1_, int jarg2);
public final static native int btCollisionObjectFloatData_checkCollideWith_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native void btCollisionObjectFloatData_padding_set(long jarg1, btCollisionObjectFloatData jarg1_, String jarg2);
public final static native String btCollisionObjectFloatData_padding_get(long jarg1, btCollisionObjectFloatData jarg1_);
public final static native long new_btCollisionObjectFloatData();
public final static native void delete_btCollisionObjectFloatData(long jarg1);
public final static native void GdxCollisionObjectBridge_userValue_set(long jarg1, GdxCollisionObjectBridge jarg1_, int jarg2);
public final static native int GdxCollisionObjectBridge_userValue_get(long jarg1, GdxCollisionObjectBridge jarg1_);
public final static native void GdxCollisionObjectBridge_contactCallbackFlag_set(long jarg1, GdxCollisionObjectBridge jarg1_, int jarg2);
public final static native int GdxCollisionObjectBridge_contactCallbackFlag_get(long jarg1, GdxCollisionObjectBridge jarg1_);
public final static native void GdxCollisionObjectBridge_contactCallbackFilter_set(long jarg1, GdxCollisionObjectBridge jarg1_, int jarg2);
public final static native int GdxCollisionObjectBridge_contactCallbackFilter_get(long jarg1, GdxCollisionObjectBridge jarg1_);
public final static native long new_GdxCollisionObjectBridge();
public final static native void delete_GdxCollisionObjectBridge(long jarg1);
public final static native boolean gdxCheckFilter__SWIG_0(int jarg1, int jarg2);
public final static native boolean gdxCheckFilter__SWIG_1(long jarg1, btCollisionObject jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long new_btCollisionObjectArray__SWIG_0();
public final static native void delete_btCollisionObjectArray(long jarg1);
public final static native long new_btCollisionObjectArray__SWIG_1(long jarg1, btCollisionObjectArray jarg1_);
public final static native int btCollisionObjectArray_size(long jarg1, btCollisionObjectArray jarg1_);
public final static native long btCollisionObjectArray_at__SWIG_0(long jarg1, btCollisionObjectArray jarg1_, int jarg2);
public final static native void btCollisionObjectArray_clear(long jarg1, btCollisionObjectArray jarg1_);
public final static native void btCollisionObjectArray_pop_back(long jarg1, btCollisionObjectArray jarg1_);
public final static native void btCollisionObjectArray_resizeNoInitialize(long jarg1, btCollisionObjectArray jarg1_, int jarg2);
public final static native void btCollisionObjectArray_resize__SWIG_0(long jarg1, btCollisionObjectArray jarg1_, int jarg2, long jarg3, btCollisionObject jarg3_);
public final static native void btCollisionObjectArray_resize__SWIG_1(long jarg1, btCollisionObjectArray jarg1_, int jarg2);
public final static native long btCollisionObjectArray_expandNonInitializing(long jarg1, btCollisionObjectArray jarg1_);
public final static native long btCollisionObjectArray_expand__SWIG_0(long jarg1, btCollisionObjectArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long btCollisionObjectArray_expand__SWIG_1(long jarg1, btCollisionObjectArray jarg1_);
public final static native void btCollisionObjectArray_push_back(long jarg1, btCollisionObjectArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native int btCollisionObjectArray_capacity(long jarg1, btCollisionObjectArray jarg1_);
public final static native void btCollisionObjectArray_reserve(long jarg1, btCollisionObjectArray jarg1_, int jarg2);
public final static native long new_btCollisionObjectArray_less();
public final static native void delete_btCollisionObjectArray_less(long jarg1);
public final static native void btCollisionObjectArray_swap(long jarg1, btCollisionObjectArray jarg1_, int jarg2, int jarg3);
public final static native int btCollisionObjectArray_findBinarySearch(long jarg1, btCollisionObjectArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native int btCollisionObjectArray_findLinearSearch(long jarg1, btCollisionObjectArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native void btCollisionObjectArray_remove(long jarg1, btCollisionObjectArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native void btCollisionObjectArray_initializeFromBuffer(long jarg1, btCollisionObjectArray jarg1_, long jarg2, int jarg3, int jarg4);
public final static native void btCollisionObjectArray_copyFromArray(long jarg1, btCollisionObjectArray jarg1_, long jarg2, btCollisionObjectArray jarg2_);
public final static native long new_btCollisionObjectConstArray__SWIG_0();
public final static native void delete_btCollisionObjectConstArray(long jarg1);
public final static native long new_btCollisionObjectConstArray__SWIG_1(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native int btCollisionObjectConstArray_size(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native long btCollisionObjectConstArray_at__SWIG_0(long jarg1, btCollisionObjectConstArray jarg1_, int jarg2);
public final static native void btCollisionObjectConstArray_clear(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native void btCollisionObjectConstArray_pop_back(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native void btCollisionObjectConstArray_resizeNoInitialize(long jarg1, btCollisionObjectConstArray jarg1_, int jarg2);
public final static native void btCollisionObjectConstArray_resize__SWIG_0(long jarg1, btCollisionObjectConstArray jarg1_, int jarg2, long jarg3, btCollisionObject jarg3_);
public final static native void btCollisionObjectConstArray_resize__SWIG_1(long jarg1, btCollisionObjectConstArray jarg1_, int jarg2);
public final static native long btCollisionObjectConstArray_expandNonInitializing(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native long btCollisionObjectConstArray_expand__SWIG_0(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long btCollisionObjectConstArray_expand__SWIG_1(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native void btCollisionObjectConstArray_push_back(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native int btCollisionObjectConstArray_capacity(long jarg1, btCollisionObjectConstArray jarg1_);
public final static native void btCollisionObjectConstArray_reserve(long jarg1, btCollisionObjectConstArray jarg1_, int jarg2);
public final static native long new_btCollisionObjectConstArray_less();
public final static native void delete_btCollisionObjectConstArray_less(long jarg1);
public final static native void btCollisionObjectConstArray_swap(long jarg1, btCollisionObjectConstArray jarg1_, int jarg2, int jarg3);
public final static native int btCollisionObjectConstArray_findBinarySearch(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native int btCollisionObjectConstArray_findLinearSearch(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native void btCollisionObjectConstArray_remove(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native void btCollisionObjectConstArray_initializeFromBuffer(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, int jarg3, int jarg4);
public final static native void btCollisionObjectConstArray_copyFromArray(long jarg1, btCollisionObjectConstArray jarg1_, long jarg2, btCollisionObjectConstArray jarg2_);
public final static native void btCollisionObjectWrapper_parent_set(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionObjectWrapper jarg2_);
public final static native long btCollisionObjectWrapper_parent_get(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native void btCollisionObjectWrapper_shape_set(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionShape jarg2_);
public final static native long btCollisionObjectWrapper_shape_get(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native void btCollisionObjectWrapper_collisionObject_set(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long btCollisionObjectWrapper_collisionObject_get(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native Matrix4 btCollisionObjectWrapper_worldTransform_get(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native void btCollisionObjectWrapper_partId_set(long jarg1, btCollisionObjectWrapper jarg1_, int jarg2);
public final static native int btCollisionObjectWrapper_partId_get(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native void btCollisionObjectWrapper_index_set(long jarg1, btCollisionObjectWrapper jarg1_, int jarg2);
public final static native int btCollisionObjectWrapper_index_get(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native long btCollisionObjectWrapper_getCollisionShape(long jarg1, btCollisionObjectWrapper jarg1_);
public final static native long new_CollisionObjectWrapper__SWIG_0(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionShape jarg2_, long jarg3, btCollisionObject jarg3_, Matrix4 jarg4, int jarg5, int jarg6);
public final static native long new_CollisionObjectWrapper__SWIG_1(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionShape jarg2_, long jarg3, btCollisionObject jarg3_, Matrix4 jarg4, int jarg5);
public final static native long new_CollisionObjectWrapper__SWIG_2(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionShape jarg2_, long jarg3, btCollisionObject jarg3_, Matrix4 jarg4);
public final static native long new_CollisionObjectWrapper__SWIG_3(long jarg1, btCollisionShape jarg1_, long jarg2, btCollisionObject jarg2_, Matrix4 jarg3, int jarg4, int jarg5);
public final static native long new_CollisionObjectWrapper__SWIG_4(long jarg1, btCollisionShape jarg1_, long jarg2, btCollisionObject jarg2_, Matrix4 jarg3, int jarg4);
public final static native long new_CollisionObjectWrapper__SWIG_5(long jarg1, btCollisionShape jarg1_, long jarg2, btCollisionObject jarg2_, Matrix4 jarg3);
public final static native long new_CollisionObjectWrapper__SWIG_6(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionObject jarg2_, int jarg3, int jarg4);
public final static native long new_CollisionObjectWrapper__SWIG_7(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionObject jarg2_, int jarg3);
public final static native long new_CollisionObjectWrapper__SWIG_8(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long new_CollisionObjectWrapper__SWIG_9(long jarg1, btCollisionObject jarg1_, int jarg2, int jarg3);
public final static native long new_CollisionObjectWrapper__SWIG_10(long jarg1, btCollisionObject jarg1_, int jarg2);
public final static native long new_CollisionObjectWrapper__SWIG_11(long jarg1, btCollisionObject jarg1_);
public final static native long CollisionObjectWrapper_getWrapper(long jarg1, CollisionObjectWrapper jarg1_);
public final static native void delete_CollisionObjectWrapper(long jarg1);
public final static native long new_btEmptyAlgorithm(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native long btEmptyAlgorithm_CreateFunc_CreateCollisionAlgorithm(long jarg1, btEmptyAlgorithm.CreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btEmptyAlgorithm_CreateFunc();
public final static native void delete_btEmptyAlgorithm_CreateFunc(long jarg1);
public final static native void delete_btEmptyAlgorithm(long jarg1);
public final static native void delete_btActivatingCollisionAlgorithm(long jarg1);
public final static native void btConvexTriangleCallback_triangleCount_set(long jarg1, btConvexTriangleCallback jarg1_, int jarg2);
public final static native int btConvexTriangleCallback_triangleCount_get(long jarg1, btConvexTriangleCallback jarg1_);
public final static native void btConvexTriangleCallback_manifoldPtr_set(long jarg1, btConvexTriangleCallback jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native long btConvexTriangleCallback_manifoldPtr_get(long jarg1, btConvexTriangleCallback jarg1_);
public final static native long new_btConvexTriangleCallback(long jarg1, btDispatcher jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, boolean jarg4);
public final static native void btConvexTriangleCallback_setTimeStepAndCounters(long jarg1, btConvexTriangleCallback jarg1_, float jarg2, long jarg3, btDispatcherInfo jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, long jarg5, btCollisionObjectWrapper jarg5_, long jarg6, btManifoldResult jarg6_);
public final static native void btConvexTriangleCallback_clearWrapperData(long jarg1, btConvexTriangleCallback jarg1_);
public final static native void delete_btConvexTriangleCallback(long jarg1);
public final static native void btConvexTriangleCallback_processTriangle(long jarg1, btConvexTriangleCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native void btConvexTriangleCallback_processTriangleSwigExplicitbtConvexTriangleCallback(long jarg1, btConvexTriangleCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native void btConvexTriangleCallback_clearCache(long jarg1, btConvexTriangleCallback jarg1_);
public final static native Vector3 btConvexTriangleCallback_getAabbMin(long jarg1, btConvexTriangleCallback jarg1_);
public final static native Vector3 btConvexTriangleCallback_getAabbMax(long jarg1, btConvexTriangleCallback jarg1_);
public final static native void btConvexTriangleCallback_director_connect(btConvexTriangleCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btConvexTriangleCallback_change_ownership(btConvexTriangleCallback obj, long cptr, boolean take_or_release);
public final static native long new_btConvexConcaveCollisionAlgorithm(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, boolean jarg4);
public final static native void delete_btConvexConcaveCollisionAlgorithm(long jarg1);
public final static native void btConvexConcaveCollisionAlgorithm_clearCache(long jarg1, btConvexConcaveCollisionAlgorithm jarg1_);
public final static native long btConvexConcaveCollisionAlgorithm_CreateFunc_CreateCollisionAlgorithm(long jarg1, btConvexConcaveCollisionAlgorithm.CreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btConvexConcaveCollisionAlgorithm_CreateFunc();
public final static native void delete_btConvexConcaveCollisionAlgorithm_CreateFunc(long jarg1);
public final static native long btConvexConcaveCollisionAlgorithm_SwappedCreateFunc_CreateCollisionAlgorithm(long jarg1, btConvexConcaveCollisionAlgorithm.SwappedCreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btConvexConcaveCollisionAlgorithm_SwappedCreateFunc();
public final static native void delete_btConvexConcaveCollisionAlgorithm_SwappedCreateFunc(long jarg1);
public final static native long new_btConvexPlaneCollisionAlgorithm(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, boolean jarg5, int jarg6, int jarg7);
public final static native void delete_btConvexPlaneCollisionAlgorithm(long jarg1);
public final static native void btConvexPlaneCollisionAlgorithm_collideSingleContact(long jarg1, btConvexPlaneCollisionAlgorithm jarg1_, Quaternion jarg2, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, long jarg5, btDispatcherInfo jarg5_, long jarg6, btManifoldResult jarg6_);
public final static native void btConvexPlaneCollisionAlgorithm_CreateFunc_numPerturbationIterations_set(long jarg1, btConvexPlaneCollisionAlgorithm.CreateFunc jarg1_, int jarg2);
public final static native int btConvexPlaneCollisionAlgorithm_CreateFunc_numPerturbationIterations_get(long jarg1, btConvexPlaneCollisionAlgorithm.CreateFunc jarg1_);
public final static native void btConvexPlaneCollisionAlgorithm_CreateFunc_minimumPointsPerturbationThreshold_set(long jarg1, btConvexPlaneCollisionAlgorithm.CreateFunc jarg1_, int jarg2);
public final static native int btConvexPlaneCollisionAlgorithm_CreateFunc_minimumPointsPerturbationThreshold_get(long jarg1, btConvexPlaneCollisionAlgorithm.CreateFunc jarg1_);
public final static native long new_btConvexPlaneCollisionAlgorithm_CreateFunc();
public final static native long btConvexPlaneCollisionAlgorithm_CreateFunc_CreateCollisionAlgorithm(long jarg1, btConvexPlaneCollisionAlgorithm.CreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native void delete_btConvexPlaneCollisionAlgorithm_CreateFunc(long jarg1);
public final static native void gCompoundCompoundChildShapePairCallback_set(long jarg1);
public final static native long gCompoundCompoundChildShapePairCallback_get();
public final static native long new_btCompoundCompoundCollisionAlgorithm(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, boolean jarg4);
public final static native void delete_btCompoundCompoundCollisionAlgorithm(long jarg1);
public final static native long btCompoundCompoundCollisionAlgorithm_CreateFunc_CreateCollisionAlgorithm(long jarg1, btCompoundCompoundCollisionAlgorithm.CreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btCompoundCompoundCollisionAlgorithm_CreateFunc();
public final static native void delete_btCompoundCompoundCollisionAlgorithm_CreateFunc(long jarg1);
public final static native long btCompoundCompoundCollisionAlgorithm_SwappedCreateFunc_CreateCollisionAlgorithm(long jarg1, btCompoundCompoundCollisionAlgorithm.SwappedCreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btCompoundCompoundCollisionAlgorithm_SwappedCreateFunc();
public final static native void delete_btCompoundCompoundCollisionAlgorithm_SwappedCreateFunc(long jarg1);
public final static native void delete_btCollisionConfiguration(long jarg1);
public final static native long btCollisionConfiguration_getPersistentManifoldPool(long jarg1, btCollisionConfiguration jarg1_);
public final static native long btCollisionConfiguration_getCollisionAlgorithmPool(long jarg1, btCollisionConfiguration jarg1_);
public final static native long btCollisionConfiguration_getCollisionAlgorithmCreateFunc(long jarg1, btCollisionConfiguration jarg1_, int jarg2, int jarg3);
public final static native void btDefaultCollisionConstructionInfo_persistentManifoldPool_set(long jarg1, btDefaultCollisionConstructionInfo jarg1_, long jarg2, btPoolAllocator jarg2_);
public final static native long btDefaultCollisionConstructionInfo_persistentManifoldPool_get(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native void btDefaultCollisionConstructionInfo_collisionAlgorithmPool_set(long jarg1, btDefaultCollisionConstructionInfo jarg1_, long jarg2, btPoolAllocator jarg2_);
public final static native long btDefaultCollisionConstructionInfo_collisionAlgorithmPool_get(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native void btDefaultCollisionConstructionInfo_defaultMaxPersistentManifoldPoolSize_set(long jarg1, btDefaultCollisionConstructionInfo jarg1_, int jarg2);
public final static native int btDefaultCollisionConstructionInfo_defaultMaxPersistentManifoldPoolSize_get(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native void btDefaultCollisionConstructionInfo_defaultMaxCollisionAlgorithmPoolSize_set(long jarg1, btDefaultCollisionConstructionInfo jarg1_, int jarg2);
public final static native int btDefaultCollisionConstructionInfo_defaultMaxCollisionAlgorithmPoolSize_get(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native void btDefaultCollisionConstructionInfo_customCollisionAlgorithmMaxElementSize_set(long jarg1, btDefaultCollisionConstructionInfo jarg1_, int jarg2);
public final static native int btDefaultCollisionConstructionInfo_customCollisionAlgorithmMaxElementSize_get(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native void btDefaultCollisionConstructionInfo_useEpaPenetrationAlgorithm_set(long jarg1, btDefaultCollisionConstructionInfo jarg1_, int jarg2);
public final static native int btDefaultCollisionConstructionInfo_useEpaPenetrationAlgorithm_get(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native long new_btDefaultCollisionConstructionInfo();
public final static native void delete_btDefaultCollisionConstructionInfo(long jarg1);
public final static native long new_btDefaultCollisionConfiguration__SWIG_0(long jarg1, btDefaultCollisionConstructionInfo jarg1_);
public final static native long new_btDefaultCollisionConfiguration__SWIG_1();
public final static native void delete_btDefaultCollisionConfiguration(long jarg1);
public final static native long btDefaultCollisionConfiguration_getSimplexSolver(long jarg1, btDefaultCollisionConfiguration jarg1_);
public final static native void btDefaultCollisionConfiguration_setConvexConvexMultipointIterations__SWIG_0(long jarg1, btDefaultCollisionConfiguration jarg1_, int jarg2, int jarg3);
public final static native void btDefaultCollisionConfiguration_setConvexConvexMultipointIterations__SWIG_1(long jarg1, btDefaultCollisionConfiguration jarg1_, int jarg2);
public final static native void btDefaultCollisionConfiguration_setConvexConvexMultipointIterations__SWIG_2(long jarg1, btDefaultCollisionConfiguration jarg1_);
public final static native void btDefaultCollisionConfiguration_setPlaneConvexMultipointIterations__SWIG_0(long jarg1, btDefaultCollisionConfiguration jarg1_, int jarg2, int jarg3);
public final static native void btDefaultCollisionConfiguration_setPlaneConvexMultipointIterations__SWIG_1(long jarg1, btDefaultCollisionConfiguration jarg1_, int jarg2);
public final static native void btDefaultCollisionConfiguration_setPlaneConvexMultipointIterations__SWIG_2(long jarg1, btDefaultCollisionConfiguration jarg1_);
public final static native void gContactAddedCallback_set(long jarg1);
public final static native long gContactAddedCallback_get();
public final static native long new_btManifoldResult__SWIG_0();
public final static native long new_btManifoldResult__SWIG_1(long jarg1, btCollisionObjectWrapper jarg1_, long jarg2, btCollisionObjectWrapper jarg2_);
public final static native void delete_btManifoldResult(long jarg1);
public final static native void btManifoldResult_setPersistentManifold(long jarg1, btManifoldResult jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native long btManifoldResult_getPersistentManifold__SWIG_0(long jarg1, btManifoldResult jarg1_);
public final static native void btManifoldResult_refreshContactPoints(long jarg1, btManifoldResult jarg1_);
public final static native long btManifoldResult_getBody0Wrap(long jarg1, btManifoldResult jarg1_);
public final static native long btManifoldResult_getBody1Wrap(long jarg1, btManifoldResult jarg1_);
public final static native void btManifoldResult_setBody0Wrap(long jarg1, btManifoldResult jarg1_, long jarg2, btCollisionObjectWrapper jarg2_);
public final static native void btManifoldResult_setBody1Wrap(long jarg1, btManifoldResult jarg1_, long jarg2, btCollisionObjectWrapper jarg2_);
public final static native long btManifoldResult_getBody0Internal(long jarg1, btManifoldResult jarg1_);
public final static native long btManifoldResult_getBody1Internal(long jarg1, btManifoldResult jarg1_);
public final static native float btManifoldResult_calculateCombinedRestitution(long jarg1, btCollisionObject jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native float btManifoldResult_calculateCombinedFriction(long jarg1, btCollisionObject jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native int BT_SIMPLE_NULL_PAIR_get();
public final static native long new_btSimplePair(int jarg1, int jarg2);
public final static native void btSimplePair_indexA_set(long jarg1, btSimplePair jarg1_, int jarg2);
public final static native int btSimplePair_indexA_get(long jarg1, btSimplePair jarg1_);
public final static native void btSimplePair_indexB_set(long jarg1, btSimplePair jarg1_, int jarg2);
public final static native int btSimplePair_indexB_get(long jarg1, btSimplePair jarg1_);
public final static native void btSimplePair_userPointer_set(long jarg1, btSimplePair jarg1_, long jarg2);
public final static native long btSimplePair_userPointer_get(long jarg1, btSimplePair jarg1_);
public final static native void btSimplePair_userValue_set(long jarg1, btSimplePair jarg1_, int jarg2);
public final static native int btSimplePair_userValue_get(long jarg1, btSimplePair jarg1_);
public final static native void delete_btSimplePair(long jarg1);
public final static native void gOverlappingSimplePairs_set(int jarg1);
public final static native int gOverlappingSimplePairs_get();
public final static native void gRemoveSimplePairs_set(int jarg1);
public final static native int gRemoveSimplePairs_get();
public final static native void gAddedSimplePairs_set(int jarg1);
public final static native int gAddedSimplePairs_get();
public final static native void gFindSimplePairs_set(int jarg1);
public final static native int gFindSimplePairs_get();
public final static native long new_btHashedSimplePairCache();
public final static native void delete_btHashedSimplePairCache(long jarg1);
public final static native void btHashedSimplePairCache_removeAllPairs(long jarg1, btHashedSimplePairCache jarg1_);
public final static native long btHashedSimplePairCache_removeOverlappingPair(long jarg1, btHashedSimplePairCache jarg1_, int jarg2, int jarg3);
public final static native long btHashedSimplePairCache_addOverlappingPair(long jarg1, btHashedSimplePairCache jarg1_, int jarg2, int jarg3);
public final static native long btHashedSimplePairCache_getOverlappingPairArrayPtr__SWIG_0(long jarg1, btHashedSimplePairCache jarg1_);
public final static native long btHashedSimplePairCache_getOverlappingPairArray__SWIG_0(long jarg1, btHashedSimplePairCache jarg1_);
public final static native long btHashedSimplePairCache_findPair(long jarg1, btHashedSimplePairCache jarg1_, int jarg2, int jarg3);
public final static native int btHashedSimplePairCache_GetCount(long jarg1, btHashedSimplePairCache jarg1_);
public final static native int btHashedSimplePairCache_getNumOverlappingPairs(long jarg1, btHashedSimplePairCache jarg1_);
public final static native long new_btSphereSphereCollisionAlgorithm__SWIG_0(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btSphereSphereCollisionAlgorithm__SWIG_1(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native void delete_btSphereSphereCollisionAlgorithm(long jarg1);
public final static native long btSphereSphereCollisionAlgorithm_CreateFunc_CreateCollisionAlgorithm(long jarg1, btSphereSphereCollisionAlgorithm.CreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btSphereSphereCollisionAlgorithm_CreateFunc();
public final static native void delete_btSphereSphereCollisionAlgorithm_CreateFunc(long jarg1);
public final static native long new_btBoxBoxCollisionAlgorithm__SWIG_0(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native long new_btBoxBoxCollisionAlgorithm__SWIG_1(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native void delete_btBoxBoxCollisionAlgorithm(long jarg1);
public final static native long btBoxBoxCollisionAlgorithm_CreateFunc_CreateCollisionAlgorithm(long jarg1, btBoxBoxCollisionAlgorithm.CreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btBoxBoxCollisionAlgorithm_CreateFunc();
public final static native void delete_btBoxBoxCollisionAlgorithm_CreateFunc(long jarg1);
public final static native void btCollisionAlgorithmCreateFunc_swapped_set(long jarg1, btCollisionAlgorithmCreateFunc jarg1_, boolean jarg2);
public final static native boolean btCollisionAlgorithmCreateFunc_swapped_get(long jarg1, btCollisionAlgorithmCreateFunc jarg1_);
public final static native long new_btCollisionAlgorithmCreateFunc();
public final static native void delete_btCollisionAlgorithmCreateFunc(long jarg1);
public final static native long btCollisionAlgorithmCreateFunc_CreateCollisionAlgorithm(long jarg1, btCollisionAlgorithmCreateFunc jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native long new_btBox2dBox2dCollisionAlgorithm__SWIG_0(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native long new_btBox2dBox2dCollisionAlgorithm__SWIG_1(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_);
public final static native void delete_btBox2dBox2dCollisionAlgorithm(long jarg1);
public final static native long new_btBox2dBox2dCollisionAlgorithm_CreateFunc();
public final static native void delete_btBox2dBox2dCollisionAlgorithm_CreateFunc(long jarg1);
public final static native void btElement_id_set(long jarg1, btElement jarg1_, int jarg2);
public final static native int btElement_id_get(long jarg1, btElement jarg1_);
public final static native void btElement_sz_set(long jarg1, btElement jarg1_, int jarg2);
public final static native int btElement_sz_get(long jarg1, btElement jarg1_);
public final static native long new_btElement();
public final static native void delete_btElement(long jarg1);
public final static native long new_btUnionFind();
public final static native void delete_btUnionFind(long jarg1);
public final static native void btUnionFind_sortIslands(long jarg1, btUnionFind jarg1_);
public final static native void btUnionFind_reset(long jarg1, btUnionFind jarg1_, int jarg2);
public final static native int btUnionFind_getNumElements(long jarg1, btUnionFind jarg1_);
public final static native boolean btUnionFind_isRoot(long jarg1, btUnionFind jarg1_, int jarg2);
public final static native long btUnionFind_getElement__SWIG_0(long jarg1, btUnionFind jarg1_, int jarg2);
public final static native void btUnionFind_allocate(long jarg1, btUnionFind jarg1_, int jarg2);
public final static native void btUnionFind_Free(long jarg1, btUnionFind jarg1_);
public final static native int btUnionFind_find__SWIG_0(long jarg1, btUnionFind jarg1_, int jarg2, int jarg3);
public final static native void btUnionFind_unite(long jarg1, btUnionFind jarg1_, int jarg2, int jarg3);
public final static native int btUnionFind_find__SWIG_1(long jarg1, btUnionFind jarg1_, int jarg2);
public final static native long new_btSphereTriangleCollisionAlgorithm__SWIG_0(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, boolean jarg5);
public final static native long new_btSphereTriangleCollisionAlgorithm__SWIG_1(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_);
public final static native void delete_btSphereTriangleCollisionAlgorithm(long jarg1);
public final static native long new_btSphereTriangleCollisionAlgorithm_CreateFunc();
public final static native void delete_btSphereTriangleCollisionAlgorithm_CreateFunc(long jarg1);
public final static native long new_btSimulationIslandManager();
public final static native void delete_btSimulationIslandManager(long jarg1);
public final static native void btSimulationIslandManager_initUnionFind(long jarg1, btSimulationIslandManager jarg1_, int jarg2);
public final static native long btSimulationIslandManager_getUnionFind(long jarg1, btSimulationIslandManager jarg1_);
public final static native void btSimulationIslandManager_updateActivationState(long jarg1, btSimulationIslandManager jarg1_, long jarg2, btCollisionWorld jarg2_, long jarg3, btDispatcher jarg3_);
public final static native void btSimulationIslandManager_storeIslandActivationState(long jarg1, btSimulationIslandManager jarg1_, long jarg2, btCollisionWorld jarg2_);
public final static native void btSimulationIslandManager_findUnions(long jarg1, btSimulationIslandManager jarg1_, long jarg2, btDispatcher jarg2_, long jarg3, btCollisionWorld jarg3_);
public final static native void delete_btSimulationIslandManager_IslandCallback(long jarg1);
public final static native void btSimulationIslandManager_IslandCallback_processIsland(long jarg1, btSimulationIslandManager.IslandCallback jarg1_, long jarg2, int jarg3, long jarg4, int jarg5, int jarg6);
public final static native void btSimulationIslandManager_buildAndProcessIslands(long jarg1, btSimulationIslandManager jarg1_, long jarg2, btDispatcher jarg2_, long jarg3, btCollisionWorld jarg3_, long jarg4, btSimulationIslandManager.IslandCallback jarg4_);
public final static native void btSimulationIslandManager_buildIslands(long jarg1, btSimulationIslandManager jarg1_, long jarg2, btDispatcher jarg2_, long jarg3, btCollisionWorld jarg3_);
public final static native boolean btSimulationIslandManager_getSplitIslands(long jarg1, btSimulationIslandManager jarg1_);
public final static native void btSimulationIslandManager_setSplitIslands(long jarg1, btSimulationIslandManager jarg1_, boolean jarg2);
public final static native long new_btGhostObject();
public final static native void delete_btGhostObject(long jarg1);
public final static native void btGhostObject_convexSweepTest__SWIG_0(long jarg1, btGhostObject jarg1_, long jarg2, btConvexShape jarg2_, Matrix4 jarg3, Matrix4 jarg4, long jarg5, ConvexResultCallback jarg5_, float jarg6);
public final static native void btGhostObject_convexSweepTest__SWIG_1(long jarg1, btGhostObject jarg1_, long jarg2, btConvexShape jarg2_, Matrix4 jarg3, Matrix4 jarg4, long jarg5, ConvexResultCallback jarg5_);
public final static native void btGhostObject_rayTest(long jarg1, btGhostObject jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, RayResultCallback jarg4_);
public final static native void btGhostObject_addOverlappingObjectInternal__SWIG_0(long jarg1, btGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native void btGhostObject_addOverlappingObjectInternal__SWIG_1(long jarg1, btGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native void btGhostObject_removeOverlappingObjectInternal__SWIG_0(long jarg1, btGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_, long jarg4, btBroadphaseProxy jarg4_);
public final static native void btGhostObject_removeOverlappingObjectInternal__SWIG_1(long jarg1, btGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native int btGhostObject_getNumOverlappingObjects(long jarg1, btGhostObject jarg1_);
public final static native long btGhostObject_getOverlappingObject__SWIG_0(long jarg1, btGhostObject jarg1_, int jarg2);
public final static native long btGhostObject_getOverlappingPairs__SWIG_0(long jarg1, btGhostObject jarg1_);
public final static native long btGhostObject_upcast__SWIG_0(long jarg1, btCollisionObject jarg1_);
public final static native long new_btPairCachingGhostObject();
public final static native void delete_btPairCachingGhostObject(long jarg1);
public final static native void btPairCachingGhostObject_addOverlappingObjectInternal__SWIG_0(long jarg1, btPairCachingGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native void btPairCachingGhostObject_addOverlappingObjectInternal__SWIG_1(long jarg1, btPairCachingGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native void btPairCachingGhostObject_removeOverlappingObjectInternal__SWIG_0(long jarg1, btPairCachingGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_, long jarg4, btBroadphaseProxy jarg4_);
public final static native void btPairCachingGhostObject_removeOverlappingObjectInternal__SWIG_1(long jarg1, btPairCachingGhostObject jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native long btPairCachingGhostObject_getOverlappingPairCache(long jarg1, btPairCachingGhostObject jarg1_);
public final static native long new_btGhostPairCallback();
public final static native void delete_btGhostPairCallback(long jarg1);
public final static native long btGhostPairCallback_addOverlappingPair(long jarg1, btGhostPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btGhostPairCallback_addOverlappingPairSwigExplicitbtGhostPairCallback(long jarg1, btGhostPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_);
public final static native long btGhostPairCallback_removeOverlappingPair(long jarg1, btGhostPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_, long jarg4, btDispatcher jarg4_);
public final static native long btGhostPairCallback_removeOverlappingPairSwigExplicitbtGhostPairCallback(long jarg1, btGhostPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btBroadphaseProxy jarg3_, long jarg4, btDispatcher jarg4_);
public final static native void btGhostPairCallback_removeOverlappingPairsContainingProxy(long jarg1, btGhostPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native void btGhostPairCallback_removeOverlappingPairsContainingProxySwigExplicitbtGhostPairCallback(long jarg1, btGhostPairCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_, long jarg3, btDispatcher jarg3_);
public final static native void btGhostPairCallback_director_connect(btGhostPairCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btGhostPairCallback_change_ownership(btGhostPairCallback obj, long cptr, boolean take_or_release);
public final static native long new_btCollisionWorld(long jarg1, btDispatcher jarg1_, long jarg2, btBroadphaseInterface jarg2_, long jarg3, btCollisionConfiguration jarg3_);
public final static native void delete_btCollisionWorld(long jarg1);
public final static native void btCollisionWorld_setBroadphase(long jarg1, btCollisionWorld jarg1_, long jarg2, btBroadphaseInterface jarg2_);
public final static native long btCollisionWorld_getBroadphase__SWIG_0(long jarg1, btCollisionWorld jarg1_);
public final static native long btCollisionWorld_getPairCache(long jarg1, btCollisionWorld jarg1_);
public final static native long btCollisionWorld_getDispatcher__SWIG_0(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_updateSingleAabb(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native void btCollisionWorld_updateAabbs(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_computeOverlappingPairs(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_setDebugDrawer(long jarg1, btCollisionWorld jarg1_, long jarg2, btIDebugDraw jarg2_);
public final static native long btCollisionWorld_getDebugDrawer(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_debugDrawWorld(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_debugDrawObject(long jarg1, btCollisionWorld jarg1_, Matrix4 jarg2, long jarg3, btCollisionShape jarg3_, Vector3 jarg4);
public final static native int btCollisionWorld_getNumCollisionObjects(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_rayTest(long jarg1, btCollisionWorld jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, RayResultCallback jarg4_);
public final static native void btCollisionWorld_convexSweepTest__SWIG_0(long jarg1, btCollisionWorld jarg1_, long jarg2, btConvexShape jarg2_, Matrix4 jarg3, Matrix4 jarg4, long jarg5, ConvexResultCallback jarg5_, float jarg6);
public final static native void btCollisionWorld_convexSweepTest__SWIG_1(long jarg1, btCollisionWorld jarg1_, long jarg2, btConvexShape jarg2_, Matrix4 jarg3, Matrix4 jarg4, long jarg5, ConvexResultCallback jarg5_);
public final static native void btCollisionWorld_contactTest(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, ContactResultCallback jarg3_);
public final static native void btCollisionWorld_contactPairTest(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_, long jarg4, ContactResultCallback jarg4_);
public final static native void btCollisionWorld_rayTestSingle(Matrix4 jarg1, Matrix4 jarg2, long jarg3, btCollisionObject jarg3_, long jarg4, btCollisionShape jarg4_, Matrix4 jarg5, long jarg6, RayResultCallback jarg6_);
public final static native void btCollisionWorld_rayTestSingleInternal(Matrix4 jarg1, Matrix4 jarg2, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, RayResultCallback jarg4_);
public final static native void btCollisionWorld_objectQuerySingle(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, Matrix4 jarg3, long jarg4, btCollisionObject jarg4_, long jarg5, btCollisionShape jarg5_, Matrix4 jarg6, long jarg7, ConvexResultCallback jarg7_, float jarg8);
public final static native void btCollisionWorld_objectQuerySingleInternal(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, Matrix4 jarg3, long jarg4, btCollisionObjectWrapper jarg4_, long jarg5, ConvexResultCallback jarg5_, float jarg6);
public final static native void btCollisionWorld_addCollisionObject__SWIG_0(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_, short jarg3, short jarg4);
public final static native void btCollisionWorld_addCollisionObject__SWIG_1(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_, short jarg3);
public final static native void btCollisionWorld_addCollisionObject__SWIG_2(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long btCollisionWorld_getCollisionObjectArray__SWIG_0(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_removeCollisionObject(long jarg1, btCollisionWorld jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native void btCollisionWorld_performDiscreteCollisionDetection(long jarg1, btCollisionWorld jarg1_);
public final static native long btCollisionWorld_getDispatchInfo__SWIG_0(long jarg1, btCollisionWorld jarg1_);
public final static native boolean btCollisionWorld_getForceUpdateAllAabbs(long jarg1, btCollisionWorld jarg1_);
public final static native void btCollisionWorld_setForceUpdateAllAabbs(long jarg1, btCollisionWorld jarg1_, boolean jarg2);
public final static native void btCollisionWorld_serialize(long jarg1, btCollisionWorld jarg1_, long jarg2);
public final static native void LocalShapeInfo_shapePart_set(long jarg1, LocalShapeInfo jarg1_, int jarg2);
public final static native int LocalShapeInfo_shapePart_get(long jarg1, LocalShapeInfo jarg1_);
public final static native void LocalShapeInfo_triangleIndex_set(long jarg1, LocalShapeInfo jarg1_, int jarg2);
public final static native int LocalShapeInfo_triangleIndex_get(long jarg1, LocalShapeInfo jarg1_);
public final static native long new_LocalShapeInfo();
public final static native void delete_LocalShapeInfo(long jarg1);
public final static native long new_LocalRayResult(long jarg1, btCollisionObject jarg1_, long jarg2, LocalShapeInfo jarg2_, Vector3 jarg3, float jarg4);
public final static native void LocalRayResult_collisionObject_set(long jarg1, LocalRayResult jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long LocalRayResult_collisionObject_get(long jarg1, LocalRayResult jarg1_);
public final static native void LocalRayResult_localShapeInfo_set(long jarg1, LocalRayResult jarg1_, long jarg2, LocalShapeInfo jarg2_);
public final static native long LocalRayResult_localShapeInfo_get(long jarg1, LocalRayResult jarg1_);
public final static native void LocalRayResult_hitNormalLocal_set(long jarg1, LocalRayResult jarg1_, long jarg2, btVector3 jarg2_);
public final static native long LocalRayResult_hitNormalLocal_get(long jarg1, LocalRayResult jarg1_);
public final static native void LocalRayResult_hitFraction_set(long jarg1, LocalRayResult jarg1_, float jarg2);
public final static native float LocalRayResult_hitFraction_get(long jarg1, LocalRayResult jarg1_);
public final static native void delete_LocalRayResult(long jarg1);
public final static native void RayResultCallback_closestHitFraction_set(long jarg1, RayResultCallback jarg1_, float jarg2);
public final static native float RayResultCallback_closestHitFraction_get(long jarg1, RayResultCallback jarg1_);
public final static native void RayResultCallback_collisionObject_set(long jarg1, RayResultCallback jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long RayResultCallback_collisionObject_get(long jarg1, RayResultCallback jarg1_);
public final static native void RayResultCallback_collisionFilterGroup_set(long jarg1, RayResultCallback jarg1_, short jarg2);
public final static native short RayResultCallback_collisionFilterGroup_get(long jarg1, RayResultCallback jarg1_);
public final static native void RayResultCallback_collisionFilterMask_set(long jarg1, RayResultCallback jarg1_, short jarg2);
public final static native short RayResultCallback_collisionFilterMask_get(long jarg1, RayResultCallback jarg1_);
public final static native void RayResultCallback_flags_set(long jarg1, RayResultCallback jarg1_, long jarg2);
public final static native long RayResultCallback_flags_get(long jarg1, RayResultCallback jarg1_);
public final static native void delete_RayResultCallback(long jarg1);
public final static native boolean RayResultCallback_hasHit(long jarg1, RayResultCallback jarg1_);
public final static native long new_RayResultCallback();
public final static native boolean RayResultCallback_needsCollision(long jarg1, RayResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native boolean RayResultCallback_needsCollisionSwigExplicitRayResultCallback(long jarg1, RayResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native float RayResultCallback_addSingleResult(long jarg1, RayResultCallback jarg1_, long jarg2, LocalRayResult jarg2_, boolean jarg3);
public final static native void RayResultCallback_director_connect(RayResultCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void RayResultCallback_change_ownership(RayResultCallback obj, long cptr, boolean take_or_release);
public final static native long new_ClosestRayResultCallback(Vector3 jarg1, Vector3 jarg2);
public final static native float ClosestRayResultCallback_addSingleResult(long jarg1, ClosestRayResultCallback jarg1_, long jarg2, LocalRayResult jarg2_, boolean jarg3);
public final static native float ClosestRayResultCallback_addSingleResultSwigExplicitClosestRayResultCallback(long jarg1, ClosestRayResultCallback jarg1_, long jarg2, LocalRayResult jarg2_, boolean jarg3);
public final static native void ClosestRayResultCallback_getRayFromWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_setRayFromWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_getRayToWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_setRayToWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_getHitNormalWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_setHitNormalWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_getHitPointWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestRayResultCallback_setHitPointWorld(long jarg1, ClosestRayResultCallback jarg1_, Vector3 jarg2);
public final static native void delete_ClosestRayResultCallback(long jarg1);
public final static native void ClosestRayResultCallback_director_connect(ClosestRayResultCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void ClosestRayResultCallback_change_ownership(ClosestRayResultCallback obj, long cptr, boolean take_or_release);
public final static native long new_AllHitsRayResultCallback(Vector3 jarg1, Vector3 jarg2);
public final static native void AllHitsRayResultCallback_collisionObjects_set(long jarg1, AllHitsRayResultCallback jarg1_, long jarg2, btCollisionObjectConstArray jarg2_);
public final static native long AllHitsRayResultCallback_collisionObjects_get(long jarg1, AllHitsRayResultCallback jarg1_);
public final static native void AllHitsRayResultCallback_hitNormalWorld_set(long jarg1, AllHitsRayResultCallback jarg1_, long jarg2, btVector3Array jarg2_);
public final static native long AllHitsRayResultCallback_hitNormalWorld_get(long jarg1, AllHitsRayResultCallback jarg1_);
public final static native void AllHitsRayResultCallback_hitPointWorld_set(long jarg1, AllHitsRayResultCallback jarg1_, long jarg2, btVector3Array jarg2_);
public final static native long AllHitsRayResultCallback_hitPointWorld_get(long jarg1, AllHitsRayResultCallback jarg1_);
public final static native void AllHitsRayResultCallback_hitFractions_set(long jarg1, AllHitsRayResultCallback jarg1_, long jarg2, btScalarArray jarg2_);
public final static native long AllHitsRayResultCallback_hitFractions_get(long jarg1, AllHitsRayResultCallback jarg1_);
public final static native float AllHitsRayResultCallback_addSingleResult(long jarg1, AllHitsRayResultCallback jarg1_, long jarg2, LocalRayResult jarg2_, boolean jarg3);
public final static native float AllHitsRayResultCallback_addSingleResultSwigExplicitAllHitsRayResultCallback(long jarg1, AllHitsRayResultCallback jarg1_, long jarg2, LocalRayResult jarg2_, boolean jarg3);
public final static native void AllHitsRayResultCallback_getRayFromWorld(long jarg1, AllHitsRayResultCallback jarg1_, Vector3 jarg2);
public final static native void AllHitsRayResultCallback_setRayFromWorld(long jarg1, AllHitsRayResultCallback jarg1_, Vector3 jarg2);
public final static native void AllHitsRayResultCallback_getRayToWorld(long jarg1, AllHitsRayResultCallback jarg1_, Vector3 jarg2);
public final static native void AllHitsRayResultCallback_setRayToWorld(long jarg1, AllHitsRayResultCallback jarg1_, Vector3 jarg2);
public final static native void delete_AllHitsRayResultCallback(long jarg1);
public final static native void AllHitsRayResultCallback_director_connect(AllHitsRayResultCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void AllHitsRayResultCallback_change_ownership(AllHitsRayResultCallback obj, long cptr, boolean take_or_release);
public final static native long new_LocalConvexResult(long jarg1, btCollisionObject jarg1_, long jarg2, LocalShapeInfo jarg2_, Vector3 jarg3, Vector3 jarg4, float jarg5);
public final static native void LocalConvexResult_hitCollisionObject_set(long jarg1, LocalConvexResult jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long LocalConvexResult_hitCollisionObject_get(long jarg1, LocalConvexResult jarg1_);
public final static native void LocalConvexResult_localShapeInfo_set(long jarg1, LocalConvexResult jarg1_, long jarg2, LocalShapeInfo jarg2_);
public final static native long LocalConvexResult_localShapeInfo_get(long jarg1, LocalConvexResult jarg1_);
public final static native void LocalConvexResult_hitFraction_set(long jarg1, LocalConvexResult jarg1_, float jarg2);
public final static native float LocalConvexResult_hitFraction_get(long jarg1, LocalConvexResult jarg1_);
public final static native void LocalConvexResult_getHitNormalLocal(long jarg1, LocalConvexResult jarg1_, Vector3 jarg2);
public final static native void LocalConvexResult_setHitNormalLocal(long jarg1, LocalConvexResult jarg1_, Vector3 jarg2);
public final static native void LocalConvexResult_getHitPointLocal(long jarg1, LocalConvexResult jarg1_, Vector3 jarg2);
public final static native void LocalConvexResult_setHitPointLocal(long jarg1, LocalConvexResult jarg1_, Vector3 jarg2);
public final static native void delete_LocalConvexResult(long jarg1);
public final static native void ConvexResultCallback_closestHitFraction_set(long jarg1, ConvexResultCallback jarg1_, float jarg2);
public final static native float ConvexResultCallback_closestHitFraction_get(long jarg1, ConvexResultCallback jarg1_);
public final static native void ConvexResultCallback_collisionFilterGroup_set(long jarg1, ConvexResultCallback jarg1_, short jarg2);
public final static native short ConvexResultCallback_collisionFilterGroup_get(long jarg1, ConvexResultCallback jarg1_);
public final static native void ConvexResultCallback_collisionFilterMask_set(long jarg1, ConvexResultCallback jarg1_, short jarg2);
public final static native short ConvexResultCallback_collisionFilterMask_get(long jarg1, ConvexResultCallback jarg1_);
public final static native long new_ConvexResultCallback();
public final static native void delete_ConvexResultCallback(long jarg1);
public final static native boolean ConvexResultCallback_hasHit(long jarg1, ConvexResultCallback jarg1_);
public final static native boolean ConvexResultCallback_needsCollision(long jarg1, ConvexResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native boolean ConvexResultCallback_needsCollisionSwigExplicitConvexResultCallback(long jarg1, ConvexResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native float ConvexResultCallback_addSingleResult(long jarg1, ConvexResultCallback jarg1_, long jarg2, LocalConvexResult jarg2_, boolean jarg3);
public final static native void ConvexResultCallback_director_connect(ConvexResultCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void ConvexResultCallback_change_ownership(ConvexResultCallback obj, long cptr, boolean take_or_release);
public final static native long new_ClosestConvexResultCallback(Vector3 jarg1, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_convexFromWorld_set(long jarg1, ClosestConvexResultCallback jarg1_, long jarg2, btVector3 jarg2_);
public final static native long ClosestConvexResultCallback_convexFromWorld_get(long jarg1, ClosestConvexResultCallback jarg1_);
public final static native void ClosestConvexResultCallback_convexToWorld_set(long jarg1, ClosestConvexResultCallback jarg1_, long jarg2, btVector3 jarg2_);
public final static native long ClosestConvexResultCallback_convexToWorld_get(long jarg1, ClosestConvexResultCallback jarg1_);
public final static native void ClosestConvexResultCallback_hitCollisionObject_set(long jarg1, ClosestConvexResultCallback jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long ClosestConvexResultCallback_hitCollisionObject_get(long jarg1, ClosestConvexResultCallback jarg1_);
public final static native float ClosestConvexResultCallback_addSingleResult(long jarg1, ClosestConvexResultCallback jarg1_, long jarg2, LocalConvexResult jarg2_, boolean jarg3);
public final static native float ClosestConvexResultCallback_addSingleResultSwigExplicitClosestConvexResultCallback(long jarg1, ClosestConvexResultCallback jarg1_, long jarg2, LocalConvexResult jarg2_, boolean jarg3);
public final static native void ClosestConvexResultCallback_getConvexFromWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_setRayFromWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_getConvexToWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_setConvexToWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_getHitNormalWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_setHitNormalWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_getHitPointWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void ClosestConvexResultCallback_setHitPointWorld(long jarg1, ClosestConvexResultCallback jarg1_, Vector3 jarg2);
public final static native void delete_ClosestConvexResultCallback(long jarg1);
public final static native void ClosestConvexResultCallback_director_connect(ClosestConvexResultCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void ClosestConvexResultCallback_change_ownership(ClosestConvexResultCallback obj, long cptr, boolean take_or_release);
public final static native void ContactResultCallback_collisionFilterGroup_set(long jarg1, ContactResultCallback jarg1_, short jarg2);
public final static native short ContactResultCallback_collisionFilterGroup_get(long jarg1, ContactResultCallback jarg1_);
public final static native void ContactResultCallback_collisionFilterMask_set(long jarg1, ContactResultCallback jarg1_, short jarg2);
public final static native short ContactResultCallback_collisionFilterMask_get(long jarg1, ContactResultCallback jarg1_);
public final static native long new_ContactResultCallback();
public final static native void delete_ContactResultCallback(long jarg1);
public final static native boolean ContactResultCallback_needsCollision(long jarg1, ContactResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native boolean ContactResultCallback_needsCollisionSwigExplicitContactResultCallback(long jarg1, ContactResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native float ContactResultCallback_addSingleResult(long jarg1, ContactResultCallback jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, int jarg4, int jarg5, long jarg6, btCollisionObjectWrapper jarg6_, int jarg7, int jarg8);
public final static native void ContactResultCallback_director_connect(ContactResultCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void ContactResultCallback_change_ownership(ContactResultCallback obj, long cptr, boolean take_or_release);
public final static native void ClosestNotMeConvexResultCallback_me_set(long jarg1, ClosestNotMeConvexResultCallback jarg1_, long jarg2, btCollisionObject jarg2_);
public final static native long ClosestNotMeConvexResultCallback_me_get(long jarg1, ClosestNotMeConvexResultCallback jarg1_);
public final static native void ClosestNotMeConvexResultCallback_allowedPenetration_set(long jarg1, ClosestNotMeConvexResultCallback jarg1_, float jarg2);
public final static native float ClosestNotMeConvexResultCallback_allowedPenetration_get(long jarg1, ClosestNotMeConvexResultCallback jarg1_);
public final static native long new_ClosestNotMeConvexResultCallback(long jarg1, btCollisionObject jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native boolean ClosestNotMeConvexResultCallback_needsCollision(long jarg1, ClosestNotMeConvexResultCallback jarg1_, long jarg2, btBroadphaseProxy jarg2_);
public final static native void delete_ClosestNotMeConvexResultCallback(long jarg1);
public final static native long new_ClosestNotMeRayResultCallback(long jarg1, btCollisionObject jarg1_);
public final static native void delete_ClosestNotMeRayResultCallback(long jarg1);
public final static native long new_btConvex2dConvex2dAlgorithm(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, long jarg5, btVoronoiSimplexSolver jarg5_, long jarg6, btConvexPenetrationDepthSolver jarg6_, int jarg7, int jarg8);
public final static native void delete_btConvex2dConvex2dAlgorithm(long jarg1);
public final static native void btConvex2dConvex2dAlgorithm_setLowLevelOfDetail(long jarg1, btConvex2dConvex2dAlgorithm jarg1_, boolean jarg2);
public final static native long btConvex2dConvex2dAlgorithm_getManifold(long jarg1, btConvex2dConvex2dAlgorithm jarg1_);
public final static native void btConvex2dConvex2dAlgorithm_CreateFunc_pdSolver_set(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_, long jarg2, btConvexPenetrationDepthSolver jarg2_);
public final static native long btConvex2dConvex2dAlgorithm_CreateFunc_pdSolver_get(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_);
public final static native void btConvex2dConvex2dAlgorithm_CreateFunc_simplexSolver_set(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_, long jarg2, btVoronoiSimplexSolver jarg2_);
public final static native long btConvex2dConvex2dAlgorithm_CreateFunc_simplexSolver_get(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_);
public final static native void btConvex2dConvex2dAlgorithm_CreateFunc_numPerturbationIterations_set(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_, int jarg2);
public final static native int btConvex2dConvex2dAlgorithm_CreateFunc_numPerturbationIterations_get(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_);
public final static native void btConvex2dConvex2dAlgorithm_CreateFunc_minimumPointsPerturbationThreshold_set(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_, int jarg2);
public final static native int btConvex2dConvex2dAlgorithm_CreateFunc_minimumPointsPerturbationThreshold_get(long jarg1, btConvex2dConvex2dAlgorithm.CreateFunc jarg1_);
public final static native long new_btConvex2dConvex2dAlgorithm_CreateFunc(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btConvexPenetrationDepthSolver jarg2_);
public final static native void delete_btConvex2dConvex2dAlgorithm_CreateFunc(long jarg1);
public final static native void btBoxBoxDetector_box1_set(long jarg1, btBoxBoxDetector jarg1_, long jarg2, btBoxShape jarg2_);
public final static native long btBoxBoxDetector_box1_get(long jarg1, btBoxBoxDetector jarg1_);
public final static native void btBoxBoxDetector_box2_set(long jarg1, btBoxBoxDetector jarg1_, long jarg2, btBoxShape jarg2_);
public final static native long btBoxBoxDetector_box2_get(long jarg1, btBoxBoxDetector jarg1_);
public final static native long new_btBoxBoxDetector(long jarg1, btBoxShape jarg1_, long jarg2, btBoxShape jarg2_);
public final static native void delete_btBoxBoxDetector(long jarg1);
public final static native void btBoxBoxDetector_getClosestPoints__SWIG_0(long jarg1, btBoxBoxDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_, boolean jarg5);
public final static native void btBoxBoxDetector_getClosestPoints__SWIG_1(long jarg1, btBoxBoxDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_);
public final static native long new_btSphereBoxCollisionAlgorithm(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, boolean jarg5);
public final static native void delete_btSphereBoxCollisionAlgorithm(long jarg1);
public final static native boolean btSphereBoxCollisionAlgorithm_getSphereDistance(long jarg1, btSphereBoxCollisionAlgorithm jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, Vector3 jarg3, Vector3 jarg4, long jarg5, Vector3 jarg6, float jarg7, float jarg8);
public final static native float btSphereBoxCollisionAlgorithm_getSpherePenetration(long jarg1, btSphereBoxCollisionAlgorithm jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5);
public final static native long new_btSphereBoxCollisionAlgorithm_CreateFunc();
public final static native void delete_btSphereBoxCollisionAlgorithm_CreateFunc(long jarg1);
public final static native int btCollisionDispatcher_getDispatcherFlags(long jarg1, btCollisionDispatcher jarg1_);
public final static native void btCollisionDispatcher_setDispatcherFlags(long jarg1, btCollisionDispatcher jarg1_, int jarg2);
public final static native void btCollisionDispatcher_registerCollisionCreateFunc(long jarg1, btCollisionDispatcher jarg1_, int jarg2, int jarg3, long jarg4, btCollisionAlgorithmCreateFunc jarg4_);
public final static native long btCollisionDispatcher_getManifoldByIndexInternal__SWIG_0(long jarg1, btCollisionDispatcher jarg1_, int jarg2);
public final static native long new_btCollisionDispatcher(long jarg1, btCollisionConfiguration jarg1_);
public final static native void delete_btCollisionDispatcher(long jarg1);
public final static native long btCollisionDispatcher_findAlgorithm__SWIG_0(long jarg1, btCollisionDispatcher jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btPersistentManifold jarg4_);
public final static native long btCollisionDispatcher_findAlgorithm__SWIG_1(long jarg1, btCollisionDispatcher jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_);
public final static native void btCollisionDispatcher_setNearCallback(long jarg1, btCollisionDispatcher jarg1_, long jarg2);
public final static native long btCollisionDispatcher_getNearCallback(long jarg1, btCollisionDispatcher jarg1_);
public final static native void btCollisionDispatcher_defaultNearCallback(btBroadphasePair jarg1, long jarg2, btCollisionDispatcher jarg2_, long jarg3, btDispatcherInfo jarg3_);
public final static native long btCollisionDispatcher_getCollisionConfiguration__SWIG_0(long jarg1, btCollisionDispatcher jarg1_);
public final static native void btCollisionDispatcher_setCollisionConfiguration(long jarg1, btCollisionDispatcher jarg1_, long jarg2, btCollisionConfiguration jarg2_);
public final static native long btCollisionDispatcher_getInternalManifoldPool__SWIG_0(long jarg1, btCollisionDispatcher jarg1_);
public final static native long new_btConvexConvexAlgorithm(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionAlgorithmConstructionInfo jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btCollisionObjectWrapper jarg4_, long jarg5, btVoronoiSimplexSolver jarg5_, long jarg6, btConvexPenetrationDepthSolver jarg6_, int jarg7, int jarg8);
public final static native void delete_btConvexConvexAlgorithm(long jarg1);
public final static native void btConvexConvexAlgorithm_setLowLevelOfDetail(long jarg1, btConvexConvexAlgorithm jarg1_, boolean jarg2);
public final static native long btConvexConvexAlgorithm_getManifold(long jarg1, btConvexConvexAlgorithm jarg1_);
public final static native void btConvexConvexAlgorithm_CreateFunc_pdSolver_set(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_, long jarg2, btConvexPenetrationDepthSolver jarg2_);
public final static native long btConvexConvexAlgorithm_CreateFunc_pdSolver_get(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_);
public final static native void btConvexConvexAlgorithm_CreateFunc_simplexSolver_set(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_, long jarg2, btVoronoiSimplexSolver jarg2_);
public final static native long btConvexConvexAlgorithm_CreateFunc_simplexSolver_get(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_);
public final static native void btConvexConvexAlgorithm_CreateFunc_numPerturbationIterations_set(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_, int jarg2);
public final static native int btConvexConvexAlgorithm_CreateFunc_numPerturbationIterations_get(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_);
public final static native void btConvexConvexAlgorithm_CreateFunc_minimumPointsPerturbationThreshold_set(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_, int jarg2);
public final static native int btConvexConvexAlgorithm_CreateFunc_minimumPointsPerturbationThreshold_get(long jarg1, btConvexConvexAlgorithm.CreateFunc jarg1_);
public final static native long new_btConvexConvexAlgorithm_CreateFunc(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btConvexPenetrationDepthSolver jarg2_);
public final static native void delete_btConvexConvexAlgorithm_CreateFunc(long jarg1);
public final static native void SphereTriangleDetector_getClosestPoints__SWIG_0(long jarg1, SphereTriangleDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_, boolean jarg5);
public final static native void SphereTriangleDetector_getClosestPoints__SWIG_1(long jarg1, SphereTriangleDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_);
public final static native long new_SphereTriangleDetector(long jarg1, btSphereShape jarg1_, long jarg2, btTriangleShape jarg2_, float jarg3);
public final static native void delete_SphereTriangleDetector(long jarg1);
public final static native boolean SphereTriangleDetector_collide(long jarg1, SphereTriangleDetector jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, long jarg5, long jarg6, float jarg7);
public final static native void btGenerateInternalEdgeInfo(long jarg1, btBvhTriangleMeshShape jarg1_, long jarg2, btTriangleInfoMap jarg2_);
public final static native void btAdjustInternalEdgeContacts__SWIG_0(long jarg1, btManifoldPoint jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, int jarg4, int jarg5, int jarg6);
public final static native void btAdjustInternalEdgeContacts__SWIG_1(long jarg1, btManifoldPoint jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, int jarg4, int jarg5);
public final static native void gCompoundChildShapePairCallback_set(long jarg1);
public final static native long gCompoundChildShapePairCallback_get();
public final static native long new_btCompoundCollisionAlgorithm(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, boolean jarg4);
public final static native void delete_btCompoundCollisionAlgorithm(long jarg1);
public final static native long btCompoundCollisionAlgorithm_getChildAlgorithm(long jarg1, btCompoundCollisionAlgorithm jarg1_, int jarg2);
public final static native long new_btCompoundCollisionAlgorithm_CreateFunc();
public final static native void delete_btCompoundCollisionAlgorithm_CreateFunc(long jarg1);
public final static native long new_btCompoundCollisionAlgorithm_SwappedCreateFunc();
public final static native void delete_btCompoundCollisionAlgorithm_SwappedCreateFunc(long jarg1);
public final static native void delete_btConvexCast(long jarg1);
public final static native void btConvexCast_CastResult_DebugDraw(long jarg1, btConvexCast.CastResult jarg1_, float jarg2);
public final static native void btConvexCast_CastResult_drawCoordSystem(long jarg1, btConvexCast.CastResult jarg1_, Matrix4 jarg2);
public final static native void btConvexCast_CastResult_reportFailure(long jarg1, btConvexCast.CastResult jarg1_, int jarg2, int jarg3);
public final static native long new_btConvexCast_CastResult();
public final static native void delete_btConvexCast_CastResult(long jarg1);
public final static native void btConvexCast_CastResult_hitTransformA_set(long jarg1, btConvexCast.CastResult jarg1_, long jarg2, btTransform jarg2_);
public final static native long btConvexCast_CastResult_hitTransformA_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native void btConvexCast_CastResult_hitTransformB_set(long jarg1, btConvexCast.CastResult jarg1_, long jarg2, btTransform jarg2_);
public final static native long btConvexCast_CastResult_hitTransformB_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native void btConvexCast_CastResult_normal_set(long jarg1, btConvexCast.CastResult jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btConvexCast_CastResult_normal_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native void btConvexCast_CastResult_hitPoint_set(long jarg1, btConvexCast.CastResult jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btConvexCast_CastResult_hitPoint_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native void btConvexCast_CastResult_fraction_set(long jarg1, btConvexCast.CastResult jarg1_, float jarg2);
public final static native float btConvexCast_CastResult_fraction_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native void btConvexCast_CastResult_debugDrawer_set(long jarg1, btConvexCast.CastResult jarg1_, long jarg2, btIDebugDraw jarg2_);
public final static native long btConvexCast_CastResult_debugDrawer_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native void btConvexCast_CastResult_allowedPenetration_set(long jarg1, btConvexCast.CastResult jarg1_, float jarg2);
public final static native float btConvexCast_CastResult_allowedPenetration_get(long jarg1, btConvexCast.CastResult jarg1_);
public final static native boolean btConvexCast_calcTimeOfImpact(long jarg1, btConvexCast jarg1_, Matrix4 jarg2, Matrix4 jarg3, Matrix4 jarg4, Matrix4 jarg5, long jarg6, btConvexCast.CastResult jarg6_);
public final static native long new_btSubsimplexConvexCast(long jarg1, btConvexShape jarg1_, long jarg2, btConvexShape jarg2_, long jarg3, btVoronoiSimplexSolver jarg3_);
public final static native void delete_btSubsimplexConvexCast(long jarg1);
public final static native void btPolyhedralContactClipping_clipHullAgainstHull(Vector3 jarg1, long jarg2, btConvexPolyhedron jarg2_, long jarg3, btConvexPolyhedron jarg3_, Matrix4 jarg4, Matrix4 jarg5, float jarg6, float jarg7, long jarg8, btDiscreteCollisionDetectorInterface.Result jarg8_);
public final static native void btPolyhedralContactClipping_clipFaceAgainstHull(Vector3 jarg1, long jarg2, btConvexPolyhedron jarg2_, Matrix4 jarg3, long jarg4, btVector3Array jarg4_, float jarg5, float jarg6, long jarg7, btDiscreteCollisionDetectorInterface.Result jarg7_);
public final static native boolean btPolyhedralContactClipping_findSeparatingAxis(long jarg1, btConvexPolyhedron jarg1_, long jarg2, btConvexPolyhedron jarg2_, Matrix4 jarg3, Matrix4 jarg4, Vector3 jarg5, long jarg6, btDiscreteCollisionDetectorInterface.Result jarg6_);
public final static native void btPolyhedralContactClipping_clipFace(long jarg1, btVector3Array jarg1_, long jarg2, btVector3Array jarg2_, Vector3 jarg3, float jarg4);
public final static native long new_btPolyhedralContactClipping();
public final static native void delete_btPolyhedralContactClipping(long jarg1);
public final static native void gContactBreakingThreshold_set(float jarg1);
public final static native float gContactBreakingThreshold_get();
public final static native void btPersistentManifold_companionIdA_set(long jarg1, btPersistentManifold jarg1_, int jarg2);
public final static native int btPersistentManifold_companionIdA_get(long jarg1, btPersistentManifold jarg1_);
public final static native void btPersistentManifold_companionIdB_set(long jarg1, btPersistentManifold jarg1_, int jarg2);
public final static native int btPersistentManifold_companionIdB_get(long jarg1, btPersistentManifold jarg1_);
public final static native void btPersistentManifold_index1a_set(long jarg1, btPersistentManifold jarg1_, int jarg2);
public final static native int btPersistentManifold_index1a_get(long jarg1, btPersistentManifold jarg1_);
public final static native long new_btPersistentManifold__SWIG_0();
public final static native long new_btPersistentManifold__SWIG_1(long jarg1, btCollisionObject jarg1_, long jarg2, btCollisionObject jarg2_, int jarg3, float jarg4, float jarg5);
public final static native long btPersistentManifold_getBody0(long jarg1, btPersistentManifold jarg1_);
public final static native long btPersistentManifold_getBody1(long jarg1, btPersistentManifold jarg1_);
public final static native void btPersistentManifold_setBodies(long jarg1, btPersistentManifold jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void btPersistentManifold_clearUserCache(long jarg1, btPersistentManifold jarg1_, long jarg2, btManifoldPoint jarg2_);
public final static native int btPersistentManifold_getNumContacts(long jarg1, btPersistentManifold jarg1_);
public final static native void btPersistentManifold_setNumContacts(long jarg1, btPersistentManifold jarg1_, int jarg2);
public final static native long btPersistentManifold_getContactPoint__SWIG_0(long jarg1, btPersistentManifold jarg1_, int jarg2);
public final static native float btPersistentManifold_getContactBreakingThreshold(long jarg1, btPersistentManifold jarg1_);
public final static native float btPersistentManifold_getContactProcessingThreshold(long jarg1, btPersistentManifold jarg1_);
public final static native void btPersistentManifold_setContactBreakingThreshold(long jarg1, btPersistentManifold jarg1_, float jarg2);
public final static native void btPersistentManifold_setContactProcessingThreshold(long jarg1, btPersistentManifold jarg1_, float jarg2);
public final static native int btPersistentManifold_getCacheEntry(long jarg1, btPersistentManifold jarg1_, long jarg2, btManifoldPoint jarg2_);
public final static native int btPersistentManifold_addManifoldPoint__SWIG_0(long jarg1, btPersistentManifold jarg1_, long jarg2, btManifoldPoint jarg2_, boolean jarg3);
public final static native int btPersistentManifold_addManifoldPoint__SWIG_1(long jarg1, btPersistentManifold jarg1_, long jarg2, btManifoldPoint jarg2_);
public final static native void btPersistentManifold_removeContactPoint(long jarg1, btPersistentManifold jarg1_, int jarg2);
public final static native void btPersistentManifold_replaceContactPoint(long jarg1, btPersistentManifold jarg1_, long jarg2, btManifoldPoint jarg2_, int jarg3);
public final static native boolean btPersistentManifold_validContactDistance(long jarg1, btPersistentManifold jarg1_, long jarg2, btManifoldPoint jarg2_);
public final static native void btPersistentManifold_refreshContactPoints(long jarg1, btPersistentManifold jarg1_, Matrix4 jarg2, Matrix4 jarg3);
public final static native void btPersistentManifold_clearManifold(long jarg1, btPersistentManifold jarg1_);
public final static native void delete_btPersistentManifold(long jarg1);
public final static native long new_btPersistentManifoldArray__SWIG_0();
public final static native void delete_btPersistentManifoldArray(long jarg1);
public final static native long new_btPersistentManifoldArray__SWIG_1(long jarg1, btPersistentManifoldArray jarg1_);
public final static native int btPersistentManifoldArray_size(long jarg1, btPersistentManifoldArray jarg1_);
public final static native long btPersistentManifoldArray_at__SWIG_0(long jarg1, btPersistentManifoldArray jarg1_, int jarg2);
public final static native void btPersistentManifoldArray_clear(long jarg1, btPersistentManifoldArray jarg1_);
public final static native void btPersistentManifoldArray_pop_back(long jarg1, btPersistentManifoldArray jarg1_);
public final static native void btPersistentManifoldArray_resizeNoInitialize(long jarg1, btPersistentManifoldArray jarg1_, int jarg2);
public final static native void btPersistentManifoldArray_resize__SWIG_0(long jarg1, btPersistentManifoldArray jarg1_, int jarg2, long jarg3, btPersistentManifold jarg3_);
public final static native void btPersistentManifoldArray_resize__SWIG_1(long jarg1, btPersistentManifoldArray jarg1_, int jarg2);
public final static native long btPersistentManifoldArray_expandNonInitializing(long jarg1, btPersistentManifoldArray jarg1_);
public final static native long btPersistentManifoldArray_expand__SWIG_0(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native long btPersistentManifoldArray_expand__SWIG_1(long jarg1, btPersistentManifoldArray jarg1_);
public final static native void btPersistentManifoldArray_push_back(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native int btPersistentManifoldArray_capacity(long jarg1, btPersistentManifoldArray jarg1_);
public final static native void btPersistentManifoldArray_reserve(long jarg1, btPersistentManifoldArray jarg1_, int jarg2);
public final static native long new_btPersistentManifoldArray_less();
public final static native void delete_btPersistentManifoldArray_less(long jarg1);
public final static native void btPersistentManifoldArray_swap(long jarg1, btPersistentManifoldArray jarg1_, int jarg2, int jarg3);
public final static native int btPersistentManifoldArray_findBinarySearch(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native int btPersistentManifoldArray_findLinearSearch(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native void btPersistentManifoldArray_remove(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native void btPersistentManifoldArray_initializeFromBuffer(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, int jarg3, int jarg4);
public final static native void btPersistentManifoldArray_copyFromArray(long jarg1, btPersistentManifoldArray jarg1_, long jarg2, btPersistentManifoldArray jarg2_);
public final static native void btGjkPairDetector_lastUsedMethod_set(long jarg1, btGjkPairDetector jarg1_, int jarg2);
public final static native int btGjkPairDetector_lastUsedMethod_get(long jarg1, btGjkPairDetector jarg1_);
public final static native void btGjkPairDetector_curIter_set(long jarg1, btGjkPairDetector jarg1_, int jarg2);
public final static native int btGjkPairDetector_curIter_get(long jarg1, btGjkPairDetector jarg1_);
public final static native void btGjkPairDetector_degenerateSimplex_set(long jarg1, btGjkPairDetector jarg1_, int jarg2);
public final static native int btGjkPairDetector_degenerateSimplex_get(long jarg1, btGjkPairDetector jarg1_);
public final static native void btGjkPairDetector_catchDegeneracies_set(long jarg1, btGjkPairDetector jarg1_, int jarg2);
public final static native int btGjkPairDetector_catchDegeneracies_get(long jarg1, btGjkPairDetector jarg1_);
public final static native void btGjkPairDetector_fixContactNormalDirection_set(long jarg1, btGjkPairDetector jarg1_, int jarg2);
public final static native int btGjkPairDetector_fixContactNormalDirection_get(long jarg1, btGjkPairDetector jarg1_);
public final static native long new_btGjkPairDetector__SWIG_0(long jarg1, btConvexShape jarg1_, long jarg2, btConvexShape jarg2_, long jarg3, btVoronoiSimplexSolver jarg3_, long jarg4, btConvexPenetrationDepthSolver jarg4_);
public final static native long new_btGjkPairDetector__SWIG_1(long jarg1, btConvexShape jarg1_, long jarg2, btConvexShape jarg2_, int jarg3, int jarg4, float jarg5, float jarg6, long jarg7, btVoronoiSimplexSolver jarg7_, long jarg8, btConvexPenetrationDepthSolver jarg8_);
public final static native void delete_btGjkPairDetector(long jarg1);
public final static native void btGjkPairDetector_getClosestPoints__SWIG_0(long jarg1, btGjkPairDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_, boolean jarg5);
public final static native void btGjkPairDetector_getClosestPoints__SWIG_1(long jarg1, btGjkPairDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_);
public final static native void btGjkPairDetector_getClosestPointsNonVirtual(long jarg1, btGjkPairDetector jarg1_, long jarg2, btDiscreteCollisionDetectorInterface.ClosestPointInput jarg2_, long jarg3, btDiscreteCollisionDetectorInterface.Result jarg3_, long jarg4, btIDebugDraw jarg4_);
public final static native void btGjkPairDetector_setMinkowskiA(long jarg1, btGjkPairDetector jarg1_, long jarg2, btConvexShape jarg2_);
public final static native void btGjkPairDetector_setMinkowskiB(long jarg1, btGjkPairDetector jarg1_, long jarg2, btConvexShape jarg2_);
public final static native void btGjkPairDetector_setCachedSeperatingAxis(long jarg1, btGjkPairDetector jarg1_, Vector3 jarg2);
public final static native Vector3 btGjkPairDetector_getCachedSeparatingAxis(long jarg1, btGjkPairDetector jarg1_);
public final static native float btGjkPairDetector_getCachedSeparatingDistance(long jarg1, btGjkPairDetector jarg1_);
public final static native void btGjkPairDetector_setPenetrationDepthSolver(long jarg1, btGjkPairDetector jarg1_, long jarg2, btConvexPenetrationDepthSolver jarg2_);
public final static native void btGjkPairDetector_setIgnoreMargin(long jarg1, btGjkPairDetector jarg1_, boolean jarg2);
public final static native void delete_btConvexPenetrationDepthSolver(long jarg1);
public final static native boolean btConvexPenetrationDepthSolver_calcPenDepth(long jarg1, btConvexPenetrationDepthSolver jarg1_, long jarg2, btVoronoiSimplexSolver jarg2_, long jarg3, btConvexShape jarg3_, long jarg4, btConvexShape jarg4_, Matrix4 jarg5, Matrix4 jarg6, Vector3 jarg7, Vector3 jarg8, Vector3 jarg9, long jarg10, btIDebugDraw jarg10_);
public final static native long new_btMinkowskiPenetrationDepthSolver();
public final static native void delete_btMinkowskiPenetrationDepthSolver(long jarg1);
public final static native long new_btGjkConvexCast(long jarg1, btConvexShape jarg1_, long jarg2, btConvexShape jarg2_, long jarg3, btVoronoiSimplexSolver jarg3_);
public final static native void delete_btGjkConvexCast(long jarg1);
public final static native void btConstraintRow_normal_set(long jarg1, btConstraintRow jarg1_, float[] jarg2);
public final static native float[] btConstraintRow_normal_get(long jarg1, btConstraintRow jarg1_);
public final static native void btConstraintRow_rhs_set(long jarg1, btConstraintRow jarg1_, float jarg2);
public final static native float btConstraintRow_rhs_get(long jarg1, btConstraintRow jarg1_);
public final static native void btConstraintRow_jacDiagInv_set(long jarg1, btConstraintRow jarg1_, float jarg2);
public final static native float btConstraintRow_jacDiagInv_get(long jarg1, btConstraintRow jarg1_);
public final static native void btConstraintRow_lowerLimit_set(long jarg1, btConstraintRow jarg1_, float jarg2);
public final static native float btConstraintRow_lowerLimit_get(long jarg1, btConstraintRow jarg1_);
public final static native void btConstraintRow_upperLimit_set(long jarg1, btConstraintRow jarg1_, float jarg2);
public final static native float btConstraintRow_upperLimit_get(long jarg1, btConstraintRow jarg1_);
public final static native void btConstraintRow_accumImpulse_set(long jarg1, btConstraintRow jarg1_, float jarg2);
public final static native float btConstraintRow_accumImpulse_get(long jarg1, btConstraintRow jarg1_);
public final static native long new_btConstraintRow();
public final static native void delete_btConstraintRow(long jarg1);
public final static native long new_btManifoldPoint__SWIG_0();
public final static native long new_btManifoldPoint__SWIG_1(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, float jarg4);
public final static native void btManifoldPoint_distance1_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_distance1_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_combinedFriction_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_combinedFriction_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_combinedRollingFriction_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_combinedRollingFriction_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_combinedRestitution_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_combinedRestitution_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_partId0_set(long jarg1, btManifoldPoint jarg1_, int jarg2);
public final static native int btManifoldPoint_partId0_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_partId1_set(long jarg1, btManifoldPoint jarg1_, int jarg2);
public final static native int btManifoldPoint_partId1_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_index0_set(long jarg1, btManifoldPoint jarg1_, int jarg2);
public final static native int btManifoldPoint_index0_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_index1_set(long jarg1, btManifoldPoint jarg1_, int jarg2);
public final static native int btManifoldPoint_index1_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_userPersistentData_set(long jarg1, btManifoldPoint jarg1_, long jarg2);
public final static native long btManifoldPoint_userPersistentData_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_lateralFrictionInitialized_set(long jarg1, btManifoldPoint jarg1_, boolean jarg2);
public final static native boolean btManifoldPoint_lateralFrictionInitialized_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_appliedImpulse_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_appliedImpulse_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_appliedImpulseLateral1_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_appliedImpulseLateral1_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_appliedImpulseLateral2_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_appliedImpulseLateral2_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_contactMotion1_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_contactMotion1_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_contactMotion2_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_contactMotion2_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_contactCFM1_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_contactCFM1_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_contactCFM2_set(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native float btManifoldPoint_contactCFM2_get(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_lifeTime_set(long jarg1, btManifoldPoint jarg1_, int jarg2);
public final static native int btManifoldPoint_lifeTime_get(long jarg1, btManifoldPoint jarg1_);
public final static native float btManifoldPoint_getDistance(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_setDistance(long jarg1, btManifoldPoint jarg1_, float jarg2);
public final static native int btManifoldPoint_getUserValue(long jarg1, btManifoldPoint jarg1_);
public final static native void btManifoldPoint_setUserValue(long jarg1, btManifoldPoint jarg1_, int jarg2);
public final static native void btManifoldPoint_getLocalPointA(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setLocalPointA(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_getLocalPointB(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setLocalPointB(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_getPositionWorldOnA(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setPositionWorldOnA(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_getPositionWorldOnB(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setPositionWorldOnB(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_getNormalWorldOnB(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setNormalWorldOnB(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_getLateralFrictionDir1(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setLateralFrictionDir1(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_getLateralFrictionDir2(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void btManifoldPoint_setLateralFrictionDir2(long jarg1, btManifoldPoint jarg1_, Vector3 jarg2);
public final static native void delete_btManifoldPoint(long jarg1);
public final static native long new_btContinuousConvexCollision__SWIG_0(long jarg1, btConvexShape jarg1_, long jarg2, btConvexShape jarg2_, long jarg3, btVoronoiSimplexSolver jarg3_, long jarg4, btConvexPenetrationDepthSolver jarg4_);
public final static native long new_btContinuousConvexCollision__SWIG_1(long jarg1, btConvexShape jarg1_, long jarg2, btStaticPlaneShape jarg2_);
public final static native void delete_btContinuousConvexCollision(long jarg1);
public final static native void btTriangleRaycastCallback_from_set(long jarg1, btTriangleRaycastCallback jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btTriangleRaycastCallback_from_get(long jarg1, btTriangleRaycastCallback jarg1_);
public final static native void btTriangleRaycastCallback_to_set(long jarg1, btTriangleRaycastCallback jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btTriangleRaycastCallback_to_get(long jarg1, btTriangleRaycastCallback jarg1_);
public final static native void btTriangleRaycastCallback_flags_set(long jarg1, btTriangleRaycastCallback jarg1_, long jarg2);
public final static native long btTriangleRaycastCallback_flags_get(long jarg1, btTriangleRaycastCallback jarg1_);
public final static native void btTriangleRaycastCallback_hitFraction_set(long jarg1, btTriangleRaycastCallback jarg1_, float jarg2);
public final static native float btTriangleRaycastCallback_hitFraction_get(long jarg1, btTriangleRaycastCallback jarg1_);
public final static native long new_btTriangleRaycastCallback__SWIG_0(Vector3 jarg1, Vector3 jarg2, long jarg3);
public final static native long new_btTriangleRaycastCallback__SWIG_1(Vector3 jarg1, Vector3 jarg2);
public final static native void btTriangleRaycastCallback_processTriangle(long jarg1, btTriangleRaycastCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native void btTriangleRaycastCallback_processTriangleSwigExplicitbtTriangleRaycastCallback(long jarg1, btTriangleRaycastCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native float btTriangleRaycastCallback_reportHit(long jarg1, btTriangleRaycastCallback jarg1_, Vector3 jarg2, float jarg3, int jarg4, int jarg5);
public final static native void delete_btTriangleRaycastCallback(long jarg1);
public final static native void btTriangleRaycastCallback_director_connect(btTriangleRaycastCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btTriangleRaycastCallback_change_ownership(btTriangleRaycastCallback obj, long cptr, boolean take_or_release);
public final static native void btTriangleConvexcastCallback_convexShape_set(long jarg1, btTriangleConvexcastCallback jarg1_, long jarg2, btConvexShape jarg2_);
public final static native long btTriangleConvexcastCallback_convexShape_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native void btTriangleConvexcastCallback_convexShapeFrom_set(long jarg1, btTriangleConvexcastCallback jarg1_, long jarg2, btTransform jarg2_);
public final static native long btTriangleConvexcastCallback_convexShapeFrom_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native void btTriangleConvexcastCallback_convexShapeTo_set(long jarg1, btTriangleConvexcastCallback jarg1_, long jarg2, btTransform jarg2_);
public final static native long btTriangleConvexcastCallback_convexShapeTo_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native void btTriangleConvexcastCallback_triangleToWorld_set(long jarg1, btTriangleConvexcastCallback jarg1_, long jarg2, btTransform jarg2_);
public final static native long btTriangleConvexcastCallback_triangleToWorld_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native void btTriangleConvexcastCallback_hitFraction_set(long jarg1, btTriangleConvexcastCallback jarg1_, float jarg2);
public final static native float btTriangleConvexcastCallback_hitFraction_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native void btTriangleConvexcastCallback_triangleCollisionMargin_set(long jarg1, btTriangleConvexcastCallback jarg1_, float jarg2);
public final static native float btTriangleConvexcastCallback_triangleCollisionMargin_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native void btTriangleConvexcastCallback_allowedPenetration_set(long jarg1, btTriangleConvexcastCallback jarg1_, float jarg2);
public final static native float btTriangleConvexcastCallback_allowedPenetration_get(long jarg1, btTriangleConvexcastCallback jarg1_);
public final static native long new_btTriangleConvexcastCallback(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, Matrix4 jarg3, Matrix4 jarg4, float jarg5);
public final static native void btTriangleConvexcastCallback_processTriangle(long jarg1, btTriangleConvexcastCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native void btTriangleConvexcastCallback_processTriangleSwigExplicitbtTriangleConvexcastCallback(long jarg1, btTriangleConvexcastCallback jarg1_, long jarg2, btVector3 jarg2_, int jarg3, int jarg4);
public final static native float btTriangleConvexcastCallback_reportHit(long jarg1, btTriangleConvexcastCallback jarg1_, Vector3 jarg2, Vector3 jarg3, float jarg4, int jarg5, int jarg6);
public final static native void delete_btTriangleConvexcastCallback(long jarg1);
public final static native void btTriangleConvexcastCallback_director_connect(btTriangleConvexcastCallback obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void btTriangleConvexcastCallback_change_ownership(btTriangleConvexcastCallback obj, long cptr, boolean take_or_release);
public final static native void btGjkEpaSolver2_sResults_status_set(long jarg1, btGjkEpaSolver2.sResults jarg1_, int jarg2);
public final static native int btGjkEpaSolver2_sResults_status_get(long jarg1, btGjkEpaSolver2.sResults jarg1_);
public final static native void btGjkEpaSolver2_sResults_witnesses_set(long jarg1, btGjkEpaSolver2.sResults jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btGjkEpaSolver2_sResults_witnesses_get(long jarg1, btGjkEpaSolver2.sResults jarg1_);
public final static native void btGjkEpaSolver2_sResults_normal_set(long jarg1, btGjkEpaSolver2.sResults jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btGjkEpaSolver2_sResults_normal_get(long jarg1, btGjkEpaSolver2.sResults jarg1_);
public final static native void btGjkEpaSolver2_sResults_distance_set(long jarg1, btGjkEpaSolver2.sResults jarg1_, float jarg2);
public final static native float btGjkEpaSolver2_sResults_distance_get(long jarg1, btGjkEpaSolver2.sResults jarg1_);
public final static native long new_btGjkEpaSolver2_sResults();
public final static native void delete_btGjkEpaSolver2_sResults(long jarg1);
public final static native int btGjkEpaSolver2_StackSizeRequirement();
public final static native boolean btGjkEpaSolver2_Distance(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, long jarg3, btConvexShape jarg3_, Matrix4 jarg4, Vector3 jarg5, long jarg6, btGjkEpaSolver2.sResults jarg6_);
public final static native boolean btGjkEpaSolver2_Penetration__SWIG_0(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, long jarg3, btConvexShape jarg3_, Matrix4 jarg4, Vector3 jarg5, long jarg6, btGjkEpaSolver2.sResults jarg6_, boolean jarg7);
public final static native boolean btGjkEpaSolver2_Penetration__SWIG_1(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, long jarg3, btConvexShape jarg3_, Matrix4 jarg4, Vector3 jarg5, long jarg6, btGjkEpaSolver2.sResults jarg6_);
public final static native float btGjkEpaSolver2_SignedDistance__SWIG_0(Vector3 jarg1, float jarg2, long jarg3, btConvexShape jarg3_, Matrix4 jarg4, long jarg5, btGjkEpaSolver2.sResults jarg5_);
public final static native boolean btGjkEpaSolver2_SignedDistance__SWIG_1(long jarg1, btConvexShape jarg1_, Matrix4 jarg2, long jarg3, btConvexShape jarg3_, Matrix4 jarg4, Vector3 jarg5, long jarg6, btGjkEpaSolver2.sResults jarg6_);
public final static native long new_btGjkEpaSolver2();
public final static native void delete_btGjkEpaSolver2(long jarg1);
public final static native long new_btGjkEpaPenetrationDepthSolver();
public final static native void delete_btGjkEpaPenetrationDepthSolver(long jarg1);
public final static native void btPointCollector_normalOnBInWorld_set(long jarg1, btPointCollector jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btPointCollector_normalOnBInWorld_get(long jarg1, btPointCollector jarg1_);
public final static native void btPointCollector_pointInWorld_set(long jarg1, btPointCollector jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btPointCollector_pointInWorld_get(long jarg1, btPointCollector jarg1_);
public final static native void btPointCollector_distance_set(long jarg1, btPointCollector jarg1_, float jarg2);
public final static native float btPointCollector_distance_get(long jarg1, btPointCollector jarg1_);
public final static native void btPointCollector_hasResult_set(long jarg1, btPointCollector jarg1_, boolean jarg2);
public final static native boolean btPointCollector_hasResult_get(long jarg1, btPointCollector jarg1_);
public final static native long new_btPointCollector();
public final static native void delete_btPointCollector(long jarg1);
public final static native long new_btUsageBitfield();
public final static native void btUsageBitfield_reset(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_usedVertexA_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_usedVertexA_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_usedVertexB_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_usedVertexB_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_usedVertexC_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_usedVertexC_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_usedVertexD_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_usedVertexD_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_unused1_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_unused1_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_unused2_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_unused2_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_unused3_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_unused3_get(long jarg1, btUsageBitfield jarg1_);
public final static native void btUsageBitfield_unused4_set(long jarg1, btUsageBitfield jarg1_, int jarg2);
public final static native int btUsageBitfield_unused4_get(long jarg1, btUsageBitfield jarg1_);
public final static native void delete_btUsageBitfield(long jarg1);
public final static native void btSubSimplexClosestResult_closestPointOnSimplex_set(long jarg1, btSubSimplexClosestResult jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btSubSimplexClosestResult_closestPointOnSimplex_get(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native void btSubSimplexClosestResult_usedVertices_set(long jarg1, btSubSimplexClosestResult jarg1_, long jarg2, btUsageBitfield jarg2_);
public final static native long btSubSimplexClosestResult_usedVertices_get(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native void btSubSimplexClosestResult_barycentricCoords_set(long jarg1, btSubSimplexClosestResult jarg1_, float[] jarg2);
public final static native float[] btSubSimplexClosestResult_barycentricCoords_get(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native void btSubSimplexClosestResult_degenerate_set(long jarg1, btSubSimplexClosestResult jarg1_, boolean jarg2);
public final static native boolean btSubSimplexClosestResult_degenerate_get(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native void btSubSimplexClosestResult_reset(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native boolean btSubSimplexClosestResult_isValid(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native void btSubSimplexClosestResult_setBarycentricCoordinates__SWIG_0(long jarg1, btSubSimplexClosestResult jarg1_, float jarg2, float jarg3, float jarg4, float jarg5);
public final static native void btSubSimplexClosestResult_setBarycentricCoordinates__SWIG_1(long jarg1, btSubSimplexClosestResult jarg1_, float jarg2, float jarg3, float jarg4);
public final static native void btSubSimplexClosestResult_setBarycentricCoordinates__SWIG_2(long jarg1, btSubSimplexClosestResult jarg1_, float jarg2, float jarg3);
public final static native void btSubSimplexClosestResult_setBarycentricCoordinates__SWIG_3(long jarg1, btSubSimplexClosestResult jarg1_, float jarg2);
public final static native void btSubSimplexClosestResult_setBarycentricCoordinates__SWIG_4(long jarg1, btSubSimplexClosestResult jarg1_);
public final static native long new_btSubSimplexClosestResult();
public final static native void delete_btSubSimplexClosestResult(long jarg1);
public final static native void btVoronoiSimplexSolver_numVertices_set(long jarg1, btVoronoiSimplexSolver jarg1_, int jarg2);
public final static native int btVoronoiSimplexSolver_numVertices_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_simplexVectorW_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_simplexVectorW_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_simplexPointsP_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_simplexPointsP_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_simplexPointsQ_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_simplexPointsQ_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_cachedP1_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_cachedP1_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_cachedP2_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_cachedP2_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_cachedV_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_cachedV_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_lastW_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btVoronoiSimplexSolver_lastW_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_equalVertexThreshold_set(long jarg1, btVoronoiSimplexSolver jarg1_, float jarg2);
public final static native float btVoronoiSimplexSolver_equalVertexThreshold_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_cachedValidClosest_set(long jarg1, btVoronoiSimplexSolver jarg1_, boolean jarg2);
public final static native boolean btVoronoiSimplexSolver_cachedValidClosest_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_cachedBC_set(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btSubSimplexClosestResult jarg2_);
public final static native long btVoronoiSimplexSolver_cachedBC_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_needsUpdate_set(long jarg1, btVoronoiSimplexSolver jarg1_, boolean jarg2);
public final static native boolean btVoronoiSimplexSolver_needsUpdate_get(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_removeVertex(long jarg1, btVoronoiSimplexSolver jarg1_, int jarg2);
public final static native void btVoronoiSimplexSolver_reduceVertices(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btUsageBitfield jarg2_);
public final static native boolean btVoronoiSimplexSolver_updateClosestVectorAndPoints(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native boolean btVoronoiSimplexSolver_closestPtPointTetrahedron(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, Vector3 jarg6, long jarg7, btSubSimplexClosestResult jarg7_);
public final static native int btVoronoiSimplexSolver_pointOutsideOfPlane(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, Vector3 jarg6);
public final static native boolean btVoronoiSimplexSolver_closestPtPointTriangle(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, long jarg6, btSubSimplexClosestResult jarg6_);
public final static native long new_btVoronoiSimplexSolver();
public final static native void btVoronoiSimplexSolver_reset(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_addVertex(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native boolean btVoronoiSimplexSolver_closest(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2);
public final static native float btVoronoiSimplexSolver_maxVertex(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native boolean btVoronoiSimplexSolver_fullSimplex(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native int btVoronoiSimplexSolver_getSimplex(long jarg1, btVoronoiSimplexSolver jarg1_, long jarg2, btVector3 jarg2_, long jarg3, btVector3 jarg3_, long jarg4, btVector3 jarg4_);
public final static native boolean btVoronoiSimplexSolver_inSimplex(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2);
public final static native void btVoronoiSimplexSolver_backup_closest(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2);
public final static native boolean btVoronoiSimplexSolver_emptySimplex(long jarg1, btVoronoiSimplexSolver jarg1_);
public final static native void btVoronoiSimplexSolver_compute_points(long jarg1, btVoronoiSimplexSolver jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void delete_btVoronoiSimplexSolver(long jarg1);
public final static native long new_btMultiSphereShape(Vector3[] jarg1, float[] jarg2, int jarg3);
public final static native int btMultiSphereShape_getSphereCount(long jarg1, btMultiSphereShape jarg1_);
public final static native Vector3 btMultiSphereShape_getSpherePosition(long jarg1, btMultiSphereShape jarg1_, int jarg2);
public final static native float btMultiSphereShape_getSphereRadius(long jarg1, btMultiSphereShape jarg1_, int jarg2);
public final static native void delete_btMultiSphereShape(long jarg1);
public final static native void btPositionAndRadius_pos_set(long jarg1, btPositionAndRadius jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btPositionAndRadius_pos_get(long jarg1, btPositionAndRadius jarg1_);
public final static native void btPositionAndRadius_radius_set(long jarg1, btPositionAndRadius jarg1_, float jarg2);
public final static native float btPositionAndRadius_radius_get(long jarg1, btPositionAndRadius jarg1_);
public final static native long new_btPositionAndRadius();
public final static native void delete_btPositionAndRadius(long jarg1);
public final static native void btMultiSphereShapeData_convexInternalShapeData_set(long jarg1, btMultiSphereShapeData jarg1_, long jarg2, btConvexInternalShapeData jarg2_);
public final static native long btMultiSphereShapeData_convexInternalShapeData_get(long jarg1, btMultiSphereShapeData jarg1_);
public final static native void btMultiSphereShapeData_localPositionArrayPtr_set(long jarg1, btMultiSphereShapeData jarg1_, long jarg2, btPositionAndRadius jarg2_);
public final static native long btMultiSphereShapeData_localPositionArrayPtr_get(long jarg1, btMultiSphereShapeData jarg1_);
public final static native void btMultiSphereShapeData_localPositionArraySize_set(long jarg1, btMultiSphereShapeData jarg1_, int jarg2);
public final static native int btMultiSphereShapeData_localPositionArraySize_get(long jarg1, btMultiSphereShapeData jarg1_);
public final static native void btMultiSphereShapeData_padding_set(long jarg1, btMultiSphereShapeData jarg1_, String jarg2);
public final static native String btMultiSphereShapeData_padding_get(long jarg1, btMultiSphereShapeData jarg1_);
public final static native long new_btMultiSphereShapeData();
public final static native void delete_btMultiSphereShapeData(long jarg1);
public final static native long new_CustomCollisionDispatcher(long jarg1, btCollisionConfiguration jarg1_);
public final static native boolean CustomCollisionDispatcher_needsCollision(long jarg1, CustomCollisionDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native boolean CustomCollisionDispatcher_needsCollisionSwigExplicitCustomCollisionDispatcher(long jarg1, CustomCollisionDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native boolean CustomCollisionDispatcher_needsResponse(long jarg1, CustomCollisionDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native boolean CustomCollisionDispatcher_needsResponseSwigExplicitCustomCollisionDispatcher(long jarg1, CustomCollisionDispatcher jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void delete_CustomCollisionDispatcher(long jarg1);
public final static native void CustomCollisionDispatcher_director_connect(CustomCollisionDispatcher obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void CustomCollisionDispatcher_change_ownership(CustomCollisionDispatcher obj, long cptr, boolean take_or_release);
public final static native long new_ContactListener(boolean jarg1);
public final static native void delete_ContactListener(long jarg1);
public final static native void ContactListener_enable(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_disable(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_enableOnAdded(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_disableOnAdded(long jarg1, ContactListener jarg1_);
public final static native boolean ContactListener_isOnAddedEnabled(long jarg1, ContactListener jarg1_);
public final static native boolean ContactListener_onContactAdded__SWIG_0(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, int jarg4, int jarg5, long jarg6, btCollisionObjectWrapper jarg6_, int jarg7, int jarg8);
public final static native boolean ContactListener_onContactAdded__SWIG_1(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObject jarg3_, int jarg4, int jarg5, long jarg6, btCollisionObject jarg6_, int jarg7, int jarg8);
public final static native boolean ContactListener_onContactAdded__SWIG_2(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, int jarg3, int jarg4, int jarg5, int jarg6, int jarg7, int jarg8);
public final static native boolean ContactListener_onContactAdded__SWIG_3(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, int jarg4, int jarg5, boolean jarg6, long jarg7, btCollisionObjectWrapper jarg7_, int jarg8, int jarg9, boolean jarg10);
public final static native boolean ContactListener_onContactAdded__SWIG_4(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObject jarg3_, int jarg4, int jarg5, boolean jarg6, long jarg7, btCollisionObject jarg7_, int jarg8, int jarg9, boolean jarg10);
public final static native boolean ContactListener_onContactAdded__SWIG_5(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, int jarg3, int jarg4, int jarg5, boolean jarg6, int jarg7, int jarg8, int jarg9, boolean jarg10);
public final static native boolean ContactListener_onContactAdded__SWIG_6(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, int jarg3, int jarg4, long jarg5, btCollisionObjectWrapper jarg5_, int jarg6, int jarg7);
public final static native boolean ContactListener_onContactAdded__SWIG_7(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, int jarg3, int jarg4, long jarg5, btCollisionObject jarg5_, int jarg6, int jarg7);
public final static native boolean ContactListener_onContactAdded__SWIG_8(long jarg1, ContactListener jarg1_, int jarg2, int jarg3, int jarg4, int jarg5, int jarg6, int jarg7);
public final static native boolean ContactListener_onContactAdded__SWIG_9(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, int jarg3, int jarg4, boolean jarg5, long jarg6, btCollisionObjectWrapper jarg6_, int jarg7, int jarg8, boolean jarg9);
public final static native boolean ContactListener_onContactAdded__SWIG_10(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, int jarg3, int jarg4, boolean jarg5, long jarg6, btCollisionObject jarg6_, int jarg7, int jarg8, boolean jarg9);
public final static native boolean ContactListener_onContactAdded__SWIG_11(long jarg1, ContactListener jarg1_, int jarg2, int jarg3, int jarg4, boolean jarg5, int jarg6, int jarg7, int jarg8, boolean jarg9);
public final static native void ContactListener_enableOnProcessed(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_disableOnProcessed(long jarg1, ContactListener jarg1_);
public final static native boolean ContactListener_isOnProcessedEnabled(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_onContactProcessed__SWIG_0(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObject jarg3_, long jarg4, btCollisionObject jarg4_);
public final static native void ContactListener_onContactProcessed__SWIG_1(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, int jarg3, int jarg4);
public final static native void ContactListener_onContactProcessed__SWIG_2(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, long jarg3, btCollisionObject jarg3_, boolean jarg4, long jarg5, btCollisionObject jarg5_, boolean jarg6);
public final static native void ContactListener_onContactProcessed__SWIG_3(long jarg1, ContactListener jarg1_, long jarg2, btManifoldPoint jarg2_, int jarg3, boolean jarg4, int jarg5, boolean jarg6);
public final static native void ContactListener_onContactProcessed__SWIG_4(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void ContactListener_onContactProcessed__SWIG_5(long jarg1, ContactListener jarg1_, int jarg2, int jarg3);
public final static native void ContactListener_onContactProcessed__SWIG_6(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, boolean jarg3, long jarg4, btCollisionObject jarg4_, boolean jarg5);
public final static native void ContactListener_onContactProcessed__SWIG_7(long jarg1, ContactListener jarg1_, int jarg2, boolean jarg3, int jarg4, boolean jarg5);
public final static native void ContactListener_enableOnDestroyed(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_disableOnDestroyed(long jarg1, ContactListener jarg1_);
public final static native boolean ContactListener_isOnDestroyedEnabled(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_onContactDestroyed(long jarg1, ContactListener jarg1_, int jarg2);
public final static native void ContactListener_enableOnStarted(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_disableOnStarted(long jarg1, ContactListener jarg1_);
public final static native boolean ContactListener_isOnStartedEnabled(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_onContactStarted__SWIG_0(long jarg1, ContactListener jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native void ContactListener_onContactStarted__SWIG_1(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void ContactListener_onContactStarted__SWIG_2(long jarg1, ContactListener jarg1_, int jarg2, int jarg3);
public final static native void ContactListener_onContactStarted__SWIG_3(long jarg1, ContactListener jarg1_, long jarg2, btPersistentManifold jarg2_, boolean jarg3, boolean jarg4);
public final static native void ContactListener_onContactStarted__SWIG_4(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, boolean jarg3, long jarg4, btCollisionObject jarg4_, boolean jarg5);
public final static native void ContactListener_onContactStarted__SWIG_5(long jarg1, ContactListener jarg1_, int jarg2, boolean jarg3, int jarg4, boolean jarg5);
public final static native void ContactListener_enableOnEnded(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_disableOnEnded(long jarg1, ContactListener jarg1_);
public final static native boolean ContactListener_isOnEndedEnabled(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_onContactEnded__SWIG_0(long jarg1, ContactListener jarg1_, long jarg2, btPersistentManifold jarg2_);
public final static native void ContactListener_onContactEnded__SWIG_1(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, long jarg3, btCollisionObject jarg3_);
public final static native void ContactListener_onContactEnded__SWIG_2(long jarg1, ContactListener jarg1_, int jarg2, int jarg3);
public final static native void ContactListener_onContactEnded__SWIG_3(long jarg1, ContactListener jarg1_, long jarg2, btPersistentManifold jarg2_, boolean jarg3, boolean jarg4);
public final static native void ContactListener_onContactEnded__SWIG_4(long jarg1, ContactListener jarg1_, long jarg2, btCollisionObject jarg2_, boolean jarg3, long jarg4, btCollisionObject jarg4_, boolean jarg5);
public final static native void ContactListener_onContactEnded__SWIG_5(long jarg1, ContactListener jarg1_, int jarg2, boolean jarg3, int jarg4, boolean jarg5);
public final static native boolean ContactListener_setEvents(long jarg1, ContactListener jarg1_);
public final static native void ContactListener_director_connect(ContactListener obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void ContactListener_change_ownership(ContactListener obj, long cptr, boolean take_or_release);
public final static native void ContactCache_cacheTime_set(long jarg1, ContactCache jarg1_, float jarg2);
public final static native float ContactCache_cacheTime_get(long jarg1, ContactCache jarg1_);
public final static native long new_ContactCache(boolean jarg1);
public final static native void delete_ContactCache(long jarg1);
public final static native void ContactCache_enable(long jarg1, ContactCache jarg1_);
public final static native void ContactCache_disable(long jarg1, ContactCache jarg1_);
public final static native boolean ContactCache_isEnabled(long jarg1, ContactCache jarg1_);
public final static native void ContactCache_onContactStarted(long jarg1, ContactCache jarg1_, long jarg2, btPersistentManifold jarg2_, boolean jarg3, boolean jarg4);
public final static native void ContactCache_onContactEnded(long jarg1, ContactCache jarg1_, long jarg2, btCollisionObject jarg2_, boolean jarg3, long jarg4, btCollisionObject jarg4_, boolean jarg5);
public final static native void ContactCache_clear(long jarg1, ContactCache jarg1_);
public final static native void ContactCache_update(long jarg1, ContactCache jarg1_, float jarg2);
public final static native void ContactCache_director_connect(ContactCache obj, long cptr, boolean mem_own, boolean weak_global);
public final static native void ContactCache_change_ownership(ContactCache obj, long cptr, boolean take_or_release);
public final static native int btBroadphasePairArray_size(long jarg1, btBroadphasePairArray jarg1_);
public final static native btBroadphasePair btBroadphasePairArray_at(long jarg1, btBroadphasePairArray jarg1_, int jarg2);
public final static native int btBroadphasePairArray_getCollisionObjects(long jarg1, btBroadphasePairArray jarg1_, int[] jarg2, int jarg3, int jarg4);
public final static native int btBroadphasePairArray_getCollisionObjectsValue(long jarg1, btBroadphasePairArray jarg1_, int[] jarg2, int jarg3, int jarg4);
public final static native long new_btBroadphasePairArray();
public final static native void delete_btBroadphasePairArray(long jarg1);
public final static native void bt_calc_quantization_parameters(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, float jarg6);
public final static native void bt_quantize_clamp(java.nio.IntBuffer jarg1, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5);
public final static native Vector3 bt_unquantize(java.nio.IntBuffer jarg1, Vector3 jarg2, Vector3 jarg3);
public final static native float bt_mat3_dot_col(Matrix3 jarg1, Vector3 jarg2, int jarg3);
public final static native void BT_BOX_BOX_TRANSFORM_CACHE_T1to0_set(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_, long jarg2, btVector3 jarg2_);
public final static native long BT_BOX_BOX_TRANSFORM_CACHE_T1to0_get(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_);
public final static native void BT_BOX_BOX_TRANSFORM_CACHE_R1to0_set(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_, Matrix3 jarg2);
public final static native Matrix3 BT_BOX_BOX_TRANSFORM_CACHE_R1to0_get(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_);
public final static native void BT_BOX_BOX_TRANSFORM_CACHE_AR_set(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_, Matrix3 jarg2);
public final static native Matrix3 BT_BOX_BOX_TRANSFORM_CACHE_AR_get(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_);
public final static native void BT_BOX_BOX_TRANSFORM_CACHE_calc_absolute_matrix(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_);
public final static native long new_BT_BOX_BOX_TRANSFORM_CACHE();
public final static native void BT_BOX_BOX_TRANSFORM_CACHE_calc_from_homogenic(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_, Matrix4 jarg2, Matrix4 jarg3);
public final static native void BT_BOX_BOX_TRANSFORM_CACHE_calc_from_full_invert(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_, Matrix4 jarg2, Matrix4 jarg3);
public final static native Vector3 BT_BOX_BOX_TRANSFORM_CACHE_transform(long jarg1, BT_BOX_BOX_TRANSFORM_CACHE jarg1_, Vector3 jarg2);
public final static native void delete_BT_BOX_BOX_TRANSFORM_CACHE(long jarg1);
public final static native void btAABB_min_set(long jarg1, btAABB jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btAABB_min_get(long jarg1, btAABB jarg1_);
public final static native void btAABB_max_set(long jarg1, btAABB jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btAABB_max_get(long jarg1, btAABB jarg1_);
public final static native long new_btAABB__SWIG_0();
public final static native long new_btAABB__SWIG_1(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3);
public final static native long new_btAABB__SWIG_2(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, float jarg4);
public final static native long new_btAABB__SWIG_3(long jarg1, btAABB jarg1_);
public final static native long new_btAABB__SWIG_4(long jarg1, btAABB jarg1_, float jarg2);
public final static native void btAABB_invalidate(long jarg1, btAABB jarg1_);
public final static native void btAABB_increment_margin(long jarg1, btAABB jarg1_, float jarg2);
public final static native void btAABB_copy_with_margin(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_, float jarg3);
public final static native void btAABB_appy_transform(long jarg1, btAABB jarg1_, Matrix4 jarg2);
public final static native void btAABB_appy_transform_trans_cache(long jarg1, btAABB jarg1_, long jarg2, BT_BOX_BOX_TRANSFORM_CACHE jarg2_);
public final static native void btAABB_merge(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_);
public final static native void btAABB_get_center_extend(long jarg1, btAABB jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btAABB_find_intersection(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_, long jarg3, btAABB jarg3_);
public final static native boolean btAABB_has_collision(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_);
public final static native boolean btAABB_collide_ray(long jarg1, btAABB jarg1_, Vector3 jarg2, Vector3 jarg3);
public final static native void btAABB_projection_interval(long jarg1, btAABB jarg1_, Vector3 jarg2, long jarg3, long jarg4);
public final static native int btAABB_plane_classify(long jarg1, btAABB jarg1_, long jarg2, btVector4 jarg2_);
public final static native boolean btAABB_overlapping_trans_conservative(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_, Matrix4 jarg3);
public final static native boolean btAABB_overlapping_trans_conservative2(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_, long jarg3, BT_BOX_BOX_TRANSFORM_CACHE jarg3_);
public final static native boolean btAABB_overlapping_trans_cache(long jarg1, btAABB jarg1_, long jarg2, btAABB jarg2_, long jarg3, BT_BOX_BOX_TRANSFORM_CACHE jarg3_, boolean jarg4);
public final static native boolean btAABB_collide_plane(long jarg1, btAABB jarg1_, long jarg2, btVector4 jarg2_);
public final static native boolean btAABB_collide_triangle_exact(long jarg1, btAABB jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, long jarg5, btVector4 jarg5_);
public final static native void delete_btAABB(long jarg1);
public final static native boolean btCompareTransformsEqual(Matrix4 jarg1, Matrix4 jarg2);
public final static native float bt_distance_point_plane(long jarg1, btVector4 jarg1_, Vector3 jarg2);
public final static native void bt_vec_blend(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, float jarg4);
public final static native void bt_plane_clip_polygon_collect(Vector3 jarg1, Vector3 jarg2, float jarg3, float jarg4, long jarg5, btVector3 jarg5_, long jarg6);
public final static native int bt_plane_clip_polygon(long jarg1, btVector4 jarg1_, long jarg2, btVector3 jarg2_, int jarg3, long jarg4, btVector3 jarg4_);
public final static native int bt_plane_clip_triangle(long jarg1, btVector4 jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, long jarg5, btVector3 jarg5_);
public final static native void bt_edge_plane(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, long jarg4, btVector4 jarg4_);
public final static native void bt_closest_point_on_segment(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4);
public final static native int bt_line_plane_collision(long jarg1, btVector4 jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, long jarg5, float jarg6, float jarg7);
public final static native void bt_segment_collision(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5, Vector3 jarg6);
public final static native void GIM_TRIANGLE_CONTACT_penetration_depth_set(long jarg1, GIM_TRIANGLE_CONTACT jarg1_, float jarg2);
public final static native float GIM_TRIANGLE_CONTACT_penetration_depth_get(long jarg1, GIM_TRIANGLE_CONTACT jarg1_);
public final static native void GIM_TRIANGLE_CONTACT_point_count_set(long jarg1, GIM_TRIANGLE_CONTACT jarg1_, int jarg2);
public final static native int GIM_TRIANGLE_CONTACT_point_count_get(long jarg1, GIM_TRIANGLE_CONTACT jarg1_);
public final static native void GIM_TRIANGLE_CONTACT_separating_normal_set(long jarg1, GIM_TRIANGLE_CONTACT jarg1_, long jarg2, btVector4 jarg2_);
public final static native long GIM_TRIANGLE_CONTACT_separating_normal_get(long jarg1, GIM_TRIANGLE_CONTACT jarg1_);
public final static native void GIM_TRIANGLE_CONTACT_points_set(long jarg1, GIM_TRIANGLE_CONTACT jarg1_, long jarg2, btVector3 jarg2_);
public final static native long GIM_TRIANGLE_CONTACT_points_get(long jarg1, GIM_TRIANGLE_CONTACT jarg1_);
public final static native void GIM_TRIANGLE_CONTACT_copy_from(long jarg1, GIM_TRIANGLE_CONTACT jarg1_, long jarg2, GIM_TRIANGLE_CONTACT jarg2_);
public final static native long new_GIM_TRIANGLE_CONTACT__SWIG_0();
public final static native long new_GIM_TRIANGLE_CONTACT__SWIG_1(long jarg1, GIM_TRIANGLE_CONTACT jarg1_);
public final static native void GIM_TRIANGLE_CONTACT_merge_points(long jarg1, GIM_TRIANGLE_CONTACT jarg1_, long jarg2, btVector4 jarg2_, float jarg3, long jarg4, btVector3 jarg4_, int jarg5);
public final static native void delete_GIM_TRIANGLE_CONTACT(long jarg1);
public final static native void btPrimitiveTriangle_vertices_set(long jarg1, btPrimitiveTriangle jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btPrimitiveTriangle_vertices_get(long jarg1, btPrimitiveTriangle jarg1_);
public final static native void btPrimitiveTriangle_plane_set(long jarg1, btPrimitiveTriangle jarg1_, long jarg2, btVector4 jarg2_);
public final static native long btPrimitiveTriangle_plane_get(long jarg1, btPrimitiveTriangle jarg1_);
public final static native void btPrimitiveTriangle_margin_set(long jarg1, btPrimitiveTriangle jarg1_, float jarg2);
public final static native float btPrimitiveTriangle_margin_get(long jarg1, btPrimitiveTriangle jarg1_);
public final static native void btPrimitiveTriangle_dummy_set(long jarg1, btPrimitiveTriangle jarg1_, float jarg2);
public final static native float btPrimitiveTriangle_dummy_get(long jarg1, btPrimitiveTriangle jarg1_);
public final static native long new_btPrimitiveTriangle();
public final static native void btPrimitiveTriangle_buildTriPlane(long jarg1, btPrimitiveTriangle jarg1_);
public final static native boolean btPrimitiveTriangle_overlap_test_conservative(long jarg1, btPrimitiveTriangle jarg1_, long jarg2, btPrimitiveTriangle jarg2_);
public final static native void btPrimitiveTriangle_get_edge_plane(long jarg1, btPrimitiveTriangle jarg1_, int jarg2, long jarg3, btVector4 jarg3_);
public final static native void btPrimitiveTriangle_applyTransform(long jarg1, btPrimitiveTriangle jarg1_, Matrix4 jarg2);
public final static native int btPrimitiveTriangle_clip_triangle(long jarg1, btPrimitiveTriangle jarg1_, long jarg2, btPrimitiveTriangle jarg2_, long jarg3, btVector3 jarg3_);
public final static native boolean btPrimitiveTriangle_find_triangle_collision_clip_method(long jarg1, btPrimitiveTriangle jarg1_, long jarg2, btPrimitiveTriangle jarg2_, long jarg3, GIM_TRIANGLE_CONTACT jarg3_);
public final static native void delete_btPrimitiveTriangle(long jarg1);
public final static native long new_btTriangleShapeEx__SWIG_0();
public final static native long new_btTriangleShapeEx__SWIG_1(Vector3 jarg1, Vector3 jarg2, Vector3 jarg3);
public final static native long new_btTriangleShapeEx__SWIG_2(long jarg1, btTriangleShapeEx jarg1_);
public final static native void btTriangleShapeEx_applyTransform(long jarg1, btTriangleShapeEx jarg1_, Matrix4 jarg2);
public final static native void btTriangleShapeEx_buildTriPlane(long jarg1, btTriangleShapeEx jarg1_, long jarg2, btVector4 jarg2_);
public final static native boolean btTriangleShapeEx_overlap_test_conservative(long jarg1, btTriangleShapeEx jarg1_, long jarg2, btTriangleShapeEx jarg2_);
public final static native void delete_btTriangleShapeEx(long jarg1);
public final static native void GIM_PAIR_index1_set(long jarg1, GIM_PAIR jarg1_, int jarg2);
public final static native int GIM_PAIR_index1_get(long jarg1, GIM_PAIR jarg1_);
public final static native void GIM_PAIR_index2_set(long jarg1, GIM_PAIR jarg1_, int jarg2);
public final static native int GIM_PAIR_index2_get(long jarg1, GIM_PAIR jarg1_);
public final static native long new_GIM_PAIR__SWIG_0();
public final static native long new_GIM_PAIR__SWIG_1(long jarg1, GIM_PAIR jarg1_);
public final static native long new_GIM_PAIR__SWIG_2(int jarg1, int jarg2);
public final static native void delete_GIM_PAIR(long jarg1);
public final static native long new_btPairSet();
public final static native void btPairSet_push_pair(long jarg1, btPairSet jarg1_, int jarg2, int jarg3);
public final static native void btPairSet_push_pair_inv(long jarg1, btPairSet jarg1_, int jarg2, int jarg3);
public final static native void delete_btPairSet(long jarg1);
public final static native void GIM_BVH_DATA_bound_set(long jarg1, GIM_BVH_DATA jarg1_, long jarg2, btAABB jarg2_);
public final static native long GIM_BVH_DATA_bound_get(long jarg1, GIM_BVH_DATA jarg1_);
public final static native void GIM_BVH_DATA_data_set(long jarg1, GIM_BVH_DATA jarg1_, int jarg2);
public final static native int GIM_BVH_DATA_data_get(long jarg1, GIM_BVH_DATA jarg1_);
public final static native long new_GIM_BVH_DATA();
public final static native void delete_GIM_BVH_DATA(long jarg1);
public final static native void GIM_BVH_TREE_NODE_bound_set(long jarg1, GIM_BVH_TREE_NODE jarg1_, long jarg2, btAABB jarg2_);
public final static native long GIM_BVH_TREE_NODE_bound_get(long jarg1, GIM_BVH_TREE_NODE jarg1_);
public final static native long new_GIM_BVH_TREE_NODE();
public final static native boolean GIM_BVH_TREE_NODE_isLeafNode(long jarg1, GIM_BVH_TREE_NODE jarg1_);
public final static native int GIM_BVH_TREE_NODE_getEscapeIndex(long jarg1, GIM_BVH_TREE_NODE jarg1_);
public final static native void GIM_BVH_TREE_NODE_setEscapeIndex(long jarg1, GIM_BVH_TREE_NODE jarg1_, int jarg2);
public final static native int GIM_BVH_TREE_NODE_getDataIndex(long jarg1, GIM_BVH_TREE_NODE jarg1_);
public final static native void GIM_BVH_TREE_NODE_setDataIndex(long jarg1, GIM_BVH_TREE_NODE jarg1_, int jarg2);
public final static native void delete_GIM_BVH_TREE_NODE(long jarg1);
public final static native long new_GIM_BVH_DATA_ARRAY();
public final static native void delete_GIM_BVH_DATA_ARRAY(long jarg1);
public final static native long new_GIM_BVH_TREE_NODE_ARRAY();
public final static native void delete_GIM_BVH_TREE_NODE_ARRAY(long jarg1);
public final static native long new_btBvhTree();
public final static native void btBvhTree_build_tree(long jarg1, btBvhTree jarg1_, long jarg2, GIM_BVH_DATA_ARRAY jarg2_);
public final static native void btBvhTree_clearNodes(long jarg1, btBvhTree jarg1_);
public final static native int btBvhTree_getNodeCount(long jarg1, btBvhTree jarg1_);
public final static native boolean btBvhTree_isLeafNode(long jarg1, btBvhTree jarg1_, int jarg2);
public final static native int btBvhTree_getNodeData(long jarg1, btBvhTree jarg1_, int jarg2);
public final static native void btBvhTree_getNodeBound(long jarg1, btBvhTree jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native void btBvhTree_setNodeBound(long jarg1, btBvhTree jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native int btBvhTree_getLeftNode(long jarg1, btBvhTree jarg1_, int jarg2);
public final static native int btBvhTree_getRightNode(long jarg1, btBvhTree jarg1_, int jarg2);
public final static native int btBvhTree_getEscapeNodeIndex(long jarg1, btBvhTree jarg1_, int jarg2);
public final static native long btBvhTree_get_node_pointer__SWIG_0(long jarg1, btBvhTree jarg1_, int jarg2);
public final static native long btBvhTree_get_node_pointer__SWIG_1(long jarg1, btBvhTree jarg1_);
public final static native void delete_btBvhTree(long jarg1);
public final static native void delete_btPrimitiveManagerBase(long jarg1);
public final static native boolean btPrimitiveManagerBase_is_trimesh(long jarg1, btPrimitiveManagerBase jarg1_);
public final static native int btPrimitiveManagerBase_get_primitive_count(long jarg1, btPrimitiveManagerBase jarg1_);
public final static native void btPrimitiveManagerBase_get_primitive_box(long jarg1, btPrimitiveManagerBase jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native void btPrimitiveManagerBase_get_primitive_triangle(long jarg1, btPrimitiveManagerBase jarg1_, int jarg2, long jarg3, btPrimitiveTriangle jarg3_);
public final static native long new_btGImpactBvh__SWIG_0();
public final static native long new_btGImpactBvh__SWIG_1(long jarg1, btPrimitiveManagerBase jarg1_);
public final static native long btGImpactBvh_getGlobalBox(long jarg1, btGImpactBvh jarg1_);
public final static native void btGImpactBvh_setPrimitiveManager(long jarg1, btGImpactBvh jarg1_, long jarg2, btPrimitiveManagerBase jarg2_);
public final static native long btGImpactBvh_getPrimitiveManager(long jarg1, btGImpactBvh jarg1_);
public final static native void btGImpactBvh_update(long jarg1, btGImpactBvh jarg1_);
public final static native void btGImpactBvh_buildSet(long jarg1, btGImpactBvh jarg1_);
public final static native boolean btGImpactBvh_boxQuery(long jarg1, btGImpactBvh jarg1_, long jarg2, btAABB jarg2_, long jarg3);
public final static native boolean btGImpactBvh_boxQueryTrans(long jarg1, btGImpactBvh jarg1_, long jarg2, btAABB jarg2_, Matrix4 jarg3, long jarg4);
public final static native boolean btGImpactBvh_rayQuery(long jarg1, btGImpactBvh jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4);
public final static native boolean btGImpactBvh_hasHierarchy(long jarg1, btGImpactBvh jarg1_);
public final static native boolean btGImpactBvh_isTrimesh(long jarg1, btGImpactBvh jarg1_);
public final static native int btGImpactBvh_getNodeCount(long jarg1, btGImpactBvh jarg1_);
public final static native boolean btGImpactBvh_isLeafNode(long jarg1, btGImpactBvh jarg1_, int jarg2);
public final static native int btGImpactBvh_getNodeData(long jarg1, btGImpactBvh jarg1_, int jarg2);
public final static native void btGImpactBvh_getNodeBound(long jarg1, btGImpactBvh jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native void btGImpactBvh_setNodeBound(long jarg1, btGImpactBvh jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native int btGImpactBvh_getLeftNode(long jarg1, btGImpactBvh jarg1_, int jarg2);
public final static native int btGImpactBvh_getRightNode(long jarg1, btGImpactBvh jarg1_, int jarg2);
public final static native int btGImpactBvh_getEscapeNodeIndex(long jarg1, btGImpactBvh jarg1_, int jarg2);
public final static native void btGImpactBvh_getNodeTriangle(long jarg1, btGImpactBvh jarg1_, int jarg2, long jarg3, btPrimitiveTriangle jarg3_);
public final static native long btGImpactBvh_get_node_pointer__SWIG_0(long jarg1, btGImpactBvh jarg1_, int jarg2);
public final static native long btGImpactBvh_get_node_pointer__SWIG_1(long jarg1, btGImpactBvh jarg1_);
public final static native void btGImpactBvh_find_collision(long jarg1, btGImpactBvh jarg1_, Matrix4 jarg2, long jarg3, btGImpactBvh jarg3_, Matrix4 jarg4, long jarg5, btPairSet jarg5_);
public final static native void delete_btGImpactBvh(long jarg1);
public final static native void BT_QUANTIZED_BVH_NODE_quantizedAabbMin_set(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_, int[] jarg2);
public final static native int[] BT_QUANTIZED_BVH_NODE_quantizedAabbMin_get(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_);
public final static native void BT_QUANTIZED_BVH_NODE_quantizedAabbMax_set(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_, int[] jarg2);
public final static native int[] BT_QUANTIZED_BVH_NODE_quantizedAabbMax_get(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_);
public final static native void BT_QUANTIZED_BVH_NODE_escapeIndexOrDataIndex_set(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_, int jarg2);
public final static native int BT_QUANTIZED_BVH_NODE_escapeIndexOrDataIndex_get(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_);
public final static native long new_BT_QUANTIZED_BVH_NODE();
public final static native boolean BT_QUANTIZED_BVH_NODE_isLeafNode(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_);
public final static native int BT_QUANTIZED_BVH_NODE_getEscapeIndex(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_);
public final static native void BT_QUANTIZED_BVH_NODE_setEscapeIndex(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_, int jarg2);
public final static native int BT_QUANTIZED_BVH_NODE_getDataIndex(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_);
public final static native void BT_QUANTIZED_BVH_NODE_setDataIndex(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_, int jarg2);
public final static native boolean BT_QUANTIZED_BVH_NODE_testQuantizedBoxOverlapp(long jarg1, BT_QUANTIZED_BVH_NODE jarg1_, java.nio.IntBuffer jarg2, java.nio.IntBuffer jarg3);
public final static native void delete_BT_QUANTIZED_BVH_NODE(long jarg1);
public final static native long new_GIM_QUANTIZED_BVH_NODE_ARRAY();
public final static native void delete_GIM_QUANTIZED_BVH_NODE_ARRAY(long jarg1);
public final static native long new_btQuantizedBvhTree();
public final static native void btQuantizedBvhTree_build_tree(long jarg1, btQuantizedBvhTree jarg1_, long jarg2, GIM_BVH_DATA_ARRAY jarg2_);
public final static native void btQuantizedBvhTree_quantizePoint(long jarg1, btQuantizedBvhTree jarg1_, java.nio.IntBuffer jarg2, Vector3 jarg3);
public final static native boolean btQuantizedBvhTree_testQuantizedBoxOverlapp(long jarg1, btQuantizedBvhTree jarg1_, int jarg2, java.nio.IntBuffer jarg3, java.nio.IntBuffer jarg4);
public final static native void btQuantizedBvhTree_clearNodes(long jarg1, btQuantizedBvhTree jarg1_);
public final static native int btQuantizedBvhTree_getNodeCount(long jarg1, btQuantizedBvhTree jarg1_);
public final static native boolean btQuantizedBvhTree_isLeafNode(long jarg1, btQuantizedBvhTree jarg1_, int jarg2);
public final static native int btQuantizedBvhTree_getNodeData(long jarg1, btQuantizedBvhTree jarg1_, int jarg2);
public final static native void btQuantizedBvhTree_getNodeBound(long jarg1, btQuantizedBvhTree jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native void btQuantizedBvhTree_setNodeBound(long jarg1, btQuantizedBvhTree jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native int btQuantizedBvhTree_getLeftNode(long jarg1, btQuantizedBvhTree jarg1_, int jarg2);
public final static native int btQuantizedBvhTree_getRightNode(long jarg1, btQuantizedBvhTree jarg1_, int jarg2);
public final static native int btQuantizedBvhTree_getEscapeNodeIndex(long jarg1, btQuantizedBvhTree jarg1_, int jarg2);
public final static native long btQuantizedBvhTree_get_node_pointer__SWIG_0(long jarg1, btQuantizedBvhTree jarg1_, int jarg2);
public final static native long btQuantizedBvhTree_get_node_pointer__SWIG_1(long jarg1, btQuantizedBvhTree jarg1_);
public final static native void delete_btQuantizedBvhTree(long jarg1);
public final static native long new_btGImpactQuantizedBvh__SWIG_0();
public final static native long new_btGImpactQuantizedBvh__SWIG_1(long jarg1, btPrimitiveManagerBase jarg1_);
public final static native long btGImpactQuantizedBvh_getGlobalBox(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native void btGImpactQuantizedBvh_setPrimitiveManager(long jarg1, btGImpactQuantizedBvh jarg1_, long jarg2, btPrimitiveManagerBase jarg2_);
public final static native long btGImpactQuantizedBvh_getPrimitiveManager(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native void btGImpactQuantizedBvh_update(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native void btGImpactQuantizedBvh_buildSet(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native boolean btGImpactQuantizedBvh_boxQuery(long jarg1, btGImpactQuantizedBvh jarg1_, long jarg2, btAABB jarg2_, long jarg3);
public final static native boolean btGImpactQuantizedBvh_boxQueryTrans(long jarg1, btGImpactQuantizedBvh jarg1_, long jarg2, btAABB jarg2_, Matrix4 jarg3, long jarg4);
public final static native boolean btGImpactQuantizedBvh_rayQuery(long jarg1, btGImpactQuantizedBvh jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4);
public final static native boolean btGImpactQuantizedBvh_hasHierarchy(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native boolean btGImpactQuantizedBvh_isTrimesh(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native int btGImpactQuantizedBvh_getNodeCount(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native boolean btGImpactQuantizedBvh_isLeafNode(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2);
public final static native int btGImpactQuantizedBvh_getNodeData(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2);
public final static native void btGImpactQuantizedBvh_getNodeBound(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native void btGImpactQuantizedBvh_setNodeBound(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2, long jarg3, btAABB jarg3_);
public final static native int btGImpactQuantizedBvh_getLeftNode(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2);
public final static native int btGImpactQuantizedBvh_getRightNode(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2);
public final static native int btGImpactQuantizedBvh_getEscapeNodeIndex(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2);
public final static native void btGImpactQuantizedBvh_getNodeTriangle(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2, long jarg3, btPrimitiveTriangle jarg3_);
public final static native long btGImpactQuantizedBvh_get_node_pointer__SWIG_0(long jarg1, btGImpactQuantizedBvh jarg1_, int jarg2);
public final static native long btGImpactQuantizedBvh_get_node_pointer__SWIG_1(long jarg1, btGImpactQuantizedBvh jarg1_);
public final static native void btGImpactQuantizedBvh_find_collision(long jarg1, btGImpactQuantizedBvh jarg1_, Matrix4 jarg2, long jarg3, btGImpactQuantizedBvh jarg3_, Matrix4 jarg4, long jarg5, btPairSet jarg5_);
public final static native void delete_btGImpactQuantizedBvh(long jarg1);
public final static native long new_btTetrahedronShapeEx();
public final static native void btTetrahedronShapeEx_setVertices(long jarg1, btTetrahedronShapeEx jarg1_, Vector3 jarg2, Vector3 jarg3, Vector3 jarg4, Vector3 jarg5);
public final static native void delete_btTetrahedronShapeEx(long jarg1);
public final static native void btGImpactShapeInterface_updateBound(long jarg1, btGImpactShapeInterface jarg1_);
public final static native void btGImpactShapeInterface_postUpdate(long jarg1, btGImpactShapeInterface jarg1_);
public final static native long btGImpactShapeInterface_getLocalBox(long jarg1, btGImpactShapeInterface jarg1_);
public final static native int btGImpactShapeInterface_getShapeType(long jarg1, btGImpactShapeInterface jarg1_);
public final static native int btGImpactShapeInterface_getGImpactShapeType(long jarg1, btGImpactShapeInterface jarg1_);
public final static native long btGImpactShapeInterface_getBoxSet(long jarg1, btGImpactShapeInterface jarg1_);
public final static native boolean btGImpactShapeInterface_hasBoxSet(long jarg1, btGImpactShapeInterface jarg1_);
public final static native long btGImpactShapeInterface_getPrimitiveManager(long jarg1, btGImpactShapeInterface jarg1_);
public final static native int btGImpactShapeInterface_getNumChildShapes(long jarg1, btGImpactShapeInterface jarg1_);
public final static native boolean btGImpactShapeInterface_childrenHasTransform(long jarg1, btGImpactShapeInterface jarg1_);
public final static native boolean btGImpactShapeInterface_needsRetrieveTriangles(long jarg1, btGImpactShapeInterface jarg1_);
public final static native boolean btGImpactShapeInterface_needsRetrieveTetrahedrons(long jarg1, btGImpactShapeInterface jarg1_);
public final static native void btGImpactShapeInterface_getBulletTriangle(long jarg1, btGImpactShapeInterface jarg1_, int jarg2, long jarg3, btTriangleShapeEx jarg3_);
public final static native void btGImpactShapeInterface_getBulletTetrahedron(long jarg1, btGImpactShapeInterface jarg1_, int jarg2, long jarg3, btTetrahedronShapeEx jarg3_);
public final static native void btGImpactShapeInterface_lockChildShapes(long jarg1, btGImpactShapeInterface jarg1_);
public final static native void btGImpactShapeInterface_unlockChildShapes(long jarg1, btGImpactShapeInterface jarg1_);
public final static native void btGImpactShapeInterface_getPrimitiveTriangle(long jarg1, btGImpactShapeInterface jarg1_, int jarg2, long jarg3, btPrimitiveTriangle jarg3_);
public final static native void btGImpactShapeInterface_getChildAabb(long jarg1, btGImpactShapeInterface jarg1_, int jarg2, Matrix4 jarg3, Vector3 jarg4, Vector3 jarg5);
public final static native long btGImpactShapeInterface_getChildShape__SWIG_0(long jarg1, btGImpactShapeInterface jarg1_, int jarg2);
public final static native Matrix4 btGImpactShapeInterface_getChildTransform(long jarg1, btGImpactShapeInterface jarg1_, int jarg2);
public final static native void btGImpactShapeInterface_setChildTransform(long jarg1, btGImpactShapeInterface jarg1_, int jarg2, Matrix4 jarg3);
public final static native void btGImpactShapeInterface_rayTest(long jarg1, btGImpactShapeInterface jarg1_, Vector3 jarg2, Vector3 jarg3, long jarg4, RayResultCallback jarg4_);
public final static native void btGImpactShapeInterface_processAllTrianglesRay(long jarg1, btGImpactShapeInterface jarg1_, long jarg2, btTriangleCallback jarg2_, Vector3 jarg3, Vector3 jarg4);
public final static native void delete_btGImpactShapeInterface(long jarg1);
public final static native void delete_btGImpactCompoundShape_CompoundPrimitiveManager(long jarg1);
public final static native void btGImpactCompoundShape_CompoundPrimitiveManager_compoundShape_set(long jarg1, btGImpactCompoundShape.CompoundPrimitiveManager jarg1_, long jarg2, btGImpactCompoundShape jarg2_);
public final static native long btGImpactCompoundShape_CompoundPrimitiveManager_compoundShape_get(long jarg1, btGImpactCompoundShape.CompoundPrimitiveManager jarg1_);
public final static native long new_btGImpactCompoundShape_CompoundPrimitiveManager__SWIG_0(long jarg1, btGImpactCompoundShape.CompoundPrimitiveManager jarg1_);
public final static native long new_btGImpactCompoundShape_CompoundPrimitiveManager__SWIG_1(long jarg1, btGImpactCompoundShape jarg1_);
public final static native long new_btGImpactCompoundShape_CompoundPrimitiveManager__SWIG_2();
public final static native long new_btGImpactCompoundShape__SWIG_0(boolean jarg1);
public final static native long new_btGImpactCompoundShape__SWIG_1();
public final static native void delete_btGImpactCompoundShape(long jarg1);
public final static native long btGImpactCompoundShape_getCompoundPrimitiveManager(long jarg1, btGImpactCompoundShape jarg1_);
public final static native void btGImpactCompoundShape_addChildShape__SWIG_0(long jarg1, btGImpactCompoundShape jarg1_, Matrix4 jarg2, long jarg3, btCollisionShape jarg3_);
public final static native void btGImpactCompoundShape_addChildShape__SWIG_1(long jarg1, btGImpactCompoundShape jarg1_, long jarg2, btCollisionShape jarg2_);
public final static native long btGImpactCompoundShape_getChildShape__SWIG_0(long jarg1, btGImpactCompoundShape jarg1_, int jarg2);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_margin_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, float jarg2);
public final static native float btGImpactMeshShapePart_TrimeshPrimitiveManager_margin_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_meshInterface_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, long jarg2, btStridingMeshInterface jarg2_);
public final static native long btGImpactMeshShapePart_TrimeshPrimitiveManager_meshInterface_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_scale_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, long jarg2, btVector3 jarg2_);
public final static native long btGImpactMeshShapePart_TrimeshPrimitiveManager_scale_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_part_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_part_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_lock_count_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_lock_count_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_vertexbase_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btGImpactMeshShapePart_TrimeshPrimitiveManager_vertexbase_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_numverts_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_numverts_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_type_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_type_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_stride_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_stride_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_indexbase_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btGImpactMeshShapePart_TrimeshPrimitiveManager_indexbase_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_indexstride_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_indexstride_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_numfaces_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_numfaces_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_indicestype_set(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_indicestype_get(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native long new_btGImpactMeshShapePart_TrimeshPrimitiveManager__SWIG_0();
public final static native long new_btGImpactMeshShapePart_TrimeshPrimitiveManager__SWIG_1(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native long new_btGImpactMeshShapePart_TrimeshPrimitiveManager__SWIG_2(long jarg1, btStridingMeshInterface jarg1_, int jarg2);
public final static native void delete_btGImpactMeshShapePart_TrimeshPrimitiveManager(long jarg1);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_lock(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_unlock(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native int btGImpactMeshShapePart_TrimeshPrimitiveManager_get_vertex_count(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_get_indices(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2, long jarg3, long jarg4, long jarg5);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_get_vertex(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, long jarg2, Vector3 jarg3);
public final static native void btGImpactMeshShapePart_TrimeshPrimitiveManager_get_bullet_triangle(long jarg1, btGImpactMeshShapePart.TrimeshPrimitiveManager jarg1_, int jarg2, long jarg3, btTriangleShapeEx jarg3_);
public final static native long new_btGImpactMeshShapePart__SWIG_0();
public final static native long new_btGImpactMeshShapePart__SWIG_1(long jarg1, btStridingMeshInterface jarg1_, int jarg2);
public final static native void delete_btGImpactMeshShapePart(long jarg1);
public final static native long btGImpactMeshShapePart_getChildShape__SWIG_0(long jarg1, btGImpactMeshShapePart jarg1_, int jarg2);
public final static native long btGImpactMeshShapePart_getTrimeshPrimitiveManager(long jarg1, btGImpactMeshShapePart jarg1_);
public final static native int btGImpactMeshShapePart_getVertexCount(long jarg1, btGImpactMeshShapePart jarg1_);
public final static native void btGImpactMeshShapePart_getVertex(long jarg1, btGImpactMeshShapePart jarg1_, int jarg2, Vector3 jarg3);
public final static native int btGImpactMeshShapePart_getPart(long jarg1, btGImpactMeshShapePart jarg1_);
public final static native long new_btGImpactMeshShape(long jarg1, btStridingMeshInterface jarg1_);
public final static native void delete_btGImpactMeshShape(long jarg1);
public final static native long btGImpactMeshShape_getMeshInterface__SWIG_0(long jarg1, btGImpactMeshShape jarg1_);
public final static native int btGImpactMeshShape_getMeshPartCount(long jarg1, btGImpactMeshShape jarg1_);
public final static native long btGImpactMeshShape_getMeshPart__SWIG_0(long jarg1, btGImpactMeshShape jarg1_, int jarg2);
public final static native long btGImpactMeshShape_getChildShape__SWIG_0(long jarg1, btGImpactMeshShape jarg1_, int jarg2);
public final static native void btGImpactMeshShapeData_collisionShapeData_set(long jarg1, btGImpactMeshShapeData jarg1_, long jarg2, btCollisionShapeData jarg2_);
public final static native long btGImpactMeshShapeData_collisionShapeData_get(long jarg1, btGImpactMeshShapeData jarg1_);
public final static native void btGImpactMeshShapeData_meshInterface_set(long jarg1, btGImpactMeshShapeData jarg1_, long jarg2, btStridingMeshInterfaceData jarg2_);
public final static native long btGImpactMeshShapeData_meshInterface_get(long jarg1, btGImpactMeshShapeData jarg1_);
public final static native void btGImpactMeshShapeData_localScaling_set(long jarg1, btGImpactMeshShapeData jarg1_, long jarg2, btVector3FloatData jarg2_);
public final static native long btGImpactMeshShapeData_localScaling_get(long jarg1, btGImpactMeshShapeData jarg1_);
public final static native void btGImpactMeshShapeData_collisionMargin_set(long jarg1, btGImpactMeshShapeData jarg1_, float jarg2);
public final static native float btGImpactMeshShapeData_collisionMargin_get(long jarg1, btGImpactMeshShapeData jarg1_);
public final static native void btGImpactMeshShapeData_gimpactSubType_set(long jarg1, btGImpactMeshShapeData jarg1_, int jarg2);
public final static native int btGImpactMeshShapeData_gimpactSubType_get(long jarg1, btGImpactMeshShapeData jarg1_);
public final static native long new_btGImpactMeshShapeData();
public final static native void delete_btGImpactMeshShapeData(long jarg1);
public final static native void GIM_CONTACT_point_set(long jarg1, GIM_CONTACT jarg1_, long jarg2, btVector3 jarg2_);
public final static native long GIM_CONTACT_point_get(long jarg1, GIM_CONTACT jarg1_);
public final static native void GIM_CONTACT_normal_set(long jarg1, GIM_CONTACT jarg1_, long jarg2, btVector3 jarg2_);
public final static native long GIM_CONTACT_normal_get(long jarg1, GIM_CONTACT jarg1_);
public final static native void GIM_CONTACT_depth_set(long jarg1, GIM_CONTACT jarg1_, float jarg2);
public final static native float GIM_CONTACT_depth_get(long jarg1, GIM_CONTACT jarg1_);
public final static native void GIM_CONTACT_distance_set(long jarg1, GIM_CONTACT jarg1_, float jarg2);
public final static native float GIM_CONTACT_distance_get(long jarg1, GIM_CONTACT jarg1_);
public final static native void GIM_CONTACT_feature1_set(long jarg1, GIM_CONTACT jarg1_, int jarg2);
public final static native int GIM_CONTACT_feature1_get(long jarg1, GIM_CONTACT jarg1_);
public final static native void GIM_CONTACT_feature2_set(long jarg1, GIM_CONTACT jarg1_, int jarg2);
public final static native int GIM_CONTACT_feature2_get(long jarg1, GIM_CONTACT jarg1_);
public final static native long new_GIM_CONTACT__SWIG_0();
public final static native long new_GIM_CONTACT__SWIG_1(long jarg1, GIM_CONTACT jarg1_);
public final static native long new_GIM_CONTACT__SWIG_2(Vector3 jarg1, Vector3 jarg2, float jarg3, int jarg4, int jarg5);
public final static native long GIM_CONTACT_calc_key_contact(long jarg1, GIM_CONTACT jarg1_);
public final static native void GIM_CONTACT_interpolate_normals(long jarg1, GIM_CONTACT jarg1_, long jarg2, btVector3 jarg2_, int jarg3);
public final static native void delete_GIM_CONTACT(long jarg1);
public final static native long new_btContactArray();
public final static native void btContactArray_push_contact(long jarg1, btContactArray jarg1_, Vector3 jarg2, Vector3 jarg3, float jarg4, int jarg5, int jarg6);
public final static native void btContactArray_push_triangle_contacts(long jarg1, btContactArray jarg1_, long jarg2, GIM_TRIANGLE_CONTACT jarg2_, int jarg3, int jarg4);
public final static native void btContactArray_merge_contacts__SWIG_0(long jarg1, btContactArray jarg1_, long jarg2, btContactArray jarg2_, boolean jarg3);
public final static native void btContactArray_merge_contacts__SWIG_1(long jarg1, btContactArray jarg1_, long jarg2, btContactArray jarg2_);
public final static native void btContactArray_merge_contacts_unique(long jarg1, btContactArray jarg1_, long jarg2, btContactArray jarg2_);
public final static native void delete_btContactArray(long jarg1);
public final static native void btGenericMemoryPool_pool_set(long jarg1, btGenericMemoryPool jarg1_, java.nio.ByteBuffer jarg2);
public final static native java.nio.ByteBuffer btGenericMemoryPool_pool_get(long jarg1, btGenericMemoryPool jarg1_);
public final static native void btGenericMemoryPool_free_nodes_set(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native long btGenericMemoryPool_free_nodes_get(long jarg1, btGenericMemoryPool jarg1_);
public final static native void btGenericMemoryPool_allocated_sizes_set(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native long btGenericMemoryPool_allocated_sizes_get(long jarg1, btGenericMemoryPool jarg1_);
public final static native void btGenericMemoryPool_allocated_count_set(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native long btGenericMemoryPool_allocated_count_get(long jarg1, btGenericMemoryPool jarg1_);
public final static native void btGenericMemoryPool_free_nodes_count_set(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native long btGenericMemoryPool_free_nodes_count_get(long jarg1, btGenericMemoryPool jarg1_);
public final static native void btGenericMemoryPool_init_pool(long jarg1, btGenericMemoryPool jarg1_, long jarg2, long jarg3);
public final static native void btGenericMemoryPool_end_pool(long jarg1, btGenericMemoryPool jarg1_);
public final static native long new_btGenericMemoryPool(long jarg1, long jarg2);
public final static native void delete_btGenericMemoryPool(long jarg1);
public final static native long btGenericMemoryPool_get_pool_capacity(long jarg1, btGenericMemoryPool jarg1_);
public final static native long btGenericMemoryPool_gem_element_size(long jarg1, btGenericMemoryPool jarg1_);
public final static native long btGenericMemoryPool_get_max_element_count(long jarg1, btGenericMemoryPool jarg1_);
public final static native long btGenericMemoryPool_get_allocated_count(long jarg1, btGenericMemoryPool jarg1_);
public final static native long btGenericMemoryPool_get_free_positions_count(long jarg1, btGenericMemoryPool jarg1_);
public final static native long btGenericMemoryPool_get_element_data(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native long btGenericMemoryPool_allocate(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native boolean btGenericMemoryPool_freeMemory(long jarg1, btGenericMemoryPool jarg1_, long jarg2);
public final static native void btGenericPoolAllocator_pools_set(long jarg1, btGenericPoolAllocator jarg1_, long jarg2);
public final static native long btGenericPoolAllocator_pools_get(long jarg1, btGenericPoolAllocator jarg1_);
public final static native void btGenericPoolAllocator_pool_count_set(long jarg1, btGenericPoolAllocator jarg1_, long jarg2);
public final static native long btGenericPoolAllocator_pool_count_get(long jarg1, btGenericPoolAllocator jarg1_);
public final static native long btGenericPoolAllocator_get_pool_capacity(long jarg1, btGenericPoolAllocator jarg1_);
public final static native long new_btGenericPoolAllocator(long jarg1, long jarg2);
public final static native void delete_btGenericPoolAllocator(long jarg1);
public final static native long btGenericPoolAllocator_allocate(long jarg1, btGenericPoolAllocator jarg1_, long jarg2);
public final static native boolean btGenericPoolAllocator_freeMemory(long jarg1, btGenericPoolAllocator jarg1_, long jarg2);
public final static native long btPoolAlloc(long jarg1);
public final static native long btPoolRealloc(long jarg1, long jarg2, long jarg3);
public final static native void btPoolFree(long jarg1);
public final static native long new_btGImpactCollisionAlgorithm(long jarg1, btCollisionAlgorithmConstructionInfo jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_);
public final static native void delete_btGImpactCollisionAlgorithm(long jarg1);
public final static native long btGImpactCollisionAlgorithm_internalGetResultOut(long jarg1, btGImpactCollisionAlgorithm jarg1_);
public final static native long new_btGImpactCollisionAlgorithm_CreateFunc();
public final static native void delete_btGImpactCollisionAlgorithm_CreateFunc(long jarg1);
public final static native void btGImpactCollisionAlgorithm_registerAlgorithm(long jarg1, btCollisionDispatcher jarg1_);
public final static native void btGImpactCollisionAlgorithm_gimpact_vs_gimpact(long jarg1, btGImpactCollisionAlgorithm jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btGImpactShapeInterface jarg4_, long jarg5, btGImpactShapeInterface jarg5_);
public final static native void btGImpactCollisionAlgorithm_gimpact_vs_shape(long jarg1, btGImpactCollisionAlgorithm jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btGImpactShapeInterface jarg4_, long jarg5, btCollisionShape jarg5_, boolean jarg6);
public final static native void btGImpactCollisionAlgorithm_gimpact_vs_compoundshape(long jarg1, btGImpactCollisionAlgorithm jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btGImpactShapeInterface jarg4_, long jarg5, btCompoundShape jarg5_, boolean jarg6);
public final static native void btGImpactCollisionAlgorithm_gimpact_vs_concave(long jarg1, btGImpactCollisionAlgorithm jarg1_, long jarg2, btCollisionObjectWrapper jarg2_, long jarg3, btCollisionObjectWrapper jarg3_, long jarg4, btGImpactShapeInterface jarg4_, long jarg5, btConcaveShape jarg5_, boolean jarg6);
public final static native void btGImpactCollisionAlgorithm_setFace0(long jarg1, btGImpactCollisionAlgorithm jarg1_, int jarg2);
public final static native int btGImpactCollisionAlgorithm_getFace0(long jarg1, btGImpactCollisionAlgorithm jarg1_);
public final static native void btGImpactCollisionAlgorithm_setFace1(long jarg1, btGImpactCollisionAlgorithm jarg1_, int jarg2);
public final static native int btGImpactCollisionAlgorithm_getFace1(long jarg1, btGImpactCollisionAlgorithm jarg1_);
public final static native void btGImpactCollisionAlgorithm_setPart0(long jarg1, btGImpactCollisionAlgorithm jarg1_, int jarg2);
public final static native int btGImpactCollisionAlgorithm_getPart0(long jarg1, btGImpactCollisionAlgorithm jarg1_);
public final static native void btGImpactCollisionAlgorithm_setPart1(long jarg1, btGImpactCollisionAlgorithm jarg1_, int jarg2);
public final static native int btGImpactCollisionAlgorithm_getPart1(long jarg1, btGImpactCollisionAlgorithm jarg1_);
public final static native Vector3 gim_inertia_add_transformed(Vector3 jarg1, Vector3 jarg2, Matrix4 jarg3);
public final static native Vector3 gim_get_point_inertia(Vector3 jarg1, float jarg2);
public final static native long btStorageResult_SWIGUpcast(long jarg1);
public final static native long btBroadphaseRayCallback_SWIGUpcast(long jarg1);
public final static native long btDbvtProxy_SWIGUpcast(long jarg1);
public final static native long btDbvtBroadphase_SWIGUpcast(long jarg1);
public final static native long btSimpleBroadphaseProxy_SWIGUpcast(long jarg1);
public final static native long btSimpleBroadphase_SWIGUpcast(long jarg1);
public final static native long btMultiSapBroadphase_btMultiSapProxy_SWIGUpcast(long jarg1);
public final static native long btMultiSapBroadphase_SWIGUpcast(long jarg1);
public final static native long btAxisSweep3InternalShort_Handle_SWIGUpcast(long jarg1);
public final static native long btAxisSweep3InternalShort_SWIGUpcast(long jarg1);
public final static native long btAxisSweep3InternalInt_Handle_SWIGUpcast(long jarg1);
public final static native long btAxisSweep3InternalInt_SWIGUpcast(long jarg1);
public final static native long btAxisSweep3_SWIGUpcast(long jarg1);
public final static native long bt32BitAxisSweep3_SWIGUpcast(long jarg1);
public final static native long btOverlappingPairCache_SWIGUpcast(long jarg1);
public final static native long btHashedOverlappingPairCache_SWIGUpcast(long jarg1);
public final static native long btSortedOverlappingPairCache_SWIGUpcast(long jarg1);
public final static native long btNullPairCache_SWIGUpcast(long jarg1);
public final static native long btConvexShape_SWIGUpcast(long jarg1);
public final static native long btConvexInternalShape_SWIGUpcast(long jarg1);
public final static native long btConvexInternalAabbCachingShape_SWIGUpcast(long jarg1);
public final static native long btPolyhedralConvexShape_SWIGUpcast(long jarg1);
public final static native long btPolyhedralConvexAabbCachingShape_SWIGUpcast(long jarg1);
public final static native long btConcaveShape_SWIGUpcast(long jarg1);
public final static native long btStaticPlaneShape_SWIGUpcast(long jarg1);
public final static native long btHeightfieldTerrainShape_SWIGUpcast(long jarg1);
public final static native long btTriangleMeshShape_SWIGUpcast(long jarg1);
public final static native long btBvhTriangleMeshShape_SWIGUpcast(long jarg1);
public final static native long btBoxShape_SWIGUpcast(long jarg1);
public final static native long btCapsuleShape_SWIGUpcast(long jarg1);
public final static native long btCapsuleShapeX_SWIGUpcast(long jarg1);
public final static native long btCapsuleShapeZ_SWIGUpcast(long jarg1);
public final static native long btBox2dShape_SWIGUpcast(long jarg1);
public final static native long btTriangleShape_SWIGUpcast(long jarg1);
public final static native long btSphereShape_SWIGUpcast(long jarg1);
public final static native long btMinkowskiSumShape_SWIGUpcast(long jarg1);
public final static native long btOptimizedBvh_SWIGUpcast(long jarg1);
public final static native long btTriangleBuffer_SWIGUpcast(long jarg1);
public final static native long btTriangleIndexVertexArray_SWIGUpcast(long jarg1);
public final static native long btScaledBvhTriangleMeshShape_SWIGUpcast(long jarg1);
public final static native long btConvexHullShape_SWIGUpcast(long jarg1);
public final static native long btTriangleIndexVertexMaterialArray_SWIGUpcast(long jarg1);
public final static native long btCylinderShape_SWIGUpcast(long jarg1);
public final static native long btCylinderShapeX_SWIGUpcast(long jarg1);
public final static native long btCylinderShapeZ_SWIGUpcast(long jarg1);
public final static native long btTriangleMesh_SWIGUpcast(long jarg1);
public final static native long btConeShape_SWIGUpcast(long jarg1);
public final static native long btConeShapeX_SWIGUpcast(long jarg1);
public final static native long btConeShapeZ_SWIGUpcast(long jarg1);
public final static native long btConvexTriangleMeshShape_SWIGUpcast(long jarg1);
public final static native long btEmptyShape_SWIGUpcast(long jarg1);
public final static native long btMultimaterialTriangleMeshShape_SWIGUpcast(long jarg1);
public final static native long btBU_Simplex1to4_SWIGUpcast(long jarg1);
public final static native long btUniformScalingShape_SWIGUpcast(long jarg1);
public final static native long btCompoundShape_SWIGUpcast(long jarg1);
public final static native long btConvexPointCloudShape_SWIGUpcast(long jarg1);
public final static native long btConvex2dShape_SWIGUpcast(long jarg1);
public final static native long btEmptyAlgorithm_SWIGUpcast(long jarg1);
public final static native long btActivatingCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btConvexTriangleCallback_SWIGUpcast(long jarg1);
public final static native long btConvexConcaveCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btConvexPlaneCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btCompoundCompoundCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btDefaultCollisionConfiguration_SWIGUpcast(long jarg1);
public final static native long btManifoldResult_SWIGUpcast(long jarg1);
public final static native long btSphereSphereCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btBoxBoxCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btBox2dBox2dCollisionAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btBox2dBox2dCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btSphereTriangleCollisionAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btSphereTriangleCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btGhostObject_SWIGUpcast(long jarg1);
public final static native long btPairCachingGhostObject_SWIGUpcast(long jarg1);
public final static native long btGhostPairCallback_SWIGUpcast(long jarg1);
public final static native long ClosestRayResultCallback_SWIGUpcast(long jarg1);
public final static native long AllHitsRayResultCallback_SWIGUpcast(long jarg1);
public final static native long ClosestConvexResultCallback_SWIGUpcast(long jarg1);
public final static native long ClosestNotMeConvexResultCallback_SWIGUpcast(long jarg1);
public final static native long ClosestNotMeRayResultCallback_SWIGUpcast(long jarg1);
public final static native long btConvex2dConvex2dAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btConvex2dConvex2dAlgorithm_SWIGUpcast(long jarg1);
public final static native long btBoxBoxDetector_SWIGUpcast(long jarg1);
public final static native long btSphereBoxCollisionAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btSphereBoxCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btCollisionDispatcher_SWIGUpcast(long jarg1);
public final static native long btConvexConvexAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btConvexConvexAlgorithm_SWIGUpcast(long jarg1);
public final static native long SphereTriangleDetector_SWIGUpcast(long jarg1);
public final static native long btCompoundCollisionAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btCompoundCollisionAlgorithm_SwappedCreateFunc_SWIGUpcast(long jarg1);
public final static native long btCompoundCollisionAlgorithm_SWIGUpcast(long jarg1);
public final static native long btSubsimplexConvexCast_SWIGUpcast(long jarg1);
public final static native long btPersistentManifold_SWIGUpcast(long jarg1);
public final static native long btGjkPairDetector_SWIGUpcast(long jarg1);
public final static native long btMinkowskiPenetrationDepthSolver_SWIGUpcast(long jarg1);
public final static native long btGjkConvexCast_SWIGUpcast(long jarg1);
public final static native long btContinuousConvexCollision_SWIGUpcast(long jarg1);
public final static native long btTriangleRaycastCallback_SWIGUpcast(long jarg1);
public final static native long btTriangleConvexcastCallback_SWIGUpcast(long jarg1);
public final static native long btGjkEpaPenetrationDepthSolver_SWIGUpcast(long jarg1);
public final static native long btPointCollector_SWIGUpcast(long jarg1);
public final static native long btMultiSphereShape_SWIGUpcast(long jarg1);
public final static native long CustomCollisionDispatcher_SWIGUpcast(long jarg1);
public final static native long btTriangleShapeEx_SWIGUpcast(long jarg1);
public final static native long btTetrahedronShapeEx_SWIGUpcast(long jarg1);
public final static native long btGImpactShapeInterface_SWIGUpcast(long jarg1);
public final static native long btGImpactCompoundShape_CompoundPrimitiveManager_SWIGUpcast(long jarg1);
public final static native long btGImpactCompoundShape_SWIGUpcast(long jarg1);
public final static native long btGImpactMeshShapePart_TrimeshPrimitiveManager_SWIGUpcast(long jarg1);
public final static native long btGImpactMeshShapePart_SWIGUpcast(long jarg1);
public final static native long btGImpactMeshShape_SWIGUpcast(long jarg1);
public final static native long btGImpactCollisionAlgorithm_CreateFunc_SWIGUpcast(long jarg1);
public final static native long btGImpactCollisionAlgorithm_SWIGUpcast(long jarg1);
public static boolean SwigDirector_btBroadphaseAabbCallback_process(btBroadphaseAabbCallback self, long proxy) {
return self.process((proxy == 0) ? null : new btBroadphaseProxy(proxy, false));
}
public static boolean SwigDirector_btBroadphaseRayCallback_process(btBroadphaseRayCallback self, long proxy) {
return self.process((proxy == 0) ? null : new btBroadphaseProxy(proxy, false));
}
public static void SwigDirector_btNodeOverlapCallback_processNode(btNodeOverlapCallback self, int subPart, int triangleIndex) {
self.processNode(subPart, triangleIndex);
}
public static long SwigDirector_btOverlappingPairCallback_addOverlappingPair(btOverlappingPairCallback self, long proxy0, long proxy1) {
return btBroadphasePair.getCPtr(self.addOverlappingPair((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false), (proxy1 == 0) ? null : new btBroadphaseProxy(proxy1, false)));
}
public static long SwigDirector_btOverlappingPairCallback_removeOverlappingPair(btOverlappingPairCallback self, long proxy0, long proxy1, long dispatcher) {
return self.removeOverlappingPair((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false), (proxy1 == 0) ? null : new btBroadphaseProxy(proxy1, false), (dispatcher == 0) ? null : new btDispatcher(dispatcher, false));
}
public static void SwigDirector_btOverlappingPairCallback_removeOverlappingPairsContainingProxy(btOverlappingPairCallback self, long proxy0, long dispatcher) {
self.removeOverlappingPairsContainingProxy((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false), (dispatcher == 0) ? null : new btDispatcher(dispatcher, false));
}
public static boolean SwigDirector_btOverlapCallback_processOverlap(btOverlapCallback self, btBroadphasePair pair) {
return self.processOverlap(pair);
}
public static boolean SwigDirector_btOverlapFilterCallback_needBroadphaseCollision(btOverlapFilterCallback self, long proxy0, long proxy1) {
return self.needBroadphaseCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false), (proxy1 == 0) ? null : new btBroadphaseProxy(proxy1, false));
}
public static void SwigDirector_btTriangleCallback_processTriangle(btTriangleCallback self, long triangle, int partId, int triangleIndex) {
self.processTriangle((triangle == 0) ? null : new btVector3(triangle, false), partId, triangleIndex);
}
public static void SwigDirector_btInternalTriangleIndexCallback_internalProcessTriangleIndex(btInternalTriangleIndexCallback self, long triangle, int partId, int triangleIndex) {
self.internalProcessTriangleIndex((triangle == 0) ? null : new btVector3(triangle, false), partId, triangleIndex);
}
public static void SwigDirector_btConvexTriangleCallback_processTriangle(btConvexTriangleCallback self, long triangle, int partId, int triangleIndex) {
self.processTriangle((triangle == 0) ? null : new btVector3(triangle, false), partId, triangleIndex);
}
public static long SwigDirector_btGhostPairCallback_addOverlappingPair(btGhostPairCallback self, long proxy0, long proxy1) {
return btBroadphasePair.getCPtr(self.addOverlappingPair((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false), (proxy1 == 0) ? null : new btBroadphaseProxy(proxy1, false)));
}
public static long SwigDirector_btGhostPairCallback_removeOverlappingPair(btGhostPairCallback self, long proxy0, long proxy1, long dispatcher) {
return self.removeOverlappingPair((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false), (proxy1 == 0) ? null : new btBroadphaseProxy(proxy1, false), (dispatcher == 0) ? null : new btDispatcher(dispatcher, false));
}
public static void SwigDirector_btGhostPairCallback_removeOverlappingPairsContainingProxy(btGhostPairCallback self, long arg0, long arg1) {
self.removeOverlappingPairsContainingProxy((arg0 == 0) ? null : new btBroadphaseProxy(arg0, false), (arg1 == 0) ? null : new btDispatcher(arg1, false));
}
public static boolean SwigDirector_RayResultCallback_needsCollision(RayResultCallback self, long proxy0) {
return self.needsCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false));
}
public static float SwigDirector_RayResultCallback_addSingleResult(RayResultCallback self, long rayResult, boolean normalInWorldSpace) {
return self.addSingleResult(new LocalRayResult(rayResult, false), normalInWorldSpace);
}
public static boolean SwigDirector_ClosestRayResultCallback_needsCollision(ClosestRayResultCallback self, long proxy0) {
return self.needsCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false));
}
public static float SwigDirector_ClosestRayResultCallback_addSingleResult(ClosestRayResultCallback self, long rayResult, boolean normalInWorldSpace) {
return self.addSingleResult(new LocalRayResult(rayResult, false), normalInWorldSpace);
}
public static boolean SwigDirector_AllHitsRayResultCallback_needsCollision(AllHitsRayResultCallback self, long proxy0) {
return self.needsCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false));
}
public static float SwigDirector_AllHitsRayResultCallback_addSingleResult(AllHitsRayResultCallback self, long rayResult, boolean normalInWorldSpace) {
return self.addSingleResult(new LocalRayResult(rayResult, false), normalInWorldSpace);
}
public static boolean SwigDirector_ConvexResultCallback_needsCollision(ConvexResultCallback self, long proxy0) {
return self.needsCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false));
}
public static float SwigDirector_ConvexResultCallback_addSingleResult(ConvexResultCallback self, long convexResult, boolean normalInWorldSpace) {
return self.addSingleResult(new LocalConvexResult(convexResult, false), normalInWorldSpace);
}
public static boolean SwigDirector_ClosestConvexResultCallback_needsCollision(ClosestConvexResultCallback self, long proxy0) {
return self.needsCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false));
}
public static float SwigDirector_ClosestConvexResultCallback_addSingleResult(ClosestConvexResultCallback self, long convexResult, boolean normalInWorldSpace) {
return self.addSingleResult(new LocalConvexResult(convexResult, false), normalInWorldSpace);
}
public static boolean SwigDirector_ContactResultCallback_needsCollision(ContactResultCallback self, long proxy0) {
return self.needsCollision((proxy0 == 0) ? null : new btBroadphaseProxy(proxy0, false));
}
public static float SwigDirector_ContactResultCallback_addSingleResult(ContactResultCallback self, long cp, long colObj0Wrap, int partId0, int index0, long colObj1Wrap, int partId1, int index1) {
return self.addSingleResult(new btManifoldPoint(cp, false), btCollisionObjectWrapper.obtainForArgument(colObj0Wrap, false), partId0, index0, btCollisionObjectWrapper.obtainForArgument(colObj1Wrap, false), partId1, index1);
}
public static void SwigDirector_btTriangleRaycastCallback_processTriangle(btTriangleRaycastCallback self, long triangle, int partId, int triangleIndex) {
self.processTriangle((triangle == 0) ? null : new btVector3(triangle, false), partId, triangleIndex);
}
public static float SwigDirector_btTriangleRaycastCallback_reportHit(btTriangleRaycastCallback self, Vector3 hitNormalLocal, float hitFraction, int partId, int triangleIndex) {
return self.reportHit(hitNormalLocal, hitFraction, partId, triangleIndex);
}
public static void SwigDirector_btTriangleConvexcastCallback_processTriangle(btTriangleConvexcastCallback self, long triangle, int partId, int triangleIndex) {
self.processTriangle((triangle == 0) ? null : new btVector3(triangle, false), partId, triangleIndex);
}
public static float SwigDirector_btTriangleConvexcastCallback_reportHit(btTriangleConvexcastCallback self, Vector3 hitNormalLocal, Vector3 hitPointLocal, float hitFraction, int partId, int triangleIndex) {
return self.reportHit(hitNormalLocal, hitPointLocal, hitFraction, partId, triangleIndex);
}
public static boolean SwigDirector_CustomCollisionDispatcher_needsCollision(CustomCollisionDispatcher self, long body0, long body1) {
return self.needsCollision(btCollisionObject.getInstance(body0, false), btCollisionObject.getInstance(body1, false));
}
public static boolean SwigDirector_CustomCollisionDispatcher_needsResponse(CustomCollisionDispatcher self, long body0, long body1) {
return self.needsResponse(btCollisionObject.getInstance(body0, false), btCollisionObject.getInstance(body1, false));
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_0(ContactListener self, long cp, long colObj0Wrap, int partId0, int index0, long colObj1Wrap, int partId1, int index1) {
return self.onContactAdded(btManifoldPoint.obtainForArgument(cp, false), btCollisionObjectWrapper.obtainForArgument(colObj0Wrap, false), partId0, index0, btCollisionObjectWrapper.obtainForArgument(colObj1Wrap, false), partId1, index1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_1(ContactListener self, long cp, long colObj0, int partId0, int index0, long colObj1, int partId1, int index1) {
return self.onContactAdded(btManifoldPoint.obtainForArgument(cp, false), btCollisionObject.getInstance(colObj0, false), partId0, index0, btCollisionObject.getInstance(colObj1, false), partId1, index1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_2(ContactListener self, long cp, int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) {
return self.onContactAdded(btManifoldPoint.obtainForArgument(cp, false), userValue0, partId0, index0, userValue1, partId1, index1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_3(ContactListener self, long cp, long colObj0Wrap, int partId0, int index0, boolean match0, long colObj1Wrap, int partId1, int index1, boolean match1) {
return self.onContactAdded(btManifoldPoint.obtainForArgument(cp, false), btCollisionObjectWrapper.obtainForArgument(colObj0Wrap, false), partId0, index0, match0, btCollisionObjectWrapper.obtainForArgument(colObj1Wrap, false), partId1, index1, match1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_4(ContactListener self, long cp, long colObj0, int partId0, int index0, boolean match0, long colObj1, int partId1, int index1, boolean match1) {
return self.onContactAdded(btManifoldPoint.obtainForArgument(cp, false), btCollisionObject.getInstance(colObj0, false), partId0, index0, match0, btCollisionObject.getInstance(colObj1, false), partId1, index1, match1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_5(ContactListener self, long cp, int userValue0, int partId0, int index0, boolean match0, int userValue1, int partId1, int index1, boolean match1) {
return self.onContactAdded(btManifoldPoint.obtainForArgument(cp, false), userValue0, partId0, index0, match0, userValue1, partId1, index1, match1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_6(ContactListener self, long colObj0Wrap, int partId0, int index0, long colObj1Wrap, int partId1, int index1) {
return self.onContactAdded(btCollisionObjectWrapper.obtainForArgument(colObj0Wrap, false), partId0, index0, btCollisionObjectWrapper.obtainForArgument(colObj1Wrap, false), partId1, index1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_7(ContactListener self, long colObj0, int partId0, int index0, long colObj1, int partId1, int index1) {
return self.onContactAdded(btCollisionObject.getInstance(colObj0, false), partId0, index0, btCollisionObject.getInstance(colObj1, false), partId1, index1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_8(ContactListener self, int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) {
return self.onContactAdded(userValue0, partId0, index0, userValue1, partId1, index1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_9(ContactListener self, long colObj0Wrap, int partId0, int index0, boolean match0, long colObj1Wrap, int partId1, int index1, boolean match1) {
return self.onContactAdded(btCollisionObjectWrapper.obtainForArgument(colObj0Wrap, false), partId0, index0, match0, btCollisionObjectWrapper.obtainForArgument(colObj1Wrap, false), partId1, index1, match1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_10(ContactListener self, long colObj0, int partId0, int index0, boolean match0, long colObj1, int partId1, int index1, boolean match1) {
return self.onContactAdded(btCollisionObject.getInstance(colObj0, false), partId0, index0, match0, btCollisionObject.getInstance(colObj1, false), partId1, index1, match1);
}
public static boolean SwigDirector_ContactListener_onContactAdded__SWIG_11(ContactListener self, int userValue0, int partId0, int index0, boolean match0, int userValue1, int partId1, int index1, boolean match1) {
return self.onContactAdded(userValue0, partId0, index0, match0, userValue1, partId1, index1, match1);
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_0(ContactListener self, long cp, long colObj0, long colObj1) {
self.onContactProcessed(btManifoldPoint.obtainForArgument(cp, false), btCollisionObject.getInstance(colObj0, false), btCollisionObject.getInstance(colObj1, false));
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_1(ContactListener self, long cp, int userValue0, int userValue1) {
self.onContactProcessed(btManifoldPoint.obtainForArgument(cp, false), userValue0, userValue1);
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_2(ContactListener self, long cp, long colObj0, boolean match0, long colObj1, boolean match1) {
self.onContactProcessed(btManifoldPoint.obtainForArgument(cp, false), btCollisionObject.getInstance(colObj0, false), match0, btCollisionObject.getInstance(colObj1, false), match1);
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_3(ContactListener self, long cp, int userValue0, boolean match0, int userValue1, boolean match1) {
self.onContactProcessed(btManifoldPoint.obtainForArgument(cp, false), userValue0, match0, userValue1, match1);
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_4(ContactListener self, long colObj0, long colObj1) {
self.onContactProcessed(btCollisionObject.getInstance(colObj0, false), btCollisionObject.getInstance(colObj1, false));
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_5(ContactListener self, int userValue0, int userValue1) {
self.onContactProcessed(userValue0, userValue1);
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_6(ContactListener self, long colObj0, boolean match0, long colObj1, boolean match1) {
self.onContactProcessed(btCollisionObject.getInstance(colObj0, false), match0, btCollisionObject.getInstance(colObj1, false), match1);
}
public static void SwigDirector_ContactListener_onContactProcessed__SWIG_7(ContactListener self, int userValue0, boolean match0, int userValue1, boolean match1) {
self.onContactProcessed(userValue0, match0, userValue1, match1);
}
public static void SwigDirector_ContactListener_onContactDestroyed(ContactListener self, int manifoldPointUserValue) {
self.onContactDestroyed(manifoldPointUserValue);
}
public static void SwigDirector_ContactListener_onContactStarted__SWIG_0(ContactListener self, long manifold) {
self.onContactStarted((manifold == 0) ? null : new btPersistentManifold(manifold, false));
}
public static void SwigDirector_ContactListener_onContactStarted__SWIG_1(ContactListener self, long colObj0, long colObj1) {
self.onContactStarted(btCollisionObject.getInstance(colObj0, false), btCollisionObject.getInstance(colObj1, false));
}
public static void SwigDirector_ContactListener_onContactStarted__SWIG_2(ContactListener self, int userValue0, int userValue1) {
self.onContactStarted(userValue0, userValue1);
}
public static void SwigDirector_ContactListener_onContactStarted__SWIG_3(ContactListener self, long manifold, boolean match0, boolean match1) {
self.onContactStarted((manifold == 0) ? null : new btPersistentManifold(manifold, false), match0, match1);
}
public static void SwigDirector_ContactListener_onContactStarted__SWIG_4(ContactListener self, long colObj0, boolean match0, long colObj1, boolean match1) {
self.onContactStarted(btCollisionObject.getInstance(colObj0, false), match0, btCollisionObject.getInstance(colObj1, false), match1);
}
public static void SwigDirector_ContactListener_onContactStarted__SWIG_5(ContactListener self, int userValue0, boolean match0, int userValue1, boolean match1) {
self.onContactStarted(userValue0, match0, userValue1, match1);
}
public static void SwigDirector_ContactListener_onContactEnded__SWIG_0(ContactListener self, long manifold) {
self.onContactEnded((manifold == 0) ? null : new btPersistentManifold(manifold, false));
}
public static void SwigDirector_ContactListener_onContactEnded__SWIG_1(ContactListener self, long colObj0, long colObj1) {
self.onContactEnded(btCollisionObject.getInstance(colObj0, false), btCollisionObject.getInstance(colObj1, false));
}
public static void SwigDirector_ContactListener_onContactEnded__SWIG_2(ContactListener self, int userValue0, int userValue1) {
self.onContactEnded(userValue0, userValue1);
}
public static void SwigDirector_ContactListener_onContactEnded__SWIG_3(ContactListener self, long manifold, boolean match0, boolean match1) {
self.onContactEnded((manifold == 0) ? null : new btPersistentManifold(manifold, false), match0, match1);
}
public static void SwigDirector_ContactListener_onContactEnded__SWIG_4(ContactListener self, long colObj0, boolean match0, long colObj1, boolean match1) {
self.onContactEnded(btCollisionObject.getInstance(colObj0, false), match0, btCollisionObject.getInstance(colObj1, false), match1);
}
public static void SwigDirector_ContactListener_onContactEnded__SWIG_5(ContactListener self, int userValue0, boolean match0, int userValue1, boolean match1) {
self.onContactEnded(userValue0, match0, userValue1, match1);
}
public static void SwigDirector_ContactCache_onContactStarted(ContactCache self, long manifold, boolean match0, boolean match1) {
self.onContactStarted((manifold == 0) ? null : new btPersistentManifold(manifold, false), match0, match1);
}
public static void SwigDirector_ContactCache_onContactEnded(ContactCache self, long colObj0, boolean match0, long colObj1, boolean match1) {
self.onContactEnded(btCollisionObject.getInstance(colObj0, false), match0, btCollisionObject.getInstance(colObj1, false), match1);
}
private final static native void swig_module_init();
static {
swig_module_init();
}
}
| EsikAntony/libgdx | extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/CollisionJNI.java | Java | apache-2.0 | 392,685 |
// Copyright 2021 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package types
import (
"fmt"
"strings"
"sigs.k8s.io/kustomize/kyaml/resid"
)
const DefaultReplacementFieldPath = "metadata.name"
// Replacement defines how to perform a substitution
// where it is from and where it is to.
type Replacement struct {
// The source of the value.
Source *SourceSelector `json:"source" yaml:"source"`
// The N fields to write the value to.
Targets []*TargetSelector `json:"targets" yaml:"targets"`
}
// SourceSelector is the source of the replacement transformer.
type SourceSelector struct {
// A specific object to read it from.
resid.ResId `json:",inline,omitempty" yaml:",inline,omitempty"`
// Structured field path expected in the allowed object.
FieldPath string `json:"fieldPath" yaml:"fieldPath"`
// Used to refine the interpretation of the field.
Options *FieldOptions `json:"options" yaml:"options"`
}
func (s *SourceSelector) String() string {
if s == nil {
return ""
}
result := []string{s.ResId.String()}
if s.FieldPath != "" {
result = append(result, s.FieldPath)
}
if opts := s.Options.String(); opts != "" {
result = append(result, opts)
}
return strings.Join(result, ":")
}
// TargetSelector specifies fields in one or more objects.
type TargetSelector struct {
// Include objects that match this.
Select *Selector `json:"select" yaml:"select"`
// From the allowed set, remove objects that match this.
Reject []*Selector `json:"reject" yaml:"reject"`
// Structured field paths expected in each allowed object.
FieldPaths []string `json:"fieldPaths" yaml:"fieldPaths"`
// Used to refine the interpretation of the field.
Options *FieldOptions `json:"options" yaml:"options"`
}
// FieldOptions refine the interpretation of FieldPaths.
type FieldOptions struct {
// Used to split/join the field.
Delimiter string `json:"delimiter" yaml:"delimiter"`
// Which position in the split to consider.
Index int `json:"index" yaml:"index"`
// TODO (#3492): Implement use of this option
// None, Base64, URL, Hex, etc
Encoding string `json:"encoding" yaml:"encoding"`
// If field missing, add it.
Create bool `json:"create" yaml:"create"`
}
func (fo *FieldOptions) String() string {
if fo == nil || fo.Delimiter == "" {
return ""
}
return fmt.Sprintf("%s(%d)", fo.Delimiter, fo.Index)
}
| verult/kubernetes | vendor/sigs.k8s.io/kustomize/api/types/replacement.go | GO | apache-2.0 | 2,367 |
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax
var buffer = new ArrayBuffer(0x100);
var array = new Uint8Array(buffer).fill(55);
var tmp = {};
tmp[Symbol.toPrimitive] = function () {
%ArrayBufferNeuter(array.buffer)
return 0;
};
assertEquals(-1, Array.prototype.indexOf.call(array, 0x00, tmp));
buffer = new ArrayBuffer(0x100);
array = new Uint8Array(buffer).fill(55);
tmp = {};
tmp[Symbol.toPrimitive] = function () {
%ArrayBufferNeuter(array.buffer)
return 0;
};
assertEquals(false, Array.prototype.includes.call(array, 0x00, tmp));
buffer = new ArrayBuffer(0x100);
array = new Uint8Array(buffer).fill(55);
tmp = {};
tmp[Symbol.toPrimitive] = function () {
%ArrayBufferNeuter(array.buffer)
return 0;
};
assertEquals(true, Array.prototype.includes.call(array, undefined, tmp));
| macchina-io/macchina.io | platform/JS/V8/v8/test/mjsunit/regress/regress-crbug-691323.js | JavaScript | apache-2.0 | 951 |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revision = '19a67dc67c3'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False))
op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False))
op.execute('''
UPDATE cycle_task_group_objects
JOIN task_group_objects
ON cycle_task_group_objects.task_group_object_id = task_group_objects.id
SET
cycle_task_group_objects.object_id = task_group_objects.object_id,
cycle_task_group_objects.object_type = task_group_objects.object_type;
''')
def downgrade():
op.drop_column('cycle_task_group_objects', 'object_type')
op.drop_column('cycle_task_group_objects', 'object_id')
| VinnieJohns/ggrc-core | src/ggrc_workflows/migrations/versions/20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py | Python | apache-2.0 | 1,141 |
###########################################################################
## ##
## Centre for Speech Technology Research ##
## University of Edinburgh, UK ##
## Copyright (c) 1996 ##
## All Rights Reserved. ##
## ##
## Permission is hereby granted, free of charge, to use and distribute ##
## this software and its documentation without restriction, including ##
## without limitation the rights to use, copy, modify, merge, publish, ##
## distribute, sublicense, and/or sell copies of this work, and to ##
## permit persons to whom this work is furnished to do so, subject to ##
## the following conditions: ##
## 1. The code must retain the above copyright notice, this list of ##
## conditions and the following disclaimer. ##
## 2. Any modifications must be clearly marked as such. ##
## 3. Original authors' names are not deleted. ##
## 4. The authors' names are not used to endorse or promote products ##
## derived from this software without specific prior written ##
## permission. ##
## ##
## THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ##
## DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ##
## ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ##
## SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ##
## FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ##
## WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ##
## AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ##
## ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ##
## THIS SOFTWARE. ##
## ##
###########################################################################
TOP=../../../../..
DIRNAME=src/modules/java/cstr/festival
BUILD_DIRS = client scheme
ALL_DIRS = $(BUILD_DIRS) jsapi
JAVA_CLASSES = Client
NEED_JAVA=1
FILES = Makefile $(JAVA_CLASSES:=.java)
ALL = .java .sub_directories
include $(TOP)/config/common_make_rules
| mjansche/tts-tutorial | usr_local/src/festival/src/modules/java/cstr/festival/Makefile | Makefile | apache-2.0 | 2,699 |
# Copyright 2017 Google Inc.
#
# 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.
"""
Unit tests for attention functions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
import numpy as np
from seq2seq.decoders.attention import AttentionLayerDot
from seq2seq.decoders.attention import AttentionLayerBahdanau
class AttentionLayerTest(tf.test.TestCase):
"""
Tests the AttentionLayer module.
"""
def setUp(self):
super(AttentionLayerTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 8
self.attention_dim = 128
self.input_dim = 16
self.seq_len = 10
self.state_dim = 32
def _create_layer(self):
"""Creates the attention layer. Should be implemented by child classes"""
raise NotImplementedError
def _test_layer(self):
"""Tests Attention layer with a given score type"""
inputs_pl = tf.placeholder(tf.float32, (None, None, self.input_dim))
inputs_length_pl = tf.placeholder(tf.int32, [None])
state_pl = tf.placeholder(tf.float32, (None, self.state_dim))
attention_fn = self._create_layer()
scores, context = attention_fn(
query=state_pl,
keys=inputs_pl,
values=inputs_pl,
values_length=inputs_length_pl)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
feed_dict = {}
feed_dict[inputs_pl] = np.random.randn(self.batch_size, self.seq_len,
self.input_dim)
feed_dict[state_pl] = np.random.randn(self.batch_size, self.state_dim)
feed_dict[inputs_length_pl] = np.arange(self.batch_size) + 1
scores_, context_ = sess.run([scores, context], feed_dict)
np.testing.assert_array_equal(scores_.shape,
[self.batch_size, self.seq_len])
np.testing.assert_array_equal(context_.shape,
[self.batch_size, self.input_dim])
for idx, batch in enumerate(scores_, 1):
# All scores that are padded should be zero
np.testing.assert_array_equal(batch[idx:], np.zeros_like(batch[idx:]))
# Scores should sum to 1
scores_sum = np.sum(scores_, axis=1)
np.testing.assert_array_almost_equal(scores_sum, np.ones([self.batch_size]))
class AttentionLayerDotTest(AttentionLayerTest):
"""Tests the AttentionLayerDot class"""
def _create_layer(self):
return AttentionLayerDot(
params={"num_units": self.attention_dim},
mode=tf.contrib.learn.ModeKeys.TRAIN)
def test_layer(self):
self._test_layer()
class AttentionLayerBahdanauTest(AttentionLayerTest):
"""Tests the AttentionLayerBahdanau class"""
def _create_layer(self):
return AttentionLayerBahdanau(
params={"num_units": self.attention_dim},
mode=tf.contrib.learn.ModeKeys.TRAIN)
def test_layer(self):
self._test_layer()
if __name__ == "__main__":
tf.test.main()
| shashankrajput/seq2seq | seq2seq/test/attention_test.py | Python | apache-2.0 | 3,532 |
// SlotArea.h
// Interfaces to the cSlotArea class representing a contiguous area of slots in a UI window
#pragma once
#include "../Inventory.h"
#include "Window.h"
class cWindow;
class cPlayer;
class cBeaconEntity;
class cBrewingstandEntity;
class cChestEntity;
class cEnderChestEntity;
class cFurnaceEntity;
class cMinecartWithChest;
class cCraftingRecipe;
class cWorld;
class cSlotArea
{
public:
cSlotArea(int a_NumSlots, cWindow & a_ParentWindow);
virtual ~cSlotArea() {} // force a virtual destructor in all subclasses
int GetNumSlots(void) const { return m_NumSlots; }
/** Called to retrieve an item in the specified slot for the specified player. Must return a valid cItem. */
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const = 0;
/** Called to set an item in the specified slot for the specified player */
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) = 0;
/** Called when a player clicks in the window. Parameters taken from the click packet. */
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem);
/** Called from Clicked when the action is a shiftclick (left or right) */
virtual void ShiftClicked(cPlayer & a_Player, int a_SlotNum, const cItem & a_ClickedItem);
/** Called from Clicked when the action is a caDblClick */
virtual void DblClicked(cPlayer & a_Player, int a_SlotNum);
/** Called from Clicked when the action is a middleclick */
virtual void MiddleClicked(cPlayer & a_Player, int a_SlotNum);
/** Called from Clicked when the action is a drop click. */
virtual void DropClicked(cPlayer & a_Player, int a_SlotNum, bool a_DropStack);
/** Called from Clicked when the action is a number click. */
virtual void NumberClicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction);
/** Called when a new player opens the same parent window. The window already tracks the player. CS-locked. */
virtual void OnPlayerAdded(cPlayer & a_Player);
/** Called when one of the players closes the parent window. The window already doesn't track the player. CS-locked. */
virtual void OnPlayerRemoved(cPlayer & a_Player);
/** Called to store as much of a_ItemStack in the area as possible. a_ItemStack is modified to reflect the change.
The default implementation searches each slot for available space and distributes the stack there.
if a_ShouldApply is true, the changes are written into the slots;
if a_ShouldApply is false, only a_ItemStack is modified to reflect the number of fits (for fit-testing purposes)
If a_KeepEmptySlots is true, empty slots will be skipped and won't be filled */
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill);
/** Called on DblClicking to collect all stackable items into hand.
The items are accumulated in a_Dragging and removed from the slots immediately.
If a_CollectFullStacks is false, slots with full stacks are skipped while collecting.
Returns true if full stack has been collected in a_Dragging, false if there's space remaining to fill. */
virtual bool CollectItemsToHand(cItem & a_Dragging, cPlayer & a_Player, bool a_CollectFullStacks);
protected:
int m_NumSlots;
cWindow & m_ParentWindow;
} ;
/** Handles any part of the inventory, using parameters in constructor to distinguish between the parts */
class cSlotAreaInventoryBase :
public cSlotArea
{
typedef cSlotArea super;
public:
cSlotAreaInventoryBase(int a_NumSlots, int a_SlotOffset, cWindow & a_ParentWindow);
// Creative inventory's click handling is somewhat different from survival inventory's, handle that here:
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
int m_SlotOffset; // Index that this area's slot 0 has in the underlying cInventory
} ;
/** Handles the main inventory of each player, excluding the armor and hotbar */
class cSlotAreaInventory :
public cSlotAreaInventoryBase
{
typedef cSlotAreaInventoryBase super;
public:
cSlotAreaInventory(cWindow & a_ParentWindow) :
cSlotAreaInventoryBase(cInventory::invInventoryCount, cInventory::invInventoryOffset, a_ParentWindow)
{
}
} ;
/** Handles the hotbar of each player */
class cSlotAreaHotBar :
public cSlotAreaInventoryBase
{
typedef cSlotAreaInventoryBase super;
public:
cSlotAreaHotBar(cWindow & a_ParentWindow) :
cSlotAreaInventoryBase(cInventory::invHotbarCount, cInventory::invHotbarOffset, a_ParentWindow)
{
}
} ;
/** Handles the armor area of the player's inventory */
class cSlotAreaArmor :
public cSlotAreaInventoryBase
{
public:
cSlotAreaArmor(cWindow & a_ParentWindow) :
cSlotAreaInventoryBase(cInventory::invArmorCount, cInventory::invArmorOffset, a_ParentWindow)
{
}
/** Distributing the stack is allowed only for compatible items (helmets into helmet slot etc.) */
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
/** Called when a player clicks in the window. Parameters taken from the click packet. */
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
static bool CanPlaceArmorInSlot(int a_SlotNum, const cItem & a_Item);
} ;
/** Handles any slot area that is representing a cItemGrid; same items for all the players */
class cSlotAreaItemGrid :
public cSlotArea,
public cItemGrid::cListener
{
typedef cSlotArea super;
public:
cSlotAreaItemGrid(cItemGrid & a_ItemGrid, cWindow & a_ParentWindow);
virtual ~cSlotAreaItemGrid();
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cItemGrid & m_ItemGrid;
// cItemGrid::cListener overrides:
virtual void OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) override;
} ;
/** A cSlotArea with items layout that is private to each player and is temporary, such as
a crafting grid or an enchantment table.
This common ancestor stores the items in a per-player map. It also implements tossing items from the map. */
class cSlotAreaTemporary :
public cSlotArea
{
typedef cSlotArea super;
public:
cSlotAreaTemporary(int a_NumSlots, cWindow & a_ParentWindow);
// cSlotArea overrides:
virtual const cItem * GetSlot (int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot (int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
virtual void OnPlayerAdded (cPlayer & a_Player) override;
virtual void OnPlayerRemoved(cPlayer & a_Player) override;
/** Tosses the player's items in slots [a_Begin, a_End) (ie. incl. a_Begin, but excl. a_End) */
void TossItems(cPlayer & a_Player, int a_Begin, int a_End);
protected:
typedef std::map<UInt32, std::vector<cItem> > cItemMap; // Maps EntityID -> items
cItemMap m_Items;
/** Returns the pointer to the slot array for the player specified. */
cItem * GetPlayerSlots(cPlayer & a_Player);
} ;
class cSlotAreaCrafting :
public cSlotAreaTemporary
{
typedef cSlotAreaTemporary super;
public:
/** a_GridSize is allowed to be only 2 or 3 */
cSlotAreaCrafting(int a_GridSize, cWindow & a_ParentWindow);
// cSlotAreaTemporary overrides:
virtual void Clicked (cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual void DblClicked (cPlayer & a_Player, int a_SlotNum) override;
virtual void OnPlayerRemoved(cPlayer & a_Player) override;
virtual void SetSlot (int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
// Distributing items into this area is completely disabled
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
protected:
/** Maps player's EntityID -> current recipe.
Not a std::map because cCraftingGrid needs proper constructor params. */
typedef std::list<std::pair<UInt32, cCraftingRecipe> > cRecipeMap;
int m_GridSize;
cRecipeMap m_Recipes;
/** Handles a click in the result slot.
Crafts using the current recipe, if possible. */
void ClickedResult(cPlayer & a_Player);
/** Handles a shift-click in the result slot.
Crafts using the current recipe until it changes or no more space for result. */
void ShiftClickedResult(cPlayer & a_Player);
/** Handles a drop-click in the result slot. */
void DropClickedResult(cPlayer & a_Player);
/** Updates the current recipe and result slot based on the ingredients currently in the crafting grid of the specified player. */
void UpdateRecipe(cPlayer & a_Player);
/** Retrieves the recipe for the specified player from the map, or creates one if not found. */
cCraftingRecipe & GetRecipeForPlayer(cPlayer & a_Player);
/** Called after an item has been crafted to handle statistics e.t.c. */
void HandleCraftItem(const cItem & a_Result, cPlayer & a_Player);
} ;
class cSlotAreaAnvil :
public cSlotAreaTemporary
{
typedef cSlotAreaTemporary super;
public:
cSlotAreaAnvil(cWindow & a_ParentWindow);
// cSlotArea overrides:
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual void ShiftClicked(cPlayer & a_Player, int a_SlotNum, const cItem & a_ClickedItem) override;
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
// cSlotAreaTemporary overrides:
virtual void OnPlayerRemoved(cPlayer & a_Player) override;
/** Can the player take the item from the slot? */
bool CanTakeResultItem(cPlayer & a_Player);
/** This function will call, when the player take the item from the slot. */
void OnTakeResult(cPlayer & a_Player);
/** Handles a click in the item slot. */
void UpdateResult(cPlayer & a_Player);
protected:
/** The maximum cost of repairing / renaming in the anvil. */
int m_MaximumCost;
/** The stack size of the second item where was used for repair */
char m_StackSizeToBeUsedInRepair;
} ;
class cSlotAreaBeacon :
public cSlotArea,
public cItemGrid::cListener
{
typedef cSlotArea super;
public:
cSlotAreaBeacon(cBeaconEntity * a_Beacon, cWindow & a_ParentWindow);
virtual ~cSlotAreaBeacon();
static bool IsPlaceableItem(short a_ItemType);
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cBeaconEntity * m_Beacon;
// cItemGrid::cListener overrides:
virtual void OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) override;
} ;
class cSlotAreaEnchanting :
public cSlotAreaTemporary
{
typedef cSlotAreaTemporary super;
public:
cSlotAreaEnchanting(cWindow & a_ParentWindow, int a_BlockX, int a_BlockY, int a_BlockZ);
// cSlotArea overrides:
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
// cSlotAreaTemporary overrides:
virtual void OnPlayerAdded (cPlayer & a_Player) override;
virtual void OnPlayerRemoved(cPlayer & a_Player) override;
/* Get the count of bookshelves who stand in the near of the enchanting table */
int GetBookshelvesCount(cWorld * a_World);
protected:
/** Handles a click in the item slot. */
void UpdateResult(cPlayer & a_Player);
int m_BlockX, m_BlockY, m_BlockZ;
};
class cSlotAreaChest :
public cSlotArea
{
public:
cSlotAreaChest(cChestEntity * a_Chest, cWindow & a_ParentWindow);
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cChestEntity * m_Chest;
} ;
class cSlotAreaDoubleChest :
public cSlotArea
{
public:
cSlotAreaDoubleChest(cChestEntity * a_TopChest, cChestEntity * a_BottomChest, cWindow & a_ParentWindow);
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cChestEntity * m_TopChest;
cChestEntity * m_BottomChest;
} ;
class cSlotAreaEnderChest :
public cSlotArea
{
public:
cSlotAreaEnderChest(cEnderChestEntity * a_EnderChest, cWindow & a_ParentWindow);
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cEnderChestEntity * m_EnderChest;
};
class cSlotAreaFurnace :
public cSlotArea,
public cItemGrid::cListener
{
typedef cSlotArea super;
public:
cSlotAreaFurnace(cFurnaceEntity * a_Furnace, cWindow & a_ParentWindow);
virtual ~cSlotAreaFurnace();
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cFurnaceEntity * m_Furnace;
// cItemGrid::cListener overrides:
virtual void OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) override;
/** Called after an item has been smelted to handle statistics etc. */
void HandleSmeltItem(const cItem & a_Result, cPlayer & a_Player);
} ;
class cSlotAreaBrewingstand :
public cSlotArea,
public cItemGrid::cListener
{
typedef cSlotArea super;
public:
cSlotAreaBrewingstand(cBrewingstandEntity * a_Brewingstand, cWindow & a_ParentWindow);
virtual ~cSlotAreaBrewingstand();
virtual void Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) override;
virtual void DistributeStack(cItem & a_ItemStack, cPlayer & a_Player, bool a_ShouldApply, bool a_KeepEmptySlots, bool a_BackFill) override;
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cBrewingstandEntity * m_Brewingstand;
// cItemGrid::cListener overrides:
virtual void OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) override;
/** Called after an item has been brewed to handle statistics etc. */
void HandleBrewedItem(cPlayer & a_Player);
} ;
class cSlotAreaMinecartWithChest :
public cSlotArea
{
public:
cSlotAreaMinecartWithChest(cMinecartWithChest * a_ChestCart, cWindow & a_ParentWindow);
virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override;
virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override;
protected:
cMinecartWithChest * m_Chest;
};
| HelenaKitty/EbooMC | src/UI/SlotArea.h | C | apache-2.0 | 15,881 |
/*
* Copyright 2014-2016 CyberVision, Inc.
*
* 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.
*/
/**
* Provides implementation of default configuration processing algorithm
*/
package org.kaaproject.kaa.server.common.core.algorithms.generation; | vtkhir/kaa | common/core/src/main/java/org/kaaproject/kaa/server/common/core/algorithms/generation/package-info.java | Java | apache-2.0 | 757 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import org.apache.drill.exec.expr.annotations.Workspace;
<@pp.dropOutputFile />
<@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/GDateTimeTruncateFunctions.java" />
<#include "/@includes/license.ftl" />
package org.apache.drill.exec.expr.fn.impl;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.holders.*;
import org.apache.drill.exec.record.RecordBatch;
import io.netty.buffer.ByteBuf;
public class GDateTimeTruncateFunctions {
<#list dateIntervalFunc.dates as type>
@SuppressWarnings("unused")
@FunctionTemplate(names = "date_trunc", scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL)
public static class G${type}DateTrunc implements DrillSimpleFunc {
@Param VarCharHolder left;
@Param ${type}Holder right;
@Output ${type}Holder out;
@Workspace org.joda.time.MutableDateTime dateTime;
public void setup(RecordBatch incoming) {
dateTime = new org.joda.time.MutableDateTime(org.joda.time.DateTimeZone.UTC);
}
public void eval() {
dateTime.setMillis(right.value);
<#if type != "Time">
if (org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(left.start, left.end, left.buffer).equalsIgnoreCase("YEAR")) dateTime.setRounding(dateTime.getChronology().year());
else if (org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(left.start, left.end, left.buffer).equalsIgnoreCase("MONTH")) dateTime.setRounding(dateTime.getChronology().monthOfYear());
else if (org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(left.start, left.end, left.buffer).equalsIgnoreCase("DAY")) dateTime.setRounding(dateTime.getChronology().dayOfMonth());
else
</#if>
<#if type != "Date">
if (org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(left.start, left.end, left.buffer).equalsIgnoreCase("HOUR")) dateTime.setRounding(dateTime.getChronology().hourOfDay());
else if (org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(left.start, left.end, left.buffer).equalsIgnoreCase("MINUTE")) dateTime.setRounding(dateTime.getChronology().minuteOfHour());
else if (org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(left.start, left.end, left.buffer).equalsIgnoreCase("SECOND")) dateTime.setRounding(dateTime.getChronology().secondOfMinute());
else
</#if>
<#if type == "TimeStamp" || type == "TimeStampTZ">
throw new UnsupportedOperationException("date_trunc function supports the following time units for TimeStamp(TZ): YEAR, MONTH, DAY, HOUR, MINUTE, SECOND");
out.value = dateTime.getMillis();
<#elseif type == "Date">
throw new UnsupportedOperationException("date_trunc function supports the following time units for Date: YEAR, MONTH, DAY");
out.value = dateTime.getMillis();
<#elseif type == "Time">
throw new UnsupportedOperationException("date_trunc function supports the following time units for Time: HOUR, MINUTE, SECOND");
out.value = (int) dateTime.getMillis();
</#if>
}
}
</#list>
} | yssharma/pig-on-drill | exec/java-exec/src/main/codegen/templates/DateIntervalFunctionTemplates/DateTruncFunctions.java | Java | apache-2.0 | 4,333 |
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2001 Johannes Lehtinen
* Copyright 2002 Paul Wilkinson
*
* 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 com.izforge.izpack.core.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* Stream which countes the bytes written through it. Be sure to flush before checking size.
*/
public class ByteCountingOutputStream extends OutputStream
{
private long count;
private OutputStream os;
public ByteCountingOutputStream(OutputStream os)
{
setOutputStream(os);
}
public void write(byte[] b, int off, int len) throws IOException
{
os.write(b, off, len);
count += len;
}
public void write(byte[] b) throws IOException
{
os.write(b);
count += b.length;
}
public void write(int b) throws IOException
{
os.write(b);
count++;
}
public void close() throws IOException
{
os.close();
}
public void flush() throws IOException
{
os.flush();
}
public long getByteCount()
{
return count;
}
protected void setOutputStream(OutputStream stream)
{
this.os = stream;
count = 0;
}
}
| codehaus/izpack | izpack-core/src/main/java/com/izforge/izpack/core/io/ByteCountingOutputStream.java | Java | apache-2.0 | 1,857 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.content.impl;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URI;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.ArrayUtils;
import org.sakaiproject.alias.api.AliasService;
import org.sakaiproject.antivirus.api.VirusFoundException;
import org.sakaiproject.antivirus.api.VirusScanIncompleteException;
import org.sakaiproject.antivirus.api.VirusScanner;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.api.RoleAlreadyDefinedException;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.conditions.api.ConditionService;
import org.sakaiproject.content.api.*;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.api.providers.SiteContentAdvisor;
import org.sakaiproject.content.api.providers.SiteContentAdvisorProvider;
import org.sakaiproject.content.api.providers.SiteContentAdvisorTypeRegistry;
import org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess;
import org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess;
import org.sakaiproject.content.util.ZipContentUtil;
import org.sakaiproject.entity.api.ContextObserver;
import org.sakaiproject.entity.api.Edit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityAccessOverloadException;
import org.sakaiproject.entity.api.EntityCopyrightException;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.EntityNotDefinedException;
import org.sakaiproject.entity.api.EntityPermissionException;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.EntityTransferrerRefMigrator;
import org.sakaiproject.entity.api.HardDeleteAware;
import org.sakaiproject.entity.api.HttpAccess;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.api.serialize.EntityParseException;
import org.sakaiproject.entity.api.serialize.EntityReader;
import org.sakaiproject.entity.api.serialize.EntityReaderHandler;
import org.sakaiproject.entity.api.serialize.EntitySerializer;
import org.sakaiproject.entity.api.serialize.SerializableEntity;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationEdit;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.CopyrightException;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.memory.api.Cache;
import org.sakaiproject.memory.api.CacheRefresher;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.thread_local.api.ThreadBound;
import org.sakaiproject.thread_local.api.ThreadLocalManager;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.SessionBindingEvent;
import org.sakaiproject.tool.api.SessionBindingListener;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.util.BaseResourcePropertiesEdit;
import org.sakaiproject.util.DefaultEntityHandler;
import org.sakaiproject.util.Resource;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SAXEntityReader;
import org.sakaiproject.util.SingleStorageUser;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.Web;
import org.sakaiproject.util.Xml;
import org.sakaiproject.util.api.LinkMigrationHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.detect.Detector;
import org.apache.tika.mime.MimeTypes;
/**
* <p>
* BaseContentService is an abstract base implementation of the Sakai ContentHostingService.
* </p>
*/
public abstract class BaseContentService implements ContentHostingService, CacheRefresher, ContextObserver, EntityTransferrer,
SiteContentAdvisorProvider, SiteContentAdvisorTypeRegistry, EntityTransferrerRefMigrator, HardDeleteAware
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseContentService.class);
protected static final long END_OF_TIME = 8000L * 365L * 24L * 60L * 60L * 1000L;
protected static final long START_OF_TIME = 365L * 24L * 60L * 60L * 1000L;
/** Maximum length of a URL which we allow for redirection
* (c/f http://www.boutell.com/newfaq/misc/urllength.html) */
protected static final long MAX_URL_LENGTH = 8192;
protected static final Pattern contextPattern = Pattern.compile("\\A/(group/|user/|~)(.+?)/");
/** sakai.properties setting to enable secure inline html (true by default) */
protected static final String SECURE_INLINE_HTML = "content.html.forcedownload";
private static final String PROP_AVAIL_NOTI = "availableNotified";
/** MIME multipart separation string */
protected static final String MIME_SEPARATOR = "SAKAI_MIME_BOUNDARY";
protected static final String DEFAULT_RESOURCE_QUOTA = "content.quota.";
protected static final String DEFAULT_DROPBOX_QUOTA = "content.dropbox.quota.";
/**
* This is the name of the sakai.properties property for the VIRUS_SCAN_PERIOD,
* this is how long (in seconds) the virus scan service will wait between checking to see if there
* is new content that need to be scanned, default=3600
*/
public static final String VIRUS_SCAN_CHECK_PERIOD_PROPERTY = "virus.scan.check.period";
/**
* This is the name of the sakai.properties property for the VIRUS_SCAN_DELAY,
* this is how long (in seconds) the virus scan service will wait after starting up
* before it does the first check for scanning, default=300
*/
public static final String VIRUS_SCAN_START_DELAY_PROPERTY = "virus.scan.start.delay";
/** The initial portion of a relative access point URL. */
protected String m_relativeAccessPoint = null;
/** A Storage object for persistent storage. */
protected Storage m_storage = null;
/** A Cache for this service - ContentResource and ContentCollection keyed by reference. */
protected Cache m_cache = null;
/**
* The quota for content resource body bytes (in Kbytes) for any hierarchy in the /user/ or /group/ areas, or 0 if quotas are not enforced.
*/
protected long m_siteQuota = 0;
/**
* The quota for content dropbox body bytes (in Kbytes), or 0 if quotas are not enforced.
*/
protected long m_dropBoxQuota = 0;
private boolean m_useSmartSort = true;
private boolean m_useMimeMagic = true;
List <String> m_ignoreExtensions = null;
List <String> m_ignoreMimeTypes = null;
private static final Detector DETECTOR = new DefaultDetector(MimeTypes.getDefaultMimeTypes());
// This is the date format for Last-Modified header
public static final String RFC1123_DATE = "EEE, dd MMM yyyy HH:mm:ss zzz";
public static final Locale LOCALE_US = Locale.US;
static
{
ROOT_COLLECTIONS.add(COLLECTION_SITE);
ROOT_COLLECTIONS.add(COLLECTION_USER);
ROOT_COLLECTIONS.add(COLLECTION_DROPBOX);
ROOT_COLLECTIONS.add(COLLECTION_PUBLIC);
ROOT_COLLECTIONS.add(COLLECTION_PRIVATE);
ROOT_COLLECTIONS.add(ATTACHMENTS_COLLECTION);
ROOT_COLLECTIONS.add(COLLECTION_MELETE_DOCS);
}
/** Optional path to external file system file store for body binary. */
protected String m_bodyPath = null;
protected String m_bodyPathDeleted = null;
/** Optional set of folders just within the m_bodyPath to distribute files among. */
protected String[] m_bodyVolumes = null;
/**********************************************************************************************************************************************************************************************************************************************************
* Constructors, Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Dependency: MemoryService. */
protected MemoryService m_memoryService = null;
/**
* Use a timer for repeating actions
*/
private Timer virusScanTimer = new Timer(true);
/** How long to wait between virus scan checks (seconds) */
private int VIRUS_SCAN_PERIOD = 300;
/** How long to wait between virus scan checks (seconds) */
public void setVIRUS_SCAN_PERIOD(int scan_period) {
VIRUS_SCAN_PERIOD = scan_period;
}
/** How long to wait before the first virus scan check (seconds) */
private int VIRUS_SCAN_DELAY = 300;
/** How long to wait before the first virus scan check (seconds) */
public void setVIRUS_SCAN_DELAY(int virus_scan_delay) {
VIRUS_SCAN_DELAY = virus_scan_delay;
}
private List<String> virusScanQueue = new Vector();
private final static SecurityAdvisor ALLOW_ADVISOR;
static {
ALLOW_ADVISOR = new SecurityAdvisor(){
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
return SecurityAdvice.ALLOWED;
}
};
}
/**
* Dependency: MemoryService.
*
* @param service
* The MemoryService.
*/
public void setMemoryService(MemoryService service)
{
m_memoryService = service;
}
private ToolManager toolManager;
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
/** Dependency: AliasService. */
protected AliasService m_aliasService = null;
/**
* Dependency: AliasService.
*
* @param service
* The AliasService.
*/
public void setAliasService(AliasService service)
{
m_aliasService = service;
}
/** Dependency: SiteService. */
protected SiteService m_siteService = null;
/**
* Dependency: SiteService.
*
* @param service
* The SiteService.
*/
public void setSiteService(SiteService service)
{
m_siteService = service;
}
protected LinkMigrationHelper linkMigrationHelper;
public void setLinkMigrationHelper(LinkMigrationHelper linkMigrationHelper) {
this.linkMigrationHelper = linkMigrationHelper;
}
/** Dependency: NotificationService. */
protected NotificationService m_notificationService = null;
/**
* Dependency: NotificationService.
*
* @param service
* The NotificationService.
*/
public void setNotificationService(NotificationService service)
{
m_notificationService = service;
}
/** Dependency: ServerConfigurationService. */
protected ServerConfigurationService m_serverConfigurationService = null;
/**
* Dependency: ServerConfigurationService.
*
* @param service
* The ServerConfigurationService.
*/
public void setServerConfigurationService(ServerConfigurationService service)
{
m_serverConfigurationService = service;
}
private IdManager idManager;
public void setIdManager(IdManager idManager) {
this.idManager = idManager;
}
private FunctionManager functionManager;
public void setFunctionManager(FunctionManager functionManager) {
this.functionManager = functionManager;
}
private ThreadLocalManager threadLocalManager;
public void setThreadLocalManager(ThreadLocalManager threadLocalManager) {
this.threadLocalManager = threadLocalManager;
}
/** Dependency: EntityManager. */
protected EntityManager m_entityManager = null;
/**
* Dependency: EntityManager.
*
* @param service
* The EntityManager.
*/
public void setEntityManager(EntityManager service)
{
m_entityManager = service;
}
protected ContentTypeImageService contentTypeImageService;
public void setContentTypeImageService(ContentTypeImageService contentTypeImageService) {
this.contentTypeImageService = contentTypeImageService;
}
/** Dependency: AuthzGroupService. */
protected AuthzGroupService m_authzGroupService = null;
/**
* Dependency: AuthzGroupService.
*
* @param service
* The AuthzGroupService.
*/
public void setAuthzGroupService(AuthzGroupService service)
{
m_authzGroupService = service;
}
private SessionManager sessionManager;
public void setSessionManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
/** Dependency: SecurityService. */
protected SecurityService m_securityService = null;
/**
* Dependency: SecurityService.
*
* @param service
* The SecurityService.
*/
public void setSecurityService(SecurityService service)
{
m_securityService = service;
}
/** Dependency: CollectionAccessFormatter. */
protected CollectionAccessFormatter m_collectionAccessFormatter = null;
/**
* Dependency: CollectionAccessFormatter.
*
* @param service
* The CollectionAccessFormatter.
*/
public void setCollectionAccessFormatter(CollectionAccessFormatter service)
{
m_collectionAccessFormatter = service;
}
/** Dependency: ContentFilterService */
protected ContentFilterService m_contentFilterService;
/**
* Dependency: ContentFilterService.
*
* @param service
* The ContentFilterService.
*/
public void setContentFilterService(ContentFilterService service)
{
m_contentFilterService = service;
}
/**
* Set the site quota.
*
* @param quota
* The site quota (as a string).
*/
public void setSiteQuota(Long quota)
{
if (quota != null)
{
m_siteQuota = quota;
}
}
/**
* Set the dropbox quota.
*
* @param quota
* The dropbox quota (as a string).
*/
public void setDropBoxQuota(Long quota)
{
if (quota != null)
{
m_dropBoxQuota = quota;
}
}
private EventTrackingService eventTrackingService;
public void setEventTrackingService(EventTrackingService eventTrackingService) {
this.eventTrackingService = eventTrackingService;
}
private VirusScanner virusScanner;
public void setVirusScanner(VirusScanner virusScanner) {
this.virusScanner = virusScanner;
}
private TimeService timeService;
public void setTimeService(TimeService timeService) {
this.timeService = timeService;
}
private UserDirectoryService userDirectoryService;
public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
this.userDirectoryService = userDirectoryService;
}
/** Configuration: cache, or not. */
protected boolean m_caching = false;
/**
* Configuration: cache, or not.
*
* @param value
* True/false
*/
public void setCaching(String value)
{
try
{
m_caching = Boolean.valueOf(value).booleanValue();
}
catch (Exception t)
{
}
}
/** Configuration: Do we protect attachments in sites with the site AuthZGroup. */
protected boolean m_siteAttachments = true; // Default to true for Sakai 2.5 and later
/**
* Configuration: Do we protect attachments in sites with the site AuthZGroup.
*
* @param value
* true - We protect the site scoped attachments with the site's AZG
* false - We use the /content/attachment hierarchy to protect attachments
*
* Default is true.
*/
public void setSiteAttachments(String value)
{
try
{
m_siteAttachments = Boolean.valueOf(value).booleanValue();
}
catch (Exception t)
{
}
}
/**
* Configuration: set the external file system path for body storage If set, the resource binary database table will not be used.
*
* @param value
* The complete path to the root of the external file system storage area for resource body bytes.
*/
public void setBodyPath(String value)
{
m_bodyPath = value;
}
/**
* Configuration: set the external file system path for body storage for deleted files.
*
* @param value
* The complete path to the root of the external file system storage area for resource body bytes of deleted resources.
*/
public void setBodyPathDeleted(String value)
{
m_bodyPathDeleted = value;
}
/**
* Configuration: set the external file system volume folders (folder just within the bodyPath) as a comma separated list of folder names.
* If set, files will be distributed over these folders. A single semicolon (';') can be added to the end of the list of values to indicate
* that leading and trailing whitespace should be preserved from each volume name. Without the semicolon, leading and trailing whitespace
* will be trimmed from each name in the list.
*
* @param value
* The comma separated list of folder names within body path to distribute files among.
*/
public void setBodyVolumes(String value)
{
boolean trimWhitespace = true;
try
{
List<String> list = new ArrayList<String>();
if(value != null && value.trim().endsWith(";"))
{
trimWhitespace = false;
value = value.substring(0, value.lastIndexOf(";"));
}
if(value != null && ! value.trim().equals(""))
{
String[] bodyVolumes = StringUtil.split(value, ",");
for(int i = 0; i < bodyVolumes.length; i++)
{
String name = bodyVolumes[i];
if(name == null || name.trim().equals(""))
{
continue;
}
list.add(trimWhitespace ? name.trim() : name);
}
}
this.m_bodyVolumes = new String[list.size()];
for(int i = 0; i < list.size(); i++)
{
this.m_bodyVolumes[i] = list.get(i);
}
}
catch (Exception t)
{
}
}
/** Configuration: short refs */
protected boolean m_shortRefs = true;
/**
* Configuration: set the short refs
*
* @param value
* The short refs value.
*/
public void setShortRefs(boolean value)
{
m_shortRefs = value;
}
/**
* {@inheritDoc}
*/
public boolean isShortRefs()
{
return m_shortRefs;
}
/** Configuration: allow use of alias for site id in references. */
protected boolean m_siteAlias = true;
/**
* Configuration: set the alias for site
*
* @param value
* The alias for site value.
*/
public void setSiteAlias(String value)
{
try
{
m_siteAlias = Boolean.valueOf(value).booleanValue();
}
catch (Exception t)
{
}
}
/** Dependency: allowGroupResources setting */
protected boolean m_allowGroupResources = true;
/**
* Dependency: allowGroupResources
*
* @param allowGroupResources
* the setting
*/
public void setAllowGroupResources(boolean allowGroupResources)
{
m_allowGroupResources = allowGroupResources;
}
/**
* Get
*
* @return allowGroupResources
*/
public boolean getAllowGroupResources()
{
return m_allowGroupResources;
}
/** flag indicating whether entities can be hidden (scheduled or otherwise) */
protected boolean m_availabilityChecksEnabled = true;
/**
* Configuration: set a flag indicating whether entities can be hidden (scheduled or otherwise)
*
* @param value
* The value indicating whether entities can be hidden.
*/
public void setAvailabilityChecksEnabled(boolean value)
{
m_availabilityChecksEnabled = value;
}
/**
* Access flag indicating whether entities can be hidden (scheduled or otherwise).
* @return true if the availability features are enabled, false otherwise.
*/
public boolean isAvailabilityEnabled()
{
return m_availabilityChecksEnabled;
}
/** flag indicating whether custom sort order based on "priority" is enabled */
protected boolean m_prioritySortEnabled = true;
/**
* Configuration: set a flag indicating whether custom sort order based on "priority" is enabled
*
* @param value
* The value indicating whether custom sort order is enabled.
*/
public void setPrioritySortEnabled(boolean value)
{
m_prioritySortEnabled = value;
}
/**
* Configuration: set a flag indicating whether custom sort order based on "priority" is enabled
*
* @param value
* The value indicating whether custom sort order is enabled.
*/
public boolean getPrioritySortEnabled()
{
return m_prioritySortEnabled;
}
/**
* Access flag indicating whether sorting by "priority" is enabled.
* @return true if the custom sort by priority is enabled, false otherwise.
*/
public boolean isSortByPriorityEnabled()
{
return m_prioritySortEnabled;
}
/**
* Dependency: the ResourceTypeRegistry
*/
protected ResourceTypeRegistry m_resourceTypeRegistry;
/**
* Dependency: inject the ResourceTypeRegistry
* @param registry
*/
public void setResourceTypeRegistry(ResourceTypeRegistry registry)
{
m_resourceTypeRegistry = registry;
}
/**
* @return the ResourceTypeRegistry
*/
public ResourceTypeRegistry getResourceTypeRegistry()
{
return m_resourceTypeRegistry;
}
protected boolean useResourceTypeRegistry = true;
public EntitySerializer collectionSerializer;
public EntitySerializer resourceSerializer;
public void setUseResourceTypeRegistry(boolean useRegistry)
{
useResourceTypeRegistry = useRegistry;
}
public boolean usingResourceTypeRegistry()
{
return useResourceTypeRegistry;
}
protected boolean filesizeColumnExists = false;
protected boolean filesizeColumnReady = false;
public boolean readyToUseFilesizeColumn()
{
return filesizeColumnExists && filesizeColumnReady;
}
public boolean m_useContextQueryForCollectionSize = false;
/**
* @return the useContextQueryForCollectionSize
*/
public boolean isUseContextQueryForCollectionSize()
{
return m_useContextQueryForCollectionSize;
}
/**
* @param useContextQueryForCollectionSize the useContextQueryForCollectionSize to set
*/
public void setUseContextQueryForCollectionSize(boolean useContextQueryForCollectionSize)
{
this.m_useContextQueryForCollectionSize = useContextQueryForCollectionSize;
}
protected boolean convertToContextQueryForCollectionSize;
/**
* @param convertToContextQueryForCollectionSize the convertToContextQueryForCollectionSize to set
*/
public void setConvertToContextQueryForCollectionSize(boolean convertToContextQueryForCollectionSize)
{
this.convertToContextQueryForCollectionSize = convertToContextQueryForCollectionSize;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
try
{
// Get resource bundle
String resourceClass = m_serverConfigurationService.getString(RESOURCECLASS, DEFAULT_RESOURCECLASS);
String resourceBundle = m_serverConfigurationService.getString(RESOURCEBUNDLE, DEFAULT_RESOURCEBUNDLE);
rb = new Resource().getLoader(resourceClass, resourceBundle);
m_relativeAccessPoint = REFERENCE_ROOT;
// construct a storage helper and read
m_storage = newStorage();
m_storage.open();
M_log.info("Loaded Storage as "+m_storage+" for "+this);
// make the cache
if (m_caching)
{
m_cache = m_memoryService
.newCache(
"org.sakaiproject.content.api.ContentHostingService.cache",
this, getAccessPoint(true));
}
// register a transient notification for resources
NotificationEdit edit = m_notificationService.addTransientNotification();
// set functions
edit.setFunction(EVENT_RESOURCE_AVAILABLE);
edit.addFunction(EVENT_RESOURCE_WRITE);
// set the filter to any site related resource
edit.setResourceFilter(getAccessPoint(true) + Entity.SEPARATOR + "group" + Entity.SEPARATOR);
// %%% is this the best we can do? -ggolden
// set the action
SiteEmailNotificationContent siteEmailNotificationContent = new SiteEmailNotificationContent(m_securityService,
m_serverConfigurationService, this, m_entityManager, m_siteService);
edit.setAction(siteEmailNotificationContent);
NotificationEdit dbNoti = m_notificationService.addTransientNotification();
// set functions
dbNoti.setFunction(EVENT_RESOURCE_AVAILABLE);
dbNoti.addFunction(EVENT_RESOURCE_WRITE);
// set the filter to any site related resource
dbNoti.setResourceFilter(getAccessPoint(true) + Entity.SEPARATOR + "group-user" + Entity.SEPARATOR);
// %%% is this the best we can do? -ggolden
// set the action
DropboxNotification dropboxNotification = new DropboxNotification(m_securityService, this, m_entityManager, m_siteService,
userDirectoryService, m_serverConfigurationService);
dbNoti.setAction(dropboxNotification);
StringBuilder buf = new StringBuilder();
if (m_bodyVolumes != null)
{
for (int i = 0; i < m_bodyVolumes.length; i++)
{
buf.append(m_bodyVolumes[i]);
buf.append(", ");
}
}
// The entity producer is registerd by the thrird party manager
m_entityManager.registerEntityProducer(this,
ContentHostingService.REFERENCE_ROOT);
// register functions
functionManager.registerFunction(AUTH_RESOURCE_ADD, true);
functionManager.registerFunction(AUTH_RESOURCE_READ, true);
functionManager.registerFunction(AUTH_RESOURCE_WRITE_ANY, true);
functionManager.registerFunction(AUTH_RESOURCE_WRITE_OWN, true);
functionManager.registerFunction(AUTH_RESOURCE_REMOVE_ANY, true);
functionManager.registerFunction(AUTH_RESOURCE_REMOVE_OWN, true);
functionManager.registerFunction(AUTH_RESOURCE_ALL_GROUPS, true);
functionManager.registerFunction(AUTH_RESOURCE_HIDDEN, true);
functionManager.registerFunction(AUTH_DROPBOX_OWN, false);
functionManager.registerFunction(AUTH_DROPBOX_GROUPS, false);
functionManager.registerFunction(AUTH_DROPBOX_MAINTAIN, false);
// quotas
m_siteQuota = Long.parseLong(m_serverConfigurationService.getString("content.quota", Long.toString(m_siteQuota)));
m_dropBoxQuota = Long.parseLong(m_serverConfigurationService.getString("content.dropbox.quota", Long.toString(m_dropBoxQuota)));
M_log.info("init(): site quota: " + m_siteQuota + ", dropbox quota: " + m_dropBoxQuota + ", body path: " + m_bodyPath + " volumes: "+ buf.toString());
int virusScanPeriod = m_serverConfigurationService.getInt(VIRUS_SCAN_CHECK_PERIOD_PROPERTY, VIRUS_SCAN_PERIOD);
int virusScanDelay = m_serverConfigurationService.getInt(VIRUS_SCAN_START_DELAY_PROPERTY, VIRUS_SCAN_DELAY);
virusScanDelay += new Random().nextInt(60); // add some random delay to get the servers out of sync
virusScanTimer.schedule(new VirusTimerTask(), (virusScanDelay * 1000), (virusScanPeriod * 1000) );
}
catch (Exception t)
{
M_log.error("init(): ", t);
}
this.m_useSmartSort = m_serverConfigurationService.getBoolean("content.smartSort", true);
} // init
/**
* Returns to uninitialized state.
*/
public void destroy()
{
if ( m_storage != null ) {
m_storage.close();
}
m_storage = null;
if ((m_caching) && (m_cache != null))
{
m_cache.close();
}
M_log.info("destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* StorageUser implementation - for collections
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Storage user for collections - in the resource side, not container
*/
protected class CollectionStorageUser implements SingleStorageUser, SAXEntityReader, EntityReaderHandler, EntityReader
{
private Map<String,Object> m_services;
private EntityReaderHandler entityReaderAdapter;
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseCollectionEdit(id);
}
public Entity newResource(Entity container, Element element)
{
return new BaseCollectionEdit(element);
}
public Entity newResource(Entity container, Entity other)
{
return new BaseCollectionEdit((ContentCollection) other);
}
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseCollectionEdit rv = new BaseCollectionEdit(id);
rv.activate();
return rv;
}
public Edit newResourceEdit(Entity container, Element element)
{
BaseCollectionEdit rv = new BaseCollectionEdit(element);
rv.activate();
return rv;
}
public Edit newResourceEdit(Entity container, Entity other)
{
BaseCollectionEdit rv = new BaseCollectionEdit((ContentCollection) other);
rv.activate();
return rv;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object[] rv = new Object[1];
rv[0] = StringUtil.referencePath(((ContentCollection) r).getId());
return rv;
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("collection".equals(qName))
{
BaseCollectionEdit bre = new BaseCollectionEdit();
entity = bre;
setContentHandler(bre.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn("Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.EntityReader#accept(java.lang.String)
*/
public boolean accept(byte[] blob)
{
return collectionSerializer.accept(blob);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.EntityReader#parseContainer(java.lang.String)
*/
public Entity parse(String xml, byte[] blob) throws EntityParseException
{
BaseCollectionEdit bce = new BaseCollectionEdit();
collectionSerializer.parse(bce,blob);
return bce;
}
/* (non-Javadoc)
* @see org.sakaiproject.entity.api.serialize.EntityReaderHandler#parse(org.sakaiproject.entity.api.Entity, java.lang.String, byte[])
*/
public Entity parse(Entity container, String xml, byte[] blob) throws EntityParseException
{
BaseCollectionEdit bce = new BaseCollectionEdit();
collectionSerializer.parse(bce,blob);
return bce;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.EntityReader#toString(org.sakaiproject.entity.api.Entity)
*/
public byte[] serialize(Entity entry) throws EntityParseException
{
if ( entry instanceof SerializableEntity ) {
return collectionSerializer.serialize((SerializableEntity)entry);
}
throw new EntityParseException("Unable to serialze entity to native format, entity is not serializable");
}
/* (non-Javadoc)
* @see org.sakaiproject.entity.api.EntityReader#getHandler()
*/
public EntityReaderHandler getHandler()
{
return entityReaderAdapter;
}
/**
* @return the entityReaderAdapter
*/
public EntityReaderHandler getEntityReaderAdapter()
{
return entityReaderAdapter;
}
/**
* @param entityReaderAdapter the entityReaderAdapter to set
*/
public void setEntityReaderAdapter(EntityReaderHandler entityReaderAdapter)
{
this.entityReaderAdapter = entityReaderAdapter;
}
} // class CollectionStorageUser
/**
* Storage user for resources - in the resource side, not container
*/
protected class ResourceStorageUser implements SingleStorageUser, SAXEntityReader, EntityReaderHandler, EntityReader
{
private Map<String, Object> m_services;
private EntityReaderHandler entityReaderAdapter;
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseResourceEdit(id);
}
public Entity newResource(Entity container, Element element)
{
return new BaseResourceEdit(element);
}
public Entity newResource(Entity container, Entity other)
{
return new BaseResourceEdit((ContentResource) other);
}
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseResourceEdit rv = new BaseResourceEdit(id);
rv.activate();
return rv;
}
public Edit newResourceEdit(Entity container, Element element)
{
BaseResourceEdit rv = new BaseResourceEdit(element);
rv.activate();
return rv;
}
public Edit newResourceEdit(Entity container, Entity other)
{
BaseResourceEdit rv = new BaseResourceEdit((ContentResource) other);
rv.activate();
return rv;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
if(filesizeColumnExists)
{
// include the file path field if we are doing body in the file system
if (m_bodyPath != null)
{
Object[] rv = new Object[5];
rv[0] = StringUtil.referencePath(((ContentResource) r).getId());
rv[1] = ((BasicGroupAwareEdit) r).getContext();
rv[2] = Long.valueOf(((ContentResource) r).getContentLength());
rv[3] = ((BasicGroupAwareEdit) r).getResourceType();
rv[4] = StringUtil.trimToZero(((BaseResourceEdit) r).m_filePath);
return rv;
}
// otherwise don't include the file path field
else
{
Object[] rv = new Object[4];
rv[0] = StringUtil.referencePath(((ContentResource) r).getId());
rv[1] = ((BasicGroupAwareEdit) r).getContext();
rv[2] = Long.valueOf(((ContentResource) r).getContentLength());
rv[3] = ((BasicGroupAwareEdit) r).getResourceType();
return rv;
}
}
else
{
// include the file path field if we are doing body in the file system
if (m_bodyPath != null)
{
Object[] rv = new Object[2];
rv[0] = StringUtil.referencePath(((ContentResource) r).getId());
rv[1] = StringUtil.trimToZero(((BaseResourceEdit) r).m_filePath);
return rv;
}
// otherwise don't include the file path field
else
{
Object[] rv = new Object[1];
rv[0] = StringUtil.referencePath(((ContentResource) r).getId());
return rv;
}
}
}
/***********************************************************************
* SAXEntityReader
*/
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getDefaultHandler(java.util.Map)
*/
public DefaultEntityHandler getDefaultHandler(final Map<String, Object> services)
{
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if (entity == null)
{
if ("resource".equals(qName))
{
BaseResourceEdit bre = new BaseResourceEdit();
entity = bre;
setContentHandler(bre.getContentHandler(services), uri,
localName, qName, attributes);
}
else
{
M_log.warn("Unexpected Element in XML [" + qName + "]");
}
}
}
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.SAXEntityReader#getServices()
*/
public Map<String, Object> getServices()
{
if (m_services == null)
{
m_services = new HashMap<String, Object>();
}
return m_services;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.EntityReader#accept(java.lang.String)
*/
public boolean accept(byte[] blob)
{
return resourceSerializer.accept(blob);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.EntityReader#parseContainer(java.lang.String)
*/
public Entity parse(String xml, byte[] blob) throws EntityParseException
{
BaseResourceEdit bre = new BaseResourceEdit();
resourceSerializer.parse(bre,blob);
ResourceProperties props = bre.getProperties();
if(props != null) {
String oldDisplayName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
bre.setOldDisplayName(oldDisplayName);
}
return bre;
}
/* (non-Javadoc)
* @see org.sakaiproject.entity.api.serialize.EntityReaderHandler#parse(org.sakaiproject.entity.api.Entity, java.lang.String, byte[])
*/
public Entity parse(Entity container, String xml, byte[] blob) throws EntityParseException
{
BaseResourceEdit bre = new BaseResourceEdit();
resourceSerializer.parse(bre,blob);
ResourceProperties props = bre.getProperties();
if(props != null) {
String oldDisplayName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
bre.setOldDisplayName(oldDisplayName);
}
return bre;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.EntityReader#toString(org.sakaiproject.entity.api.Entity)
*/
public byte[] serialize(Entity entry) throws EntityParseException
{
if ( entry instanceof SerializableEntity ) {
return resourceSerializer.serialize((SerializableEntity) entry);
}
throw new EntityParseException("Unable to parse entity, entity does not implement SerializableEntity ");
}
/* (non-Javadoc)
* @see org.sakaiproject.entity.api.EntityReader#getHandler()
*/
public EntityReaderHandler getHandler()
{
return entityReaderAdapter;
}
/**
* @return the entityReaderAdapter
*/
public EntityReaderHandler getEntityReaderAdapter()
{
return entityReaderAdapter;
}
/**
* @param entityReaderAdapter the entityReaderAdapter to set
*/
public void setEntityReaderAdapter(EntityReaderHandler entityReaderAdapter)
{
this.entityReaderAdapter = entityReaderAdapter;
}
} // class ResourceStorageUser
/**********************************************************************************************************************************************************************************************************************************************************
* ContentHostingService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct a Storage object.
*
* @return The new storage object.
*/
protected abstract Storage newStorage();
/**
* Determine whether the entityId parameter identifies a collection (as opposed to a resource).
* This method does not necessarily verify that a ContentEntity with this id exists.
* It merely determines whether the id could identify a collection.
* @param entityId
* @return true if the entityId could identify a collection, false otherwise.
*/
public boolean isCollection(String entityId)
{
return (entityId != null && entityId.endsWith(Entity.SEPARATOR));
}
/**
* @param id
* id of the resource to set the UUID for
* @param uuid
* the new UUID of the resource
*/
protected abstract void setUuidInternal(String id, String uuid);
/**
* Access the partial URL that forms the root of resource URLs.
*
* @param relative
* if true, form within the access path only (i.e. starting with /content)
* @return the partial URL that forms the root of resource URLs.
*/
protected String getAccessPoint(boolean relative)
{
return (relative ? "" : m_serverConfigurationService.getAccessUrl()) + m_relativeAccessPoint;
} // getAccessPoint
/**
* If the id is for a resource in a dropbox, change the function to a dropbox check, which is to check for write.<br />
* You have full or no access to a dropbox.
*
* @param lock
* The lock we are checking.
* @param id
* The resource id.
* @return The lock to check.
*/
protected String convertLockIfDropbox(String lock, String id)
{
//the id could be null
if (id == null) {
return null;
}
// if this resource is a dropbox, you need dropbox maintain permission
// Changed in SAK-11647 to enable group-aware dropboxes
if (id.startsWith(COLLECTION_DROPBOX))
{
// only for /group-user/SITEID/USERID/ refs.
String[] parts = StringUtil.split(id, "/");
if (parts.length >= 3)
{
String ref = null;
if (id != null)
{
ref = getReference(id);
}
//Before SAK-11647 any dropbox id asked for dropbox.maintain permission.
//Now we must support groups permission, so we ask for this permission too.
//Groups permission gives full access to dropboxes of users in current user's groups.
//A different logic can be achieved here depending of lock parameter received.
if (m_securityService.unlock(AUTH_DROPBOX_MAINTAIN, ref))
return AUTH_DROPBOX_MAINTAIN;
else if (m_securityService.unlock(AUTH_DROPBOX_GROUPS, ref))
return AUTH_DROPBOX_GROUPS;
}
}
return lock;
}
/**
* Check whether an id would identify an entity in a dropbox. Does not determine existence of the entity, just whether its id indicates it is a dropbox or contained within a dropbox.
* @return true if the entity is a dropbox or in a dropbox, false otherwise.
*/
public boolean isInDropbox(String entityId)
{
return entityId.startsWith("/group-user");
}
public boolean isSiteLevelDropbox(String id)
{
boolean isSiteLevelDropbox = (id != null) && isInDropbox(id);
if(isSiteLevelDropbox)
{
String[] parts = id.split(Entity.SEPARATOR);
isSiteLevelDropbox = parts.length == 3;
}
return isSiteLevelDropbox;
}
public boolean isIndividualDropbox(String id)
{
boolean isIndividualDropbox = (id != null) && isInDropbox(id);
if(isIndividualDropbox)
{
String[] parts = id.split(Entity.SEPARATOR);
isIndividualDropbox = parts.length == 4;
}
return isIndividualDropbox;
}
public boolean isInsideIndividualDropbox(String id)
{
boolean isIndividualDropbox = (id != null) && isInDropbox(id);
if(isIndividualDropbox)
{
String[] parts = id.split(Entity.SEPARATOR);
isIndividualDropbox = parts.length > 4;
}
return isIndividualDropbox;
}
public String getSiteLevelDropboxId(String id)
{
String dropboxId = null;
if(isSiteLevelDropbox(id))
{
String[] parts = id.split(Entity.SEPARATOR);
dropboxId = Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR;
}
return dropboxId;
}
/**
* Access the name of the individual dropbox that contains a particular entity, or null if the entity is not inside an individual dropbox.
* @param entityId The id for an entity
* @return
*/
public String getIndividualDropboxId(String entityId)
{
String dropboxId = null;
if(entityId != null && isInDropbox(entityId))
{
String[] parts = entityId.split(Entity.SEPARATOR);
if(parts.length >= 4)
{
dropboxId = Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR + parts[3] + Entity.SEPARATOR;
}
}
return dropboxId;
}
/**
* Check whether the resource is hidden.
* @param id
* @return
* @throws IdUnusedException
*/
protected boolean availabilityCheck(String id) throws IdUnusedException
{
// item is available if avaialability checks are <b>NOT</b> enabled OR if it's in /attachment
boolean available = (! m_availabilityChecksEnabled) || isAttachmentResource(id);
GroupAwareEntity entity = null;
//boolean isCollection = id.endsWith(Entity.SEPARATOR);
while(!available && entity == null && id != null && ! id.trim().equals(""))
{
if(ROOT_COLLECTIONS.contains(id))
{
available = true;
}
else
{
try
{
if (isCollection(id))
{
entity = findCollection(id);
}
else
{
entity = findResource(id);
}
}
catch (TypeException ignore)
{
if(isCollection(id))
{
M_log.warn("trying to get collection, found resource: " + id);
}
else
{
M_log.warn("trying to get resource, found collection: " + id);
}
}
if (entity == null)
{
id = isolateContainingId(id);
// isCollection = true;
}
}
}
if(!available && entity != null)
{
String creator = entity.getProperties().getProperty(ResourceProperties.PROP_CREATOR);
String userId = sessionManager.getCurrentSessionUserId();
// if we are in a roleswapped state, we want to ignore the creator check since it would not necessarily reflect an alternate role
// FIXME - unsafe check (vulnerable to collision of siteids that are the same as path elements in a resource)
String[] refs = StringUtil.split(id, Entity.SEPARATOR);
String roleswap = null;
for (int i = 0; i < refs.length; i++)
{
roleswap = m_securityService.getUserEffectiveRole("/site/" + refs[i]);
if (roleswap!=null)
break;
}
if (roleswap==null)
{
// available if user is creator
available = ( creator != null && userId != null && creator.equals(userId) )
|| ( creator == null && userId == null );
}
if(! available)
{
// available if user has permission to view hidden entities
String lock = AUTH_RESOURCE_HIDDEN;
available = m_securityService.unlock(lock, entity.getReference());
if(! available)
{
// available if not hidden or in a hidden collection
available = entity.isAvailable();
}
}
}
return available;
}
/**
* Determine whether an entity is available to this user at this time, taking into account whether the item is hidden and the user's
* status with respect to viewing hidden entities in this context.
* @param entityId
* @return true if the item is not hidden or it's hidden but the user has permissions to view hidden items in this context (site? folder? group?),
* and false otherwise.
*/
public boolean isAvailable(String entityId)
{
boolean available = true;
try
{
available = availabilityCheck(entityId);
}
catch(IdUnusedException e)
{
available = false;
}
return available;
}
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param id
* The resource id string, or null if no resource is involved.
* @return true if permitted, false if not.
*/
protected boolean unlockCheck(String lock, String id)
{
boolean isAllowed = m_securityService.isSuperUser();
if(! isAllowed)
{
//SAK-11647 - Changes in this function.
lock = convertLockIfDropbox(lock, id);
// make a reference from the resource id, if specified
String ref = null;
if (id != null)
{
ref = getReference(id);
}
isAllowed = ref != null && m_securityService.unlock(lock, ref);
if(isAllowed && lock != null && (lock.startsWith("content.") || lock.startsWith("dropbox.")) && m_availabilityChecksEnabled)
{
try
{
isAllowed = availabilityCheck(id);
}
catch (IdUnusedException e)
{
// ignore because we would have caught this earlier.
M_log.debug("BaseContentService.unlockCheck(" + lock + "," + id + ") IdUnusedException " + e);
}
}
}
return isAllowed;
} // unlockCheck
/**
* Throws a PermissionException if the resource with the given Id is explicitly locked
*
* @param id
* @throws PermissionException
*/
protected void checkExplicitLock(String id) throws PermissionException
{
String uuid = this.getUuid(id);
if (uuid != null && this.isLocked(uuid))
{
// TODO: WebDAV locks need to be more sophisticated than this
throw new PermissionException(sessionManager.getCurrentSessionUserId(), "remove", id);
}
}
/**
* Check security permission.
*
* @param lock
* The lock id string.
* @param id
* The resource id string, or null if no resource is involved.
* @exception PermissionException
* Thrown if the user does not have access
*/
protected void unlock(String lock, String id) throws PermissionException
{
if(m_securityService.isSuperUser())
{
return;
}
//SAK-11647 - Changes in this function.
lock = convertLockIfDropbox(lock, id);
// make a reference from the resource id, if specified
String ref = null;
if (id != null)
{
ref = getReference(id);
}
if (!m_securityService.unlock(lock, ref))
{
throw new PermissionException(sessionManager.getCurrentSessionUserId(), lock, ref);
}
boolean available = false;
try
{
available = availabilityCheck(id);
}
catch (IdUnusedException e)
{
// ignore. this was checked earlier in the call
}
if(! available)
{
throw new PermissionException(sessionManager.getCurrentSessionUserId(), lock, ref);
}
} // unlock
/**
* Check security permission for all contained collections of the given collection (if any) (not the collection itself)
*
* @param lock
* The lock id string.
* @param resource
* The resource id string, or null if no resource is involved.
* @exception PermissionException
* Thrown if the user does not have access
*/
/*
* protected void unlockContained(String lock, ContentCollection collection) throws PermissionException { if (SecurityService == null) return; Iterator it = collection.getMemberResources().iterator(); while (it.hasNext()) { Object mbr = it.next(); if
* (mbr == null) continue; // for a contained collection, check recursively if (mbr instanceof ContentCollection) { unlockContained(lock, (ContentCollection) mbr); } // for resources, check else if (mbr instanceof ContentResource) { unlock(lock,
* ((ContentResource) mbr).getId()); } } } // unlockContained
*/
/**
* Create the live properties for a collection.
*
* @param c
* The collection.
*/
protected void addLiveCollectionProperties(ContentCollectionEdit c)
{
ResourcePropertiesEdit p = c.getPropertiesEdit();
String current = sessionManager.getCurrentSessionUserId();
p.addProperty(ResourceProperties.PROP_CREATOR, current);
p.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
String now = timeService.newTime().toString();
p.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
p.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
p.addProperty(ResourceProperties.PROP_IS_COLLECTION, "true");
} // addLiveCollectionProperties
/**
* Create the live properties for a collection.
*
* @param c
* The collection.
*/
protected void addLiveUpdateCollectionProperties(ContentCollectionEdit c)
{
ResourcePropertiesEdit p = c.getPropertiesEdit();
String current = sessionManager.getCurrentSessionUserId();
p.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
String now = timeService.newTime().toString();
p.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
} // addLiveUpdateCollectionProperties
/**
* Create the live properties for a resource.
*
* @param r
* The resource.
*/
protected void addLiveResourceProperties(ContentResourceEdit r)
{
ResourcePropertiesEdit p = r.getPropertiesEdit();
String current = sessionManager.getCurrentSessionUserId();
p.addProperty(ResourceProperties.PROP_CREATOR, current);
p.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
String now = timeService.newTime().toString();
p.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
p.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
p.addProperty(ResourceProperties.PROP_CONTENT_LENGTH, Long.toString(r.getContentLength()));
p.addProperty(ResourceProperties.PROP_CONTENT_TYPE, r.getContentType());
p.addProperty(ResourceProperties.PROP_IS_COLLECTION, "false");
} // addLiveResourceProperties
/**
* Update the live properties for a resource when modified (for a resource).
*
* @param r
* The resource.
*/
protected void addLiveUpdateResourceProperties(ContentResourceEdit r)
{
ResourcePropertiesEdit p = r.getPropertiesEdit();
String current = sessionManager.getCurrentSessionUserId();
p.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
String now = timeService.newTime().toString();
p.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
p.addProperty(ResourceProperties.PROP_CONTENT_LENGTH, Long.toString(r.getContentLength()));
p.addProperty(ResourceProperties.PROP_CONTENT_TYPE, r.getContentType());
} // addLiveUpdateResourceProperties
/**
* Make sure that the entire set of properties are present, adding whatever is needed, replacing nothing that's there already.
*
* @param r
* The resource.
*/
protected void assureResourceProperties(ContentResourceEdit r)
{
ResourcePropertiesEdit p = r.getPropertiesEdit();
String current = sessionManager.getCurrentSessionUserId();
String now = timeService.newTime().toString();
if (p.getProperty(ResourceProperties.PROP_CREATOR) == null)
{
p.addProperty(ResourceProperties.PROP_CREATOR, current);
}
if (p.getProperty(ResourceProperties.PROP_CREATION_DATE) == null)
{
p.addProperty(ResourceProperties.PROP_CREATION_DATE, now);
}
if (p.getProperty(ResourceProperties.PROP_MODIFIED_BY) == null)
{
p.addProperty(ResourceProperties.PROP_MODIFIED_BY, current);
}
if (p.getProperty(ResourceProperties.PROP_MODIFIED_DATE) == null)
{
p.addProperty(ResourceProperties.PROP_MODIFIED_DATE, now);
}
// these can just be set
p.addProperty(ResourceProperties.PROP_CONTENT_LENGTH, Long.toString(r.getContentLength()));
p.addProperty(ResourceProperties.PROP_CONTENT_TYPE, r.getContentType());
p.addProperty(ResourceProperties.PROP_IS_COLLECTION, "false");
} // assureResourceProperties
/**
* Add properties for a resource.
*
* @param r
* The resource.
* @param props
* The properties.
*/
protected void addProperties(ResourcePropertiesEdit p, ResourceProperties props)
{
if (props == null) return;
Iterator it = props.getPropertyNames();
while (it.hasNext())
{
String name = (String) it.next();
// skip any live properties
if (!props.isLiveProperty(name))
{
p.addProperty(name, props.getProperty(name));
}
}
} // addProperties
/**********************************************************************************************************************************************************************************************************************************************************
* Collections
*********************************************************************************************************************************************************************************************************************************************************/
/**
* check permissions for addCollection().
*
* @param id
* The id of the new collection.
* @return true if the user is allowed to addCollection(id), false if not.
*/
public boolean allowAddCollection(String id)
{
// collection must also end in the separator (we fix it)
if (!id.endsWith(Entity.SEPARATOR))
{
id = id + Entity.SEPARATOR;
}
// check security
return unlockCheck(AUTH_RESOURCE_ADD, id);
} // allowAddCollection
/**
* Create a new collection with the given resource id.
*
* @param id
* The id of the collection.
* @param properties
* A java Properties object with the properties to add to the new collection.
* @exception IdUsedException
* if the id is already in use.
* @exception IdInvalidException
* if the id is invalid.
* @exception PermissionException
* if the user does not have permission to add a collection, or add a member to a collection.
* @exception InconsistentException
* if the containing collection does not exist.
* @return a new ContentCollection object.
*/
public ContentCollection addCollection(String id, ResourceProperties properties) throws IdUsedException, IdInvalidException,
PermissionException, InconsistentException
{
ContentCollectionEdit edit = addCollection(id);
// add the provided of properties
addProperties(edit.getPropertiesEdit(), properties);
// commit the change
commitCollection(edit);
return edit;
} // addCollection
public ContentCollection addCollection(String id, ResourceProperties properties, Collection groups)
throws IdUsedException, IdInvalidException, PermissionException, InconsistentException
{
ContentCollectionEdit edit = addCollection(id);
// add the provided of properties
addProperties(edit.getPropertiesEdit(), properties);
try
{
if(groups == null || groups.isEmpty())
{
((BasicGroupAwareEdit) edit).clearGroupAccess();
}
else
{
((BasicGroupAwareEdit) edit).setGroupAccess(groups);
}
}
catch(InconsistentException e)
{
// ignore
}
// commit the change
commitCollection(edit);
return edit;
}
public ContentCollection addCollection(String id, ResourceProperties properties, Collection groups, boolean hidden, Time releaseDate, Time retractDate)
throws IdUsedException, IdInvalidException, PermissionException, InconsistentException
{
ContentCollectionEdit edit = addCollection(id);
// add the provided of properties
addProperties(edit.getPropertiesEdit(), properties);
try
{
if(groups == null || groups.isEmpty())
{
((BasicGroupAwareEdit) edit).clearGroupAccess();
}
else
{
((BasicGroupAwareEdit) edit).setGroupAccess(groups);
}
}
catch(InconsistentException e)
{
// ignore
}
edit.setAvailability(hidden, releaseDate, retractDate);
// commit the change
commitCollection(edit);
return edit;
}
/**
* Create a new collection with the given resource id, locked for update. Must commitCollection() to make official, or cancelCollection() when done!
*
* @param id
* The id of the collection.
* @exception IdUsedException
* if the id is already in use.
* @exception IdInvalidException
* if the id is invalid.
* @exception PermissionException
* if the user does not have permission to add a collection, or add a member to a collection.
* @exception InconsistentException
* if the containing collection does not exist.
* @return a new ContentCollection object.
*/
public ContentCollectionEdit addCollection(String id) throws IdUsedException, IdInvalidException, PermissionException,
InconsistentException
{
// check the id's validity (this may throw IdInvalidException)
// use only the "name" portion, separated at the end
String justName = isolateName(id);
Validator.checkResourceId(justName);
// collection must also end in the separator (we fix it)
if (!id.endsWith(Entity.SEPARATOR))
{
id = id + Entity.SEPARATOR;
}
String containerId = isolateContainingId(id);
threadLocalManager.set("members@" + containerId, null);
threadLocalManager.set("getCollections@" + containerId, null);
//threadLocalManager.set("getResources@" + containerId, null);
// check security
unlock(AUTH_RESOURCE_ADD, id);
return addValidPermittedCollection(id);
}
/**
* @param collectionId
* @param name
* @return
* @exception PermissionException
* if the user does not have permission to add a resource to the containing collection.
* @exception IdUnusedException
* if the collectionId does not identify an existing collection.
* @exception IdUnusedException
* if the collection id for the proposed name already exists in this collection.
* @exception IdLengthException
* if the new collection id exceeds the maximum number of characters for a valid collection id.
* @exception IdInvalidException
* if the resource id is invalid.
*/
public ContentCollectionEdit addCollection(String collectionId, String name)
throws PermissionException, IdUnusedException, IdUsedException,
IdLengthException, IdInvalidException, TypeException
{
// check the id's validity (this may throw IdInvalidException)
// use only the "name" portion, separated at the end
Validator.checkResourceId(name);
checkCollection(collectionId);
String id = collectionId + name.trim();
if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(id);
}
// collection must also end in the separator (we fix it)
if (!id.endsWith(Entity.SEPARATOR))
{
id = id + Entity.SEPARATOR;
}
// check security
unlock(AUTH_RESOURCE_ADD, id);
ContentCollectionEdit edit = null;
try
{
edit = addValidPermittedCollection(id);
}
catch(InconsistentException e)
{
throw new IdUnusedException(collectionId);
}
return edit;
}
/**
* Create a new collection with the given resource id, locked for update. Must commitCollection() to make official, or cancelCollection() when done!
*
* @param id
* The id of the collection.
* @exception IdUsedException
* if the id is already in use.
* @exception InconsistentException
* if the containing collection does not exist.
* @return a new ContentCollection object.
*/
protected ContentCollectionEdit addValidPermittedCollection(String id) throws IdUsedException, InconsistentException
{
// make sure the containing collection exists
String container = isolateContainingId(id);
ContentCollection containingCollection = m_storage.getCollection(container);
if (containingCollection == null)
{
// make any missing collections
generateCollections(container);
// try again
containingCollection = m_storage.getCollection(container);
if (containingCollection == null) throw new InconsistentException(id);
}
// reserve the collection in storage - it will fail if the id is in use
BaseCollectionEdit edit = (BaseCollectionEdit) m_storage.putCollection(id);
if (edit == null)
{
throw new IdUsedException(id);
}
// add live properties
addLiveCollectionProperties(edit);
// track event
edit.setEvent(EVENT_RESOURCE_ADD);
return edit;
}
/**
* check permissions for getCollection().
*
* @param id
* The id of the collection.
* @return true if the user is allowed to getCollection(id), false if not.
*/
public boolean allowGetCollection(String id)
{
return unlockCheck(AUTH_RESOURCE_READ, id);
} // allowGetCollection
/**
* Check access to the collection with this local resource id.
*
* @param id
* The id of the collection.
* @exception IdUnusedException
* if the id does not exist.
* @exception TypeException
* if the resource exists but is not a collection.
* @exception PermissionException
* if the user does not have permissions to see this collection (or read through containing collections).
*/
public void checkCollection(String id) throws IdUnusedException, TypeException, PermissionException
{
unlock(AUTH_RESOURCE_READ, id);
ContentCollection collection = findCollection(id);
if (collection == null) throw new IdUnusedException(id);
} // checkCollection
/**
* Access the collection with this local resource id. The collection internal members and properties are accessible from the returned Colelction object.
*
* @param id
* The id of the collection.
* @exception IdUnusedException
* if the id does not exist.
* @exception TypeException
* if the resource exists but is not a collection.
* @exception PermissionException
* if the user does not have permissions to see this collection (or read through containing collections).
* @return The ContentCollection object found.
*/
public ContentCollection getCollection(String id) throws IdUnusedException, TypeException, PermissionException
{
unlock(AUTH_RESOURCE_READ, id);
ContentCollection collection = findCollection(id);
if (collection == null) throw new IdUnusedException(id);
// track event
// EventTrackingService.post(EventTrackingService.newEvent(EVENT_RESOURCE_READ, collection.getReference(), false));
return collection;
} // getCollection
/**
* Access a List of ContentEntity objects (resources and collections) in this path (and below) if the current user has access to the collection.
*
* @param id
* A collection id.
* @return a List of the ContentEntity objects.
*/
public List getAllEntities(String id)
{
List rv = new ArrayList();
// get the collection members
try
{
ContentCollection collection = getCollection(id);
if (collection != null)
{
getAllEntities(collection, rv, true);
}
}
catch (TypeException e)
{
// should result in an empty list
}
catch (IdUnusedException e)
{
// should result in an empty list
}
catch (PermissionException e)
{
// should result in an empty list
}
return rv;
} // getAllEntities
/**
* Access a List of all the ContentResource objects in this collection (and below).
*
* @param collection
* The collection.
* @param rv
* The list in which to accumulate resource objects.
* @param includeCollections TODO
*/
protected void getAllEntities(ContentCollection collection, List rv, boolean includeCollections)
{
if(includeCollections)
{
rv.add(collection);
}
List members = collection.getMemberResources();
// process members
for (Iterator iMbrs = members.iterator(); iMbrs.hasNext();)
{
ContentEntity next = (ContentEntity) iMbrs.next();
// if resource, add it if permitted
if (next instanceof ContentResource)
{
rv.add(next);
}
// if collection, again
else
{
getAllEntities((ContentCollection) next, rv, includeCollections);
}
}
} // getAllEntities
/**
* Access a List of all the deleted ContentResource objects in this path (and below) which the current user has access.
*
* @param id
* A collection id.
* @return a List of the ContentResource objects.
* @throws PermissionException
* @throws TypeException
* @throws IdUnusedException
*/
public List getAllDeletedResources(String id)
{
List rv = new ArrayList();
try {
ContentCollection collection = getCollection(id);
if ( unlockCheck(AUTH_RESOURCE_WRITE_ANY, id) ) {
return m_storage.getDeletedResources(collection);
} else {
List l = m_storage.getDeletedResources(collection);
String currentUserId = sessionManager.getCurrentSessionUserId();
// Check if the file was removed by the current user
for (Object o:l) {
BaseResourceEdit e = (BaseResourceEdit)o;
String removedBy = e.getProperties().getProperty(ResourceProperties.PROP_CREATOR);
if (removedBy != null && removedBy.equals(currentUserId)) {
rv.add(e);
}
}
}
} catch (IdUnusedException iue) {
M_log.warn("getAllDeletedResources: cannot retrieve collection for : " + id);
} catch (TypeException te) {
M_log.warn("getAllDeletedResources: resource with id: " + id + " not a collection");
} catch (PermissionException pe) {
M_log.warn("getAllDeletedResources: access to resource with id: " + id + " failed : " + pe);
}
return rv;
} // getAllDeletedResources
/**
* Access a List of all the ContentResource objects in this path (and below) which the current user has access.
*
* @param id
* A collection id.
* @return a List of the ContentResource objects.
*/
public List<ContentResource> getAllResources(String id)
{
List<ContentResource> rv = new ArrayList<ContentResource>();
// get the collection members
try
{
ContentCollection collection = findCollection(id);
if (collection != null)
{
getAllResources(collection, rv, false);
}
}
catch (TypeException e)
{
}
return rv;
} // getAllResources
/**
* Access a List of all the ContentResource objects in this collection (and below) which the current user has access.
*
* @param collection
* The collection.
* @param rv
* The list in which to accumulate resource objects.
* @param includeCollections TODO
*/
protected void getAllResources(ContentCollection collection, List rv, boolean includeCollections)
{
if(includeCollections)
{
if (unlockCheck(AUTH_RESOURCE_READ, collection.getId()))
{
rv.add(collection);
}
}
List members = collection.getMemberResources();
// process members
for (Iterator iMbrs = members.iterator(); iMbrs.hasNext();)
{
ContentEntity next = (ContentEntity) iMbrs.next();
// if resource, add it if permitted
if (next instanceof ContentResource)
{
if (unlockCheck(AUTH_RESOURCE_READ, next.getId()))
{
rv.add(next);
}
}
// if collection, again
else
{
getAllResources((ContentCollection) next, rv, includeCollections);
}
}
} // getAllResources
/**
* Access the collection with this local resource id. Internal find does the guts of finding without security or event tracking. The collection internal members and properties are accessible from the returned Colelction object.
*
* @param id
* The id of the collection.
* @exception TypeException
* if the resource exists but is not a collection.
* @return The ContentCollection object found, or null if not.
*/
protected ContentCollection findCollection(String id) throws TypeException
{
ContentCollection collection = null;
try
{
collection = (ContentCollection) threadLocalManager.get("findCollection@" + id);
}
catch(ClassCastException e)
{
throw new TypeException(id);
}
if(collection == null)
{
collection = m_storage.getCollection(id);
if(collection != null)
{
threadLocalManager.set("findCollection@" + id, collection); // new BaseCollectionEdit(collection));
}
}
else
{
collection = new BaseCollectionEdit(collection);
}
return collection;
} // findCollection
/**
* check permissions for editCollection()
*
* @param id
* The id of the collection.
* @return true if the user is allowed to update the collection, false if not.
*/
public boolean allowUpdateCollection(String id)
{
boolean isAllowed = allowUpdate(id);
if(isAllowed)
{
try
{
checkExplicitLock(id);
}
catch(PermissionException e)
{
isAllowed = false;
}
}
return isAllowed;
} // allowUpdateCollection
/**
* check permissions for revising collections or resources
* @param id The id of the collection.
* @return true if the user is allowed to update the collection, false if not.
*/
public boolean allowUpdate(String id)
{
String currentUser = sessionManager.getCurrentSessionUserId();
String owner = "";
if (m_securityService.isSuperUser(currentUser)) {
//supper users should always get a 404 rather than a permission exception
return true;
}
try
{
ResourceProperties props = getProperties(id);
owner = props.getProperty(ResourceProperties.PROP_CREATOR);
}
catch (PermissionException e )
{
// PermissionException can be thrown if not AUTH_RESOURCE_READ
return false;
} catch (IdUnusedException e) {
//Also non admin users should get a permission exception is the resource doesn't exist
return false;
}
// check security to delete any collection
if ( unlockCheck(AUTH_RESOURCE_WRITE_ANY, id) )
return true;
// check security to delete own collection
else if ( currentUser != null && currentUser.equals(owner)
&& unlockCheck(AUTH_RESOURCE_WRITE_OWN, id) )
return true;
// check security to delete own collection for anonymous users
else if ( currentUser == null && owner == null &&
unlockCheck(AUTH_RESOURCE_WRITE_OWN, id) )
return true;
// otherwise not authorized
else
return false;
} // allowUpdate
/**
* check permissions for removeCollection(). Note: for just this collection, not the members on down.
*
* @param id
* The id of the collection.
* @return true if the user is allowed to removeCollection(id), false if not.
*/
public boolean allowRemoveCollection(String id)
{
return allowRemove(id);
} // allowRemoveCollection
/**
* check permissions for removing collections or resources
* Note: for just this collection, not the members on down.
* @param id The id of the collection.
* @return true if the user is allowed to removeCollection(id), false if not.
*/
protected boolean allowRemove(String id)
{
String currentUser = sessionManager.getCurrentSessionUserId();
String owner = "";
//Supper users always have the permission
if (m_securityService.isSuperUser()) {
return true;
}
try
{
ResourceProperties props = getProperties(id);
owner = props.getProperty(ResourceProperties.PROP_CREATOR);
}
catch ( Exception e )
{
// PermissionException can be thrown if not RESOURCE_AUTH_READ
return false;
}
// check security to delete any collection
if ( unlockCheck(AUTH_RESOURCE_REMOVE_ANY, id) )
return true;
// check security to delete own collection
else if ( currentUser != null && currentUser.equals(owner) &&
unlockCheck(AUTH_RESOURCE_REMOVE_OWN, id) )
return true;
// check security to delete own collection for anonymous users
else if ( currentUser == null && owner == null &&
unlockCheck(AUTH_RESOURCE_REMOVE_OWN, id) )
return true;
// otherwise not authorized
else
return false;
} // allowRemove
/**
* Remove just a collection. It must be empty.
*
* @param collection
* The collection to remove.
* @exception TypeException
* if the resource exists but is not a collection.
* @exception PermissionException
* if the user does not have permissions to remove this collection, read through any containing
* @exception InconsistentException
* if the collection has members, so that the removal would leave things in an inconsistent state.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and an attempt to access the resource body of any collection member fails.
*/
public void removeCollection(ContentCollectionEdit edit) throws TypeException, PermissionException, InconsistentException,
ServerOverloadException
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("removeCollection(): closed ContentCollectionEdit", e);
return;
}
// check security
if ( ! allowRemoveCollection(edit.getId()) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_REMOVE_ANY, edit.getReference());
// clear thread-local cache SAK-12126
threadLocalManager.set("members@" + edit.getId(), null);
threadLocalManager.set("getResources@" + edit.getId(), null);
threadLocalManager.set("getCollections@" + edit.getId(), null);
// check for members
List members = edit.getMemberResources();
if (!members.isEmpty()) throw new InconsistentException(edit.getId());
// complete the edit
m_storage.removeCollection(edit);
// close the edit object
((BaseCollectionEdit) edit).closeEdit();
((BaseCollectionEdit) edit).setRemoved();
// remove the old version from thread-local cache.
threadLocalManager.set("findCollection@" + edit.getId(), null);
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(edit.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.debug("removeCollection: removing realm for : " + edit.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
M_log.debug("removeCollection: removing realm for : " + edit.getReference() + " : " + ignore);
}
// track it (no notification)
String ref = edit.getReference(null);
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_REMOVE, ref, true,
NotificationService.NOTI_NONE));
eventTrackingService.cancelDelays(ref);
} // removeCollection
/**
* Remove a collection and all members of the collection, internal or deeper.
*
* @param id
* The id of the collection.
* @exception IdUnusedException
* if the id does not exist.
* @exception TypeException
* if the resource exists but is not a collection.
* @exception PermissionException
* if the user does not have permissions to remove this collection, read through any containing
* @exception InUseException
* if the collection or a contained member is locked by someone else. collections, or remove any members of the collection.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and an attempt to access the resource body of any collection member fails.
*/
public void removeCollection(String id) throws IdUnusedException, TypeException, PermissionException, InUseException,
ServerOverloadException
{
// check security
if ( ! allowRemoveCollection(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_REMOVE_ANY, getReference(id) );
// find the collection
ContentCollection thisCollection = findCollection(id);
if (thisCollection == null) throw new IdUnusedException(id);
// check security: can we remove members (if any)
// Note: this will also be done in clear(), except some might get deleted before one is not allowed.
// unlockContained(AUTH_RESOURCE_REMOVE, thisCollection);
// get an edit
ContentCollectionEdit edit = editCollection(id);
// clear thread-local cache SAK-12126
threadLocalManager.set("members@" + id, null);
threadLocalManager.set("getResources@" + id, null);
threadLocalManager.set("getCollections@" + edit.getId(), null);
// clear of all members (recursive)
// Note: may fail if something's in use or not permitted. May result in a partial clear.
try
{
((BaseCollectionEdit) edit).clear();
// remove
removeCollection(edit);
}
catch (InconsistentException e)
{
M_log.error("removeCollection():", e);
}
finally
{
// if we don't get the remove done, we need to cancel here
if (((BaseCollectionEdit) edit).isActiveEdit())
{
cancelCollection(edit);
}
}
} // removeCollection
/**
* Commit the changes made, and release the lock. The Object is disabled, and not to be used after this call.
*
* @param edit
* The ContentCollectionEdit object to commit.
* @throws PermissionException
*/
public void commitCollection(ContentCollectionEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("commitCollection(): closed ContentCollectionEdit", e);
return;
}
if(AccessMode.GROUPED == edit.getAccess())
{
verifyGroups(edit, edit.getGroups());
}
if(this.m_prioritySortEnabled)
{
ResourcePropertiesEdit props = edit.getPropertiesEdit();
String sortBy = props.getProperty(ResourceProperties.PROP_CONTENT_PRIORITY);
if(sortBy == null)
{
// add a default value that sorts new items after existing items, with new folders before new resources
ContentCollection container = edit.getContainingCollection();
int count = container.getMemberCount();
props.addProperty(ResourceProperties.PROP_CONTENT_PRIORITY, Integer.toString(count + 1));
}
}
if(((BasicGroupAwareEdit) edit).isVisibilityUpdated()) {
// post EVENT_RESOURCE_UPD_VISIBILITY event
this.eventTrackingService.post(this.eventTrackingService.newEvent(EVENT_RESOURCE_UPD_VISIBILITY, edit.getReference(), true));
}
if(((BasicGroupAwareEdit) edit).isAccessUpdated()) {
// post EVENT_RESOURCE_UPD_ACCESS event
this.eventTrackingService.post(this.eventTrackingService.newEvent(EVENT_RESOURCE_UPD_ACCESS, edit.getReference(), true));
}
// update the properties for update
addLiveUpdateCollectionProperties(edit);
// complete the edit
m_storage.commitCollection(edit);
// close the edit object
((BaseCollectionEdit) edit).closeEdit();
// the collection has changed so we must remove the old version from thread-local cache
threadLocalManager.set("findCollection@" + edit.getId(), null);
String containerId = isolateContainingId(edit.getId());
threadLocalManager.set("findCollection@" + containerId, null);
threadLocalManager.set("members@" + containerId, null);
threadLocalManager.set("getCollections@" + containerId, null);
//threadLocalManager.set("getResources@" + containerId, null);
// track it (no notification)
String ref = edit.getReference(null);
eventTrackingService.post(eventTrackingService.newEvent(((BaseCollectionEdit) edit)
.getEvent(), ref, true, NotificationService.NOTI_NONE));
} // commitCollection
private void postAvailableEvent(GroupAwareEntity entity, String ref, int priority)
{
// cancel all scheduled available events for this entity.
eventTrackingService.cancelDelays(ref, EVENT_RESOURCE_AVAILABLE);
if ( ! entity.isAvailable() )
{
// schedule an event to tell when resource becomes available
if (entity.getReleaseDate() != null)
{
eventTrackingService.delay(eventTrackingService.newEvent(EVENT_RESOURCE_AVAILABLE, ref,
false, priority), entity.getReleaseDate());
entity.getProperties().addProperty(PROP_AVAIL_NOTI, Boolean.FALSE.toString());
}
// schedule an event to tell when resource becomes unavailable
if ( entity.getRetractDate() != null )
{
eventTrackingService.delay(eventTrackingService.newEvent(EVENT_RESOURCE_UNAVAILABLE, ref,
false, priority), entity.getRetractDate());
entity.getProperties().addProperty(PROP_AVAIL_NOTI, Boolean.FALSE.toString());
}
}
else
{
// for available resources, make sure this event hasn't been fired before. this check is
// to ensure an available event isn't sent multiple times for the same resource.
String notified = entity.getProperties().getProperty(PROP_AVAIL_NOTI);
// do not post an available event for updates
if (!Boolean.TRUE.toString().equalsIgnoreCase(notified) &&
!EVENT_RESOURCE_WRITE.equals(((BaseResourceEdit) entity).getEvent()))
{
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_AVAILABLE,
ref, false, priority));
entity.getProperties().addProperty(PROP_AVAIL_NOTI, Boolean.TRUE.toString());
}
// schedule an event to tell when resource becomes unavailable
if ( entity.getRetractDate() != null )
{
eventTrackingService.delay(eventTrackingService.newEvent(EVENT_RESOURCE_UNAVAILABLE, ref,
false, priority), entity.getRetractDate());
entity.getProperties().addProperty(PROP_AVAIL_NOTI, Boolean.FALSE.toString());
}
}
}
/**
* Recursively traverse the heirarchy of ContentEntity objects contained within a collection and remove access groups if they
* are not included in the set defined for the initial collection. The branching stops whenever we verify a ContentCollection
* with "grouped" access or a ContentResource.
* @param collection
* @param groups
*/
protected void verifyGroups(ContentCollection collection, Collection groups)
{
Collection members = collection.getMemberResources();
if(members == null || members.isEmpty())
{
return;
}
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
ContentEntity member = (ContentEntity) memberIt.next();
if(AccessMode.GROUPED == member.getAccess())
{
adjustGroups(member, groups);
}
if(member instanceof ContentCollection)
{
// recursive call
verifyGroups((ContentCollectionEdit) member, groups);
}
}
}
protected void adjustGroups(ContentEntity member, Collection groups)
{
// check groups and then return
Collection subgroups = member.getGroups();
if(groups.containsAll(subgroups))
{
// this entity's groups are OK, so do nothing
}
else
{
Collection newgroups = new ArrayList();
Iterator groupIt = subgroups.iterator();
while(groupIt.hasNext())
{
String groupRef = (String) groupIt.next();
if(groups.contains(groupRef))
{
newgroups.add(groupRef);
}
}
if(member instanceof ContentResource)
{
ContentResourceEdit edit = m_storage.editResource(member.getId());
try
{
if(newgroups.isEmpty())
{
edit.clearGroupAccess();
}
else
{
edit.setGroupAccess(newgroups);
}
// addLiveUpdateResourceProperties(edit);
m_storage.commitResource(edit);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
}
catch (InconsistentException e)
{
// If change of groups is consistent in superfolder, this should not occur here
m_storage.cancelResource(edit);
M_log.error("verifyGroups(): ", e);
}
catch (PermissionException e)
{
// If user has permission to change groups in superfolder, this should not occur here
m_storage.cancelResource(edit);
M_log.error("verifyGroups(): ", e);
}
catch (ServerOverloadException e)
{
M_log.error("verifyGroups(): ", e);
}
}
else
{
ContentCollectionEdit edit = m_storage.editCollection(member.getId());
try
{
if(newgroups.isEmpty())
{
edit.clearGroupAccess();
}
else
{
edit.setGroupAccess(newgroups);
}
// addLiveUpdateCollectionProperties(edit);
m_storage.commitCollection(edit);
}
catch (InconsistentException e)
{
// If change of groups is consistent in superfolder, this should not occur here
m_storage.cancelCollection(edit);
M_log.error("verifyGroups(): ", e);
}
catch (PermissionException e)
{
// If user has permission to change groups in superfolder, this should not occur here
m_storage.cancelCollection(edit);
M_log.error("verifyGroups(): ", e);
}
}
}
}
/**
* Cancel the changes made object, and release the lock. The Object is disabled, and not to be used after this call.
*
* @param edit
* The ContentCollectionEdit object to commit.
*/
public void cancelCollection(ContentCollectionEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("cancelCollection(): closed ContentCollectionEdit", e);
return;
}
// release the edit lock
m_storage.cancelCollection(edit);
// if the edit is newly created during an add collection process, remove it from the storage
String event = ((BaseCollectionEdit) edit).getEvent();
if (EVENT_RESOURCE_ADD.equals(event))
{
removeRecursive(edit);
m_storage.removeCollection(edit);
}
// close the edit object
((BaseCollectionEdit) edit).closeEdit();
} // cancelCollection
/**
* used to remove any members of a collection whoes add was canceled.
*
* @param parent
*/
protected void removeRecursive(ContentCollection parent)
{
List members = parent.getMemberResources();
for (Iterator i = members.iterator(); i.hasNext();)
{
Object resource = i.next();
try
{
if (resource instanceof ContentResource)
{
removeResource(((ContentResource) resource).getId());
}
else if (resource instanceof ContentCollection)
{
ContentCollection collection = (ContentCollection) resource;
removeRecursive(collection);
removeCollection(collection.getId());
}
}
catch (IdUnusedException e)
{
M_log.error("failed to removed canceled collection child", e);
}
catch (TypeException e)
{
M_log.error("failed to removed canceled collection child", e);
}
catch (PermissionException e)
{
M_log.error("failed to removed canceled collection child", e);
}
catch (InUseException e)
{
M_log.error("failed to removed canceled collection child", e);
}
catch (ServerOverloadException e)
{
M_log.error("failed to removed canceled collection child", e);
}
}
}
protected void cacheEntities(List<? extends ContentEntity> entities)
{
if(entities == null)
{
return;
}
for(ContentEntity entity : entities)
{
if(entity == null)
{
// do nothing
}
else if(entity instanceof ContentResource)
{
threadLocalManager.set("findResource@" + entity.getId(), entity);
}
else if(entity instanceof ContentCollection)
{
threadLocalManager.set("findCollection@" + entity.getId(), entity);
}
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* Resources
*********************************************************************************************************************************************************************************************************************************************************/
/**
* check permissions for addResource().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to addResource(id), false if not.
*/
public boolean allowAddResource(String id)
{
// resource must also NOT end with a separator characters (we fix it)
if (id.endsWith(Entity.SEPARATOR))
{
id = id.substring(0, id.length() - 1);
}
// check security
boolean isAllowed = unlockCheck(AUTH_RESOURCE_ADD, id);
if(isAllowed)
{
// check for explicit locks
try
{
checkExplicitLock(id);
}
catch (PermissionException e)
{
isAllowed = false;
}
}
return isAllowed;
} // allowAddResource
/**
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, byte[], org.sakaiproject.entity.api.ResourceProperties, java.util.Collection, int)
*/
public ContentResource addResource(String id, String type, byte[] content, ResourceProperties properties, Collection groups, int priority)
throws PermissionException, IdUsedException, IdInvalidException, InconsistentException, OverQuotaException,
ServerOverloadException {
ByteArrayInputStream contentStream = new ByteArrayInputStream(content);
return addResource(id, type, contentStream, properties, groups, priority);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, java.io.InputStream, org.sakaiproject.entity.api.ResourceProperties, java.util.Collection, int)
*/
public ContentResource addResource(String id, String type, InputStream content, ResourceProperties properties, Collection groups, int priority)
throws PermissionException, IdUsedException, IdInvalidException, InconsistentException, OverQuotaException,
ServerOverloadException
{
id = (String) fixTypeAndId(id, type).get("id");
ContentResourceEdit edit = addResource(id);
edit.setContentType(type);
edit.setContent(content);
addProperties(edit.getPropertiesEdit(), properties);
// commit the change
if(groups == null || groups.isEmpty())
{
// access is inherited (the default)
}
else
{
edit.setGroupAccess(groups);
// TODO: Need to deal with failure here
}
try
{
commitResource(edit, priority);
}
catch(OverQuotaException e)
{
M_log.debug("OverQuotaException " + e);
try
{
removeResource(edit.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + edit.getId() + "\n" + e1);
}
throw e;
}
catch(ServerOverloadException e)
{
M_log.debug("ServerOverloadException " + e);
try
{
removeResource(edit.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + edit.getId() + "\n" + e1);
}
throw e;
}
return edit;
} // addResource
/**
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, byte[], org.sakaiproject.entity.api.ResourceProperties, int)
*/
public ContentResource addResource(String id, String type, byte[] content, ResourceProperties properties, int priority)
throws PermissionException, IdUsedException, IdInvalidException, InconsistentException, OverQuotaException,
ServerOverloadException {
ByteArrayInputStream contentStream = new ByteArrayInputStream(content);
return addResource(id, type, contentStream, properties, priority);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, java.io.InputStream, org.sakaiproject.entity.api.ResourceProperties, int)
*/
public ContentResource addResource(String id, String type, InputStream content, ResourceProperties properties, int priority)
throws PermissionException, IdUsedException, IdInvalidException, InconsistentException, OverQuotaException,
ServerOverloadException
{
Collection no_groups = new ArrayList();
return addResource(id, type, content, properties, no_groups, priority);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, int, java.lang.String, byte[], org.sakaiproject.entity.api.ResourceProperties, java.util.Collection, boolean, org.sakaiproject.time.api.Time, org.sakaiproject.time.api.Time, int)
*/
public ContentResource addResource(String name, String collectionId, int limit, String type, byte[] content,
ResourceProperties properties, Collection groups, boolean hidden, Time releaseDate, Time retractDate, int priority)
throws PermissionException, IdUniquenessException, IdLengthException, IdInvalidException,
InconsistentException, OverQuotaException, ServerOverloadException {
ByteArrayInputStream contentStream = new ByteArrayInputStream(content);
return addResource(name, collectionId, limit, type, contentStream, properties, groups,
hidden, releaseDate, retractDate, priority);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, int, java.lang.String, java.io.InputStream, org.sakaiproject.entity.api.ResourceProperties, java.util.Collection, boolean, org.sakaiproject.time.api.Time, org.sakaiproject.time.api.Time, int)
*/
public ContentResource addResource(String name, String collectionId, int limit, String type, InputStream content,
ResourceProperties properties, Collection groups, boolean hidden, Time releaseDate, Time retractDate, int priority)
throws PermissionException, IdUniquenessException, IdLengthException, IdInvalidException,
InconsistentException, OverQuotaException, ServerOverloadException
{
try
{
collectionId = collectionId.trim();
name = Validator.escapeResourceName(name.trim());
checkCollection(collectionId);
}
catch (IdUnusedException e)
{
throw new InconsistentException(collectionId);
}
catch (TypeException e)
{
throw new InconsistentException(collectionId);
}
String id = collectionId + name;
id = (String) fixTypeAndId(id, type).get("id");
if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(id);
}
ContentResourceEdit edit = null;
try
{
edit = addResource(id);
edit.setContentType(type);
edit.setContent(content);
addProperties(edit.getPropertiesEdit(), properties);
if(groups == null || groups.isEmpty())
{
// access is inherited (the default)
}
else
{
edit.setGroupAccess(groups);
// TODO: Need to deal with failure here
}
edit.setAvailability(hidden, releaseDate, retractDate);
try
{
// commit the change
commitResource(edit, priority);
}
catch(OverQuotaException e)
{
M_log.debug("OverQuotaException " + e);
try
{
removeResource(edit.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + edit.getId() + "\n" + e1);
}
throw e;
}
catch(ServerOverloadException e)
{
M_log.debug("ServerOverloadException " + e);
try
{
removeResource(edit.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + edit.getId() + "\n" + e1);
}
throw e;
}
}
catch (IdUsedException e)
{
try
{
checkResource(id);
}
catch (IdUnusedException inner_e)
{
// TODO: What does this condition actually represent? What exception should be thrown?
throw new IdUniquenessException(id);
}
catch (TypeException inner_e)
{
throw new InconsistentException(id);
}
SortedSet<String> siblings = new TreeSet<String>();
try
{
ContentCollection collection = findCollection(collectionId);
siblings.addAll(collection.getMembers());
}
catch (TypeException inner_e)
{
throw new InconsistentException(collectionId);
}
int index = name.lastIndexOf(".");
String base = name;
String ext = "";
if (index > 0 && !"Url".equalsIgnoreCase(type))
{
base = name.substring(0, index);
ext = name.substring(index);
}
boolean trying = true;
int attempts = 1;
while (trying) // see end of loop for condition that enforces attempts <= limit)
{
String new_id = collectionId + base + "-" + attempts + ext;
if (new_id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(new_id);
}
if (!siblings.contains(new_id))
{
try
{
edit = addResource(new_id);
edit.setContentType(type);
edit.setContent(content);
if(groups == null || groups.isEmpty())
{
// access is inherited (the default)
}
else
{
edit.setGroupAccess(groups);
// TODO: Need to deal with failure here
}
addProperties(edit.getPropertiesEdit(), properties);
// commit the change
commitResource(edit, priority);
trying = false;
}
catch (IdUsedException ignore)
{
// try again
}
}
attempts++;
if (attempts > limit)
{
throw new IdUniquenessException(new_id);
}
}
}
return edit;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.api.ContentHostingService#addResource(java.lang.String, java.lang.String, java.lang.String, int)
*/
public ContentResourceEdit addResource(String collectionId, String basename, String extension, int maximum_tries)
throws PermissionException, IdUniquenessException, IdLengthException, IdInvalidException,
IdUnusedException, OverQuotaException, ServerOverloadException
{
// check the id's validity (this may throw IdInvalidException)
// use only the "name" portion, separated at the end
try
{
checkCollection(collectionId);
}
catch (TypeException e)
{
throw new IdUnusedException(collectionId);
}
if(basename == null)
{
throw new IdInvalidException("");
}
if(extension == null)
{
extension = "";
}
else
{
extension = extension.trim();
if(extension.equals("") || extension.startsWith("."))
{
// do nothing
}
else
{
extension = "." + extension;
}
}
basename = Validator.escapeResourceName(basename.trim());
extension = Validator.escapeResourceName(extension);
String name = basename + extension;
String id = collectionId + name;
if(id.length() > ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(id);
}
BaseResourceEdit edit = null;
int attempts = 0;
boolean done = false;
while(!done && attempts < maximum_tries)
{
try
{
edit = (BaseResourceEdit) addResource(id);
done = true;
// add live properties
addLiveResourceProperties(edit);
ResourceProperties props = edit.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
// track event
edit.setEvent(EVENT_RESOURCE_ADD);
}
catch(InconsistentException inner_e)
{
throw new IdInvalidException(id);
}
catch(IdUsedException e)
{
SortedSet<String> siblings = new TreeSet<String>();
try
{
ContentCollection collection = findCollection(collectionId);
siblings.addAll(collection.getMembers());
}
catch (TypeException inner_e)
{
throw new IdUnusedException(collectionId);
}
// see end of loop for condition that enforces attempts <= limit)
do
{
attempts++;
name = basename + "-" + attempts + extension;
id = collectionId + name;
if (attempts >= maximum_tries)
{
throw new IdUniquenessException(id);
}
if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(id);
}
}
while (siblings.contains(id));
}
}
threadLocalManager.set("members@" + collectionId, null);
//threadLocalManager.set("getCollections@" + collectionId, null);
threadLocalManager.set("getResources@" + collectionId, null);
// if (edit == null)
// {
// throw new IdUniquenessException(id);
// }
return edit;
}
/**
* Create a new resource with the given resource name used as a resource id within the specified collection or (if that id is already in use) with a resource id based on a variation on the name to achieve a unique id, provided a unique id can be found
* before a limit is reached on the number of attempts to achieve uniqueness. Used to create a resource that is not group aware.
*
* @param name
* The name of the new resource (such as a filename).
* @param collectionId
* The id of the collection to which the resource should be added.
* @param limit
* The maximum number of attempts at finding a unique id based on the given name.
* @param type
* The mime type string of the resource.
* @param content
* An array containing the bytes of the resource's content.
* @param properties
* A ResourceProperties object with the properties to add to the new resource.
* @param priority
* The notification priority for this commit.
* @exception PermissionException
* if the user does not have permission to add a resource to the containing collection.
* @exception IdUniquenessException
* if a unique resource id cannot be found before the limit on the number of attempts is reached.
* @exception IdLengthException
* if the resource id exceeds the maximum number of characters for a valid resource id.
* @exception IdInvalidException
* if the resource id is invalid.
* @exception InconsistentException
* if the containing collection does not exist.
* @exception OverQuotaException
* if this would result in being over quota.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @return a new ContentResource object.
*/
public ContentResource addResource(String name, String collectionId, int limit, String type, byte[] content,
ResourceProperties properties, int priority)
throws PermissionException, IdUniquenessException, IdLengthException, IdInvalidException,
InconsistentException, OverQuotaException, ServerOverloadException
{
Collection no_groups = new ArrayList();
return addResource(name, collectionId, limit, type, content, properties, no_groups, false, null, null, priority);
}
/**
* Create a new resource with the given resource id, locked for update. Must commitResource() to make official, or cancelResource() when done!
*
* @param id
* The id of the new resource.
* @exception PermissionException
* if the user does not have permission to add a resource to the containing collection.
* @exception IdUsedException
* if the resource id is already in use.
* @exception IdInvalidException
* if the resource id is invalid.
* @exception InconsistentException
* if the containing collection does not exist.
* @return a new ContentResource object.
*/
public ContentResourceEdit addResource(String id) throws PermissionException, IdUsedException, IdInvalidException,
InconsistentException
{
// check the id's validity (this may throw IdInvalidException)
// use only the "name" portion, separated at the end
String justName = isolateName(id);
Validator.checkResourceId(justName);
// resource must also NOT end with a separator characters (we fix it)
if (id.endsWith(Entity.SEPARATOR))
{
id = id.substring(0, id.length() - 1);
}
// check security
checkExplicitLock(id);
unlock(AUTH_RESOURCE_ADD, id);
// make sure the containing collection exists
String container = isolateContainingId(id);
ContentCollection containingCollection = m_storage.getCollection(container);
if (containingCollection == null)
{
// make any missing collections
generateCollections(container);
// try again
containingCollection = m_storage.getCollection(container);
if (containingCollection == null) throw new InconsistentException(id);
}
// reserve the resource in storage - it will fail if the id is in use
BaseResourceEdit edit = (BaseResourceEdit) m_storage.putResource(id);
if (edit == null)
{
throw new IdUsedException(id);
}
// add live properties
addLiveResourceProperties(edit);
// track event
edit.setEvent(EVENT_RESOURCE_ADD);
return edit;
} // addResource
/**
* Create a new resource with the given resource name used as a resource id within the specified collection or (if that id is already in use) with a resource id based on a variation on the name to achieve a unique id, provided a unique id can be found
* before a limit is reached on the number of attempts to achieve uniqueness. Used to create a group-aware resource.
*
* @param name
* The name of the new resource (such as a filename).
* @param collectionId
* The id of the collection to which the resource should be added.
* @param limit
* The maximum number of attempts at finding a unique id based on the given name.
* @param type
* The mime type string of the resource.
* @param content
* An array containing the bytes of the resource's content.
* @param properties
* A ResourceProperties object with the properties to add to the new resource.
* @param groups
* A collection (String) of references to Group objects representing the site subgroups that should have access to this entity.
* May be empty to indicate access is not limited to a group or groups.
* @param priority
* The notification priority for this commit.
* @exception PermissionException
* if the user does not have permission to add a resource to the containing collection.
* @exception IdUniquenessException
* if a unique resource id cannot be found before the limit on the number of attempts is reached.
* @exception IdLengthException
* if the resource id exceeds the maximum number of characters for a valid resource id.
* @exception IdInvalidException
* if the resource id is invalid.
* @exception InconsistentException
* if the containing collection does not exist.
* @exception OverQuotaException
* if this would result in being over quota.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @return a new ContentResource object.
*/
public ContentResource addResource(String name, String collectionId, int limit, String type, byte[] content,
ResourceProperties properties, Collection groups, int priority)
throws PermissionException, IdUniquenessException, IdLengthException, IdInvalidException,
InconsistentException, OverQuotaException, ServerOverloadException
{
try
{
collectionId = collectionId.trim();
name = Validator.escapeResourceName(name.trim());
checkCollection(collectionId);
}
catch (IdUnusedException e)
{
throw new InconsistentException(collectionId);
}
catch (TypeException e)
{
throw new InconsistentException(collectionId);
}
String id = collectionId + name;
id = (String) fixTypeAndId(id, type).get("id");
if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(id);
}
ContentResourceEdit edit = null;
try
{
edit = addResource(id);
edit.setContentType(type);
edit.setContent(content);
addProperties(edit.getPropertiesEdit(), properties);
if(groups == null || groups.isEmpty())
{
// access is inherited (the default)
}
else
{
edit.setGroupAccess(groups);
// TODO: Need to deal with failure here
}
try
{
// commit the change
commitResource(edit, priority);
}
catch(OverQuotaException e)
{
M_log.debug("OverQuotaException " + e);
try
{
removeResource(edit.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + edit.getId() + "\n" + e1);
}
throw e;
}
catch(ServerOverloadException e)
{
M_log.debug("ServerOverloadException " + e);
try
{
removeResource(edit.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + edit.getId() + "\n" + e1);
}
throw e;
}
}
catch (IdUsedException e)
{
try
{
checkResource(id);
}
catch (IdUnusedException inner_e)
{
// TODO: What does this condition actually represent? What exception should be thrown?
throw new IdUniquenessException(id);
}
catch (TypeException inner_e)
{
throw new InconsistentException(id);
}
SortedSet<String> siblings = new TreeSet<String>();
try
{
ContentCollection collection = findCollection(collectionId);
siblings.addAll(collection.getMembers());
}
catch (TypeException inner_e)
{
throw new InconsistentException(collectionId);
}
int index = name.lastIndexOf(".");
String base = name;
String ext = "";
if (index > 0 && !"Url".equalsIgnoreCase(type))
{
base = name.substring(0, index);
ext = name.substring(index);
}
boolean trying = true;
int attempts = 1;
while (trying) // see end of loop for condition that enforces attempts <= limit)
{
String new_id = collectionId + base + "-" + attempts + ext;
if (new_id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(new_id);
}
if (!siblings.contains(new_id))
{
try
{
edit = addResource(new_id);
edit.setContentType(type);
edit.setContent(content);
if(groups == null || groups.isEmpty())
{
// access is inherited (the default)
}
else
{
edit.setGroupAccess(groups);
// TODO: Need to deal with failure here
}
addProperties(edit.getPropertiesEdit(), properties);
// commit the change
commitResource(edit, priority);
trying = false;
}
catch (IdUsedException ignore)
{
// try again
}
}
attempts++;
if (attempts > limit)
{
throw new IdUniquenessException(new_id);
}
}
}
return edit;
}
/**
* check permissions for addAttachmentResource().
*
* @return true if the user is allowed to addAttachmentResource(), false if not.
*/
public boolean allowAddAttachmentResource()
{
return unlockCheck(AUTH_RESOURCE_ADD, ATTACHMENTS_COLLECTION);
} // allowAddAttachmentResource
/**
* Check whether a resource id or collection id references an entity in the attachments collection. This method makes no guarantees that a resource actually exists with this id.
*
* @param id
* Assumed to be a valid resource id or collection id.
* @return true if the id (assuming it is a valid id for an existing resource or collection) references an entity in the hidden attachments area created through one of this class's addAttachmentResource methods.
*/
public boolean isAttachmentResource(String id)
{
//the id could be null
if (id == null) {
return false;
}
// TODO: Should we check whether this is a valid resource id?
return id.startsWith(ATTACHMENTS_COLLECTION);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addAttachmentResource(java.lang.String, java.lang.String, byte[], org.sakaiproject.entity.api.ResourceProperties)
*/
public ContentResource addAttachmentResource(String name, String type, byte[] content, ResourceProperties properties)
throws IdInvalidException, InconsistentException, IdUsedException, PermissionException, OverQuotaException,
ServerOverloadException {
ByteArrayInputStream contentStream = new ByteArrayInputStream(content);
return addAttachmentResource(name, type, contentStream, properties);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addAttachmentResource(java.lang.String, java.lang.String, InputStream, org.sakaiproject.entity.api.ResourceProperties)
*/
public ContentResource addAttachmentResource(String name, String type, InputStream content, ResourceProperties properties)
throws IdInvalidException, InconsistentException, IdUsedException, PermissionException, OverQuotaException,
ServerOverloadException
{
// make sure the name is valid
Validator.checkResourceId(name);
// resource must also NOT end with a separator characters (we fix it)
if (name.endsWith(Entity.SEPARATOR))
{
name = name.substring(0, name.length() - 1);
}
// form a name based on the attachments collection, a unique folder id, and the given name
String collection = ATTACHMENTS_COLLECTION + idManager.createUuid() + Entity.SEPARATOR;
String id = collection + name;
if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new RuntimeException(ID_LENGTH_EXCEPTION);
}
// add this collection
ContentCollectionEdit edit = addCollection(collection);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
commitCollection(edit);
// and add the resource
return addResource(id, type, content, properties, new ArrayList(), NotificationService.NOTI_NONE);
} // addAttachmentResource
/**
* @see org.sakaiproject.content.api.ContentHostingService#addAttachmentResource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, byte[], org.sakaiproject.entity.api.ResourceProperties)
*/
public ContentResource addAttachmentResource(String name, String site, String tool, String type, byte[] content,
ResourceProperties properties) throws IdInvalidException, InconsistentException, IdUsedException, PermissionException,
OverQuotaException, ServerOverloadException
{
ByteArrayInputStream contentStream = new ByteArrayInputStream(content);
return addAttachmentResource(name, site, tool, type, contentStream, properties);
}
/**
* @see org.sakaiproject.content.api.ContentHostingService#addAttachmentResource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.InputStream, org.sakaiproject.entity.api.ResourceProperties)
*/
public ContentResource addAttachmentResource(String name, String site, String tool, String type, InputStream content,
ResourceProperties properties) throws IdInvalidException, InconsistentException, IdUsedException, PermissionException,
OverQuotaException, ServerOverloadException
{
// ignore site if it is not valid
if (site == null || site.trim().equals(""))
{
return addAttachmentResource(name, type, content, properties);
}
site = site.trim();
String siteId = Validator.escapeResourceName(site);
// if tool is not valid, use "_anon_"
if (tool == null || tool.trim().equals(""))
{
tool = "_anon_";
}
tool = tool.trim();
String toolId = Validator.escapeResourceName(tool);
// make sure the name is valid
Validator.checkResourceId(name);
// resource must also NOT end with a separator characters (we fix it)
if (name.endsWith(Entity.SEPARATOR))
{
name = name.substring(0, name.length() - 1);
}
String siteCollection = ATTACHMENTS_COLLECTION + siteId + Entity.SEPARATOR;
try
{
checkCollection(siteCollection);
}
catch (Exception e)
{
// add this collection
ContentCollectionEdit siteEdit = addCollection(siteCollection);
try
{
String siteTitle = m_siteService.getSite(site).getTitle();
siteEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, siteTitle);
}
catch (Exception e1)
{
siteEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, site);
}
commitCollection(siteEdit);
}
String toolCollection = siteCollection + toolId + Entity.SEPARATOR;
try
{
checkCollection(toolCollection);
}
catch (Exception e)
{
// add this collection
ContentCollectionEdit toolEdit = addCollection(toolCollection);
toolEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, tool);
commitCollection(toolEdit);
}
// form a name based on the attachments collection, a unique folder id, and the given name
String collection = toolCollection + idManager.createUuid() + Entity.SEPARATOR;
String id = collection + name;
if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new RuntimeException(ID_LENGTH_EXCEPTION);
}
// add this collection
ContentCollectionEdit edit = addCollection(collection);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
commitCollection(edit);
// and add the resource
return addResource(id, type, content, properties, new ArrayList(), NotificationService.NOTI_NONE);
} // addAttachmentResource
/**
* Create a new resource as an attachment to some other resource in the system, locked for update. Must commitResource() to make official, or cancelResource() when done! The new resource will be placed into a newly created collecion in the attachment
* collection, with an auto-generated id, and given the specified resource name within this collection.
*
* @param name
* The name of the new resource, i.e. a partial id relative to the collection where it will live.
* @exception IdUsedException
* if the resource name is already in use (not likely, as the containing collection is auto-generated!)
* @exception IdInvalidException
* if the resource name is invalid.
* @exception InconsistentException
* if the containing collection (or it's containing collection...) does not exist.
* @exception PermissionException
* if the user does not have permission to add a collection, or add a member to a collection.
* @return a new ContentResource object.
*/
public ContentResourceEdit addAttachmentResource(String name) throws IdInvalidException, InconsistentException,
IdUsedException, PermissionException
{
// make sure the name is valid
Validator.checkResourceId(name);
// resource must also NOT end with a separator characters (we fix it)
if (name.endsWith(Entity.SEPARATOR))
{
name = name.substring(0, name.length() - 1);
}
// form a name based on the attachments collection, a unique folder id, and the given name
String collection = ATTACHMENTS_COLLECTION + idManager.createUuid() + Entity.SEPARATOR;
String id = collection + name;
// add this collection
ContentCollectionEdit edit = addCollection(collection);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
commitCollection(edit);
return addResource(id);
} // addAttachmentResource
/**
* check permissions for updateResource().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to updateResource(id), false if not.
*/
public boolean allowUpdateResource(String id)
{
return allowUpdate(id);
} // allowUpdateResource
/**
* Update the body and or content type of an existing resource with the given resource id.
*
* @param id
* The id of the resource.
* @param type
* The mime type string of the resource (if null, no change).
* @param content
* An array containing the bytes of the resource's content (if null, no change).
* @exception PermissionException
* if the user does not have permission to add a resource to the containing collection or write the resource.
* @exception IdUnusedException
* if the resource id is not defined.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception OverQuotaException
* if this would result in being over quota.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @return a new ContentResource object.
*/
public ContentResource updateResource(String id, String type, byte[] content) throws PermissionException, IdUnusedException,
TypeException, InUseException, OverQuotaException, ServerOverloadException
{
// find a resource that is this resource
ContentResourceEdit edit = editResource(id);
edit.setContentType(type);
edit.setContent(content);
// commit the change
commitResource(edit, NotificationService.NOTI_NONE);
return edit;
} // updateResource
/**
* Access the resource with this resource id, locked for update. For non-collection resources only. Must commitEdit() to make official, or cancelEdit() when done! The resource content and properties are accessible from the returned Resource object.
*
* @param id
* The id of the resource.
* @exception PermissionException
* if the user does not have permissions to read the resource or read through any containing collection.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @return the ContentResource object found.
*/
public ContentResourceEdit editResource(String id) throws PermissionException, IdUnusedException, TypeException, InUseException
{
// check security (throws if not permitted)
checkExplicitLock(id);
// check security
if ( ! allowUpdateResource(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_WRITE_ANY, getReference(id));
// check for existance
if (!m_storage.checkResource(id))
{
throw new IdUnusedException(id);
}
// ignore the cache - get the collection with a lock from the info store
BaseResourceEdit resource = (BaseResourceEdit) m_storage.editResource(id);
if (resource == null) throw new InUseException(id);
resource.setEvent(EVENT_RESOURCE_WRITE);
threadLocalManager.set(String.valueOf(resource), resource);
ResourceProperties props = resource.getProperties();
if(props != null) {
resource.setOldDisplayName(props.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
}
return resource;
} // editResource
/**
* Access the resource with this resource id, locked for update. For non-collection resources only. Must commitEdit() to make official, or cancelEdit() when done! The resource content and properties are accessible from the returned Resource object.
*
* @param id
* The id of the resource.
* @exception PermissionException
* if the user does not have permissions to read the resource or read through any containing collection.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @return the ContentResource object found.
*/
public ContentResourceEdit editDeletedResource(String id) throws PermissionException, IdUnusedException, TypeException, InUseException
{
// check security
// if ( ! allowUpdateResource(id) )
// throw new PermissionException(SessionManager.getCurrentSessionUserId(),
// AUTH_RESOURCE_WRITE_ANY, getReference(id));
// ignore the cache - get the collection with a lock from the info store
BaseResourceEdit resource = (BaseResourceEdit) m_storage.editDeletedResource(id);
if (resource == null) throw new InUseException(id);
resource.setEvent(EVENT_RESOURCE_WRITE);
return resource;
} // editResource
/**
* Access the resource with this resource id, locked for update. For non-collection resources only. Must commitEdit() to make official, or cancelEdit() when done! The resource content and properties are accessible from the returned Resource object.
*
* @param id
* The id of the resource.
* @exception PermissionException
* if the user does not have permissions to read the resource or read through any containing collection.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @return the ContentResource object found.
*/
protected ContentResourceEdit editResourceForDelete(String id) throws PermissionException, IdUnusedException, TypeException, InUseException
{
// check security (throws if not permitted)
checkExplicitLock(id);
// check security
if ( ! allowRemoveResource(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_REMOVE_ANY, getReference(id));
// check for existance
if (!m_storage.checkResource(id))
{
throw new IdUnusedException(id);
}
// ignore the cache - get the collection with a lock from the info store
BaseResourceEdit resource = (BaseResourceEdit) m_storage.editResource(id);
if (resource == null) throw new InUseException(id);
resource.setEvent(EVENT_RESOURCE_REMOVE);
threadLocalManager.set(String.valueOf(resource), resource);
return resource;
} // editResourceForDelete
/**
* check permissions for getResource().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to getResource(id), false if not.
*/
public boolean allowGetResource(String id)
{
return unlockCheck(AUTH_RESOURCE_READ, id);
} // allowGetResource
/**
* Check access to the resource with this local resource id. For non-collection resources only.
*
* @param id
* The id of the resource.
* @exception PermissionException
* if the user does not have permissions to read the resource or read through any containing collection.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
*/
public void checkResource(String id) throws PermissionException, IdUnusedException, TypeException
{
// check security
unlock(AUTH_RESOURCE_READ, id);
ContentResource resource = findResource(id);
if (resource == null) throw new IdUnusedException(id);
} // checkResource
/**
* Access the resource with this resource id. For non-collection resources only. The resource content and properties are accessible from the returned Resource object.
*
* @param id
* The resource id.
* @exception PermissionException
* if the user does not have permissions to read the resource or read through any containing collection.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @return the ContentResource object found.
*/
public ContentResource getResource(String id) throws PermissionException, IdUnusedException, TypeException
{
// check security
unlock(AUTH_RESOURCE_READ, id);
ContentResource resource = findResource(id);
if (resource == null) throw new IdUnusedException(id);
// track event
// EventTrackingService.post(EventTrackingService.newEvent(EVENT_RESOURCE_READ, resource.getReference(), false));
return resource;
} // getResource
/**
* Access the collection with this local resource id, locked for update. Must commitCollection() to make official, or cancelCollection() when done! The collection internal members and properties are accessible from the returned Collection object.
*
* @param id
* The id of the collection.
* @exception IdUnusedException
* if the id does not exist.
* @exception TypeException
* if the resource exists but is not a collection.
* @exception PermissionException
* if the user does not have permissions to see this collection (or read through containing collections).
* @exception InUseException
* if the Collection is locked by someone else.
* @return The ContentCollection object found.
*/
public ContentCollectionEdit editCollection(String id) throws IdUnusedException, TypeException, PermissionException,
InUseException
{
checkExplicitLock(id);
// check security
if ( ! allowUpdateCollection(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_WRITE_ANY, getReference(id));
// check for existance
if (!m_storage.checkCollection(id))
{
throw new IdUnusedException(id);
}
// ignore the cache - get the collection with a lock from the info store
BaseCollectionEdit collection = (BaseCollectionEdit) m_storage.editCollection(id);
if (collection == null) throw new InUseException(id);
collection.setEvent(EVENT_RESOURCE_WRITE);
threadLocalManager.set(String.valueOf(collection), collection);
return collection;
} // editCollection
/**
* Access the resource with this resource id. For non-collection resources only. Internal find that doesn't do security or event tracking The resource content and properties are accessible from the returned Resource object.
*
* @param id
* The resource id.
* @exception TypeException
* if the resource is a collection.
* @return the ContentResource object found, or null if there's a problem.
*/
protected ContentResource findResource(String id) throws TypeException
{
ContentResource resource = null;
try
{
resource = (ContentResource) threadLocalManager.get("findResource@" + id);
}
catch(ClassCastException e)
{
throw new TypeException(id);
}
if(resource == null)
{
resource = m_storage.getResource(id);
if(resource != null)
{
threadLocalManager.set("findResource@" + id, resource); // new BaseResourceEdit(resource));
}
}
else
{
resource = new BaseResourceEdit(resource);
}
return resource;
} // findResource
/**
* check permissions for removeResource().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to removeResource(id), false if not.
*/
public boolean allowRemoveResource(String id)
{
// check security
boolean isAllowed = allowRemove(id);
if(isAllowed)
{
try
{
checkExplicitLock(id);
}
catch(PermissionException e)
{
isAllowed = false;
}
}
return isAllowed;
} // allowRemoveResource
/**
* Remove a resource. For non-collection resources only.
*
* @param id
* The resource id.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
*/
public void removeResource(String id) throws PermissionException, IdUnusedException,
TypeException, InUseException
{
BaseResourceEdit edit = (BaseResourceEdit) editResourceForDelete(id);
try
{
removeResource(edit);
}
finally
{
// If the edit wasn't committed unlock the resource.
if (edit.isActiveEdit())
{
cancelResource(edit);
}
}
} // removeResource
/**
* Remove a resource that is locked for update.
*
* @param edit
* The ContentResourceEdit object to remove.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
*/
public void removeResource(ContentResourceEdit edit) throws PermissionException {
removeResource(edit, true);
}
/**
* Allows removing a resource while leaving the content alone,
* this mostly matters for resources copied by reference
*
* @param edit
* The ContentResourceEdit object to remove.
* @param removeContent if true, removes the content as well (default),
* else only removes the resource record from the DB
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
*/
protected void removeResource(ContentResourceEdit edit, boolean removeContent) throws PermissionException
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("removeResource(): closed ContentResourceEdit", e);
return;
}
String id = edit.getId();
// check security (throws if not permitted)
checkExplicitLock(id);
if ( ! allowRemoveResource(edit.getId()) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_REMOVE_ANY, edit.getReference());
// htripath -store the metadata information into a delete table
// assumed uuid is not null as checkExplicitLock(id) throws exception when null
try {
String uuid = this.getUuid(id);
String userId = sessionManager.getCurrentSessionUserId().trim();
addResourceToDeleteTable(edit, uuid, userId);
edit.setContentLength(0); // we stop removing it entry from the DB
} catch (ServerOverloadException soe) {
M_log.debug("removeResource: could not save deleted resource, restore for this resource is not possible " + soe );
}
// complete the edit
m_storage.removeResource(edit, removeContent);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
if(! readyToUseFilesizeColumn())
{
removeSizeCache(edit);
}
((BaseResourceEdit) edit).setRemoved();
// remove old version of this edit from thread-local cache
threadLocalManager.set("findResource@" + edit.getId(), null);
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(edit.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.debug("removeResource: removing realm for : " + edit.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
M_log.debug("removeResource: removing realm for : " + edit.getReference() + " : " + ignore);
}
// track it (no notification)
String ref = edit.getReference(null);
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_REMOVE, ref, true,
NotificationService.NOTI_NONE));
eventTrackingService.cancelDelays(ref);
} // removeResource
public void removeDeletedResource(String id) throws PermissionException, IdUnusedException, TypeException, InUseException
{
BaseResourceEdit edit = (BaseResourceEdit) editDeletedResource(id);
removeDeletedResource(edit);
} // removeResource
/**
* Remove a resource from the deleted table.
*
* @param edit
* The ContentResourceEdit object to remove.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
*/
public void removeDeletedResource(ContentResourceEdit edit) throws PermissionException
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("removeDeletedResource(): closed ContentResourceEdit", e);
return;
}
// check security (throws if not permitted)
// if ( ! allowRemoveResource(edit.getId()) )
// throw new PermissionException(SessionManager.getCurrentSessionUserId(),
// AUTH_RESOURCE_REMOVE_ANY, edit.getReference());
//
// complete the edit
m_storage.removeDeletedResource(edit);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
((BaseResourceEdit) edit).setRemoved();
// remove old version of this edit from thread-local cache
threadLocalManager.set("findResource@" + edit.getId(), null);
// remove any realm defined for this resource
try
{
m_authzGroupService.removeAuthzGroup(m_authzGroupService.getAuthzGroup(edit.getReference()));
}
catch (AuthzPermissionException e)
{
M_log.debug("removeResource: removing realm for : " + edit.getReference() + " : " + e);
}
catch (GroupNotDefinedException ignore)
{
M_log.debug("removeResource: removing realm for : " + edit.getReference() + " : " + ignore);
}
} // removeDeletedResource
public void restoreResource(String id) throws PermissionException, IdUsedException, IdUnusedException,
IdInvalidException, InconsistentException, OverQuotaException, ServerOverloadException,
TypeException, InUseException
{
ContentResourceEdit deleResource = null;
try {
deleResource = editDeletedResource(id);
ContentResourceEdit newResource;
try {
newResource = addResource(id);
} catch (IdUsedException iue) {
M_log.error("restoreResource: cannot restore resource " + id, iue);
throw iue;
}
newResource.setContentType(deleResource.getContentType());
newResource.setContentLength(deleResource.getContentLength());
newResource.setResourceType(deleResource.getResourceType());
newResource.setAvailability(deleResource.isHidden(), deleResource.getReleaseDate(),deleResource.getRetractDate());
newResource.setContent(m_storage.streamDeletedResourceBody(deleResource));
try {
addProperties(newResource.getPropertiesEdit(), deleResource.getProperties());
commitResource(newResource, NotificationService.NOTI_NONE);
} catch (ServerOverloadException e) {
M_log.debug("ServerOverloadException " + e);
try
{
removeResource(newResource.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + newResource.getId() + "\n" + e1);
}
throw e;
} catch (OverQuotaException e) {
M_log.debug("OverQuotaException " + e);
try
{
removeResource(newResource.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + newResource.getId() + "\n" + e1);
}
throw e;
}
try {
// If you're storing the file in DB this breaks as it removes the restored file.
removeDeletedResource(deleResource);
// close the edit object
((BaseResourceEdit) deleResource).closeEdit();
} catch (PermissionException pe) {
M_log.error("restoreResource: access to resource not permitted" + id, pe);
try
{
removeResource(newResource.getId());
}
catch(Exception e1)
{
// ignore -- no need to remove the resource if it doesn't exist
M_log.debug("Unable to remove partially completed resource: " + deleResource.getId() + "\n" + e1);
}
throw pe;
}
} catch (IdUnusedException iue) {
M_log.error("restoreResource: cannot locate deleted resource " + id, iue);
throw iue;
} catch (TypeException te) {
M_log.error("restoreResource: invalid type " + id, te);
throw te;
} catch (InUseException ie) {
M_log.error("restoreResource: resource in use " + id, ie);
throw ie;
} catch (PermissionException pe) {
M_log.error("restoreResource: access to resource not permitted" + id, pe);
throw pe;
} finally {
// Unlock if something went wrong.
if (deleResource != null && deleResource.isActiveEdit()) {
m_storage.cancelDeletedResource(deleResource);
}
}
}
/**
* Store the resource in a separate delete table
*
* @param edit
* @param uuid
* @param userId
* @exception PermissionException
* @exception ServerOverloadException
* if server is configured to save resource body in filesystem and attempt to read from filesystem fails.
*/
public void addResourceToDeleteTable(ContentResourceEdit edit, String uuid, String userId) throws PermissionException, ServerOverloadException
{
if (m_bodyPathDeleted == null) {
return;
}
String id = edit.getId();
String content_type = edit.getContentType();
String resource_type = edit.getResourceType();
// KNL-245 do not read the resource body, as this is not subsequently written out
ResourceProperties properties = edit.getProperties();
InputStream content = null;
try
{
content = edit.streamContent();
addDeleteResource(id,
content_type, content, resource_type, edit.getReleaseDate(), edit.getRetractDate(),
properties, uuid, userId,
NotificationService.NOTI_OPTIONAL);
}
finally
{
if (content != null)
{
try
{
content.close();
}
catch (IOException e)
{
M_log.error("Failed to close when saving deleted content stream.", e);
}
}
}
}
public ContentResource addDeleteResource(String id, String type, InputStream inputStream, String resourceType, Time releaseDate, Time retractDate, ResourceProperties properties, String uuid, String userId, int priority) throws PermissionException, ServerOverloadException
{
id = (String) fixTypeAndId(id, type).get("id");
// resource must also NOT end with a separator characters (fix it)
if (id.endsWith(Entity.SEPARATOR))
{
id = id.substring(0, id.length() - 1);
}
// check security-unlock to add record
unlock(AUTH_RESOURCE_ADD, id);
// In the future we may wish to allow multiple copies of the file in the recycle bin.
// Remove Deleted Resource prevents id collision as #restoreResource(String) doesn't allow you to
// specify which version of a file you want to restore.
try {
removeDeletedResource(id);
} catch (Exception ex) {
// There is no collision
}
// reserve the resource in storage - it will fail if the id is in use
BaseResourceEdit edit = (BaseResourceEdit) m_storage.putDeleteResource(id, uuid, userId);
// added for NPE static code review -AZ
if (edit == null) {
throw new NullPointerException("putDeleteResource returned a null value, this is unrecoverable");
}
// add live properties-do we need this? - done to have uniformity with main table
addLiveResourceProperties(edit);
// track event - do we need this? no harm to keep track
edit.setEvent(EVENT_RESOURCE_ADD);
edit.setContentType(type);
edit.setResourceType(resourceType);
edit.setReleaseDate(releaseDate);
edit.setRetractDate(retractDate);
if (inputStream != null)
{
edit.setContent(inputStream);
}
addProperties(edit.getPropertiesEdit(), properties);
// complete the edit - update xml which contains properties xml and store the file content
m_storage.commitDeletedResource(edit, uuid);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
return edit;
} // addDeleteResource
/**
* check permissions for rename(). Note: for just this collection, not the members on down.
*
* @param id
* The id of the collection.
* @return true if the user is allowed to rename(id), false if not.
*/
public boolean allowRename(String id, String new_id)
{
// check security for remove resource (own or any)
boolean allowed = false;
if ( allowRemove(id) ) {
// check security for read resource
if ( unlockCheck(AUTH_RESOURCE_READ, id) ) {
// check security for add resource
if ( unlockCheck(AUTH_RESOURCE_ADD, new_id) ) {
allowed = true;
}
}
}
if (M_log.isDebugEnabled()) M_log.debug("content allowRename("+id+", "+new_id+") = "+allowed);
return allowed;
// return unlockCheck(AUTH_RESOURCE_ADD, new_id) &&
// unlockCheck(AUTH_RESOURCE_REMOVE, id);
} // allowRename
/**
* Rename a collection or resource.
*
* @param id
* The id of the collection.
* @param new_id
* The desired id of the collection.
* @return The full id of the resource after the rename is completed.
* @exception IdUnusedException
* if the id does not exist.
* @exception TypeException
* if the resource exists but is not a collection or resource.
* @exception PermissionException
* if the user does not have permissions to rename
* @exception InUseException
* if the id or a contained member is locked by someone else. collections, or remove any members of the collection.
* @exception IdUsedException
* if copied item is a collection and the new id is already in use or if the copied item is not a collection and a unique id cannot be found in some arbitrary number of attempts (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @deprecated DO NOT USE THIS, it does not work and will ALWAYS throw an UnsupportedOperationException - https://jira.sakaiproject.org/browse/KNL-1078
*/
public String rename(String id, String new_id) throws IdUnusedException, TypeException, PermissionException, InUseException,
OverQuotaException, InconsistentException, IdUsedException, ServerOverloadException
{
throw new UnsupportedOperationException("the rename() method is not properly implemented and should NOT be used - https://jira.sakaiproject.org/browse/KNL-1078");
/* Commented out for https://jira.sakaiproject.org/browse/KNL-1078
*
// Note - this could be implemented in this base class using a copy and a delete
// and then overridden in those derived classes which can support
// a direct rename operation.
// check security for remove resource (own or any)
if ( ! allowRemove(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_REMOVE_ANY, getReference(id));
// check security for read resource
unlock(AUTH_RESOURCE_READ, id);
// check security for add resource
unlock(AUTH_RESOURCE_ADD, new_id);
boolean isCollection = false;
ContentResourceEdit thisResource = null;
ContentCollectionEdit thisCollection = null;
if (M_log.isDebugEnabled()) M_log.debug("rename(" + id + "," + new_id + ")");
if (m_storage.checkCollection(id))
{
isCollection = true;
// find the collection
thisCollection = editCollection(id);
if (isRootCollection(id))
{
cancelCollection(thisCollection);
throw new PermissionException(sessionManager.getCurrentSessionUserId(), null, null);
}
}
else
{
thisResource = editResource(id);
}
if (thisResource == null && thisCollection == null)
{
throw new IdUnusedException(id);
}
// makes a copy each time content is renamed
if (isCollection) {
// NOTE: this does NOT do a deep copy (i.e. the collection is copied but the content is not)
new_id = copyCollection(thisCollection, new_id);
removeCollection(thisCollection);
} else {
// rename should do a reference copy only and not remove the content after
new_id = copyResource(thisResource, new_id, true); // set referenceCopy
removeResource(thisResource, false); // force content to not be removed
}
return new_id;
*/
} // rename
/**
* check permissions for copy().
*
* @param id
* The id of the new resource.
* @param new_id
* The desired id of the new resource.
* @return true if the user is allowed to copy(id,new_id), false if not.
*/
public boolean allowCopy(String id, String new_id)
{
return unlockCheck(AUTH_RESOURCE_ADD, new_id) && unlockCheck(AUTH_RESOURCE_READ, id);
}
/**
* Copy a collection or resource from one location to another. Creates a new collection with an id similar to new_folder_id and recursively copies all nested collections and resources within thisCollection to the new collection.
*
* @param id
* The id of the resource.
* @param folder_id
* The id of the folder in which the copy should be created.
* @return The full id of the new copy of the resource.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception IdLengthException
* if the new id of the copied item (or any nested item) is longer than the maximum length of an id.
* @exception InconsistentException
* if the destination folder (folder_id) is contained within the source folder (id).
* @exception IdUsedException
* if a unique resource id cannot be found after some arbitrary number of attempts (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
*/
public String copyIntoFolder(String id, String folder_id) throws PermissionException, IdUnusedException, TypeException,
InUseException, IdLengthException, IdUniquenessException, OverQuotaException, InconsistentException, IdUsedException,
ServerOverloadException
{
if (folder_id.startsWith(id))
{
throw new InconsistentException(id + " is contained within " + folder_id);
}
String new_id = newName(id, folder_id);
if (new_id.length() >= MAXIMUM_RESOURCE_ID_LENGTH)
{
throw new IdLengthException(new_id);
}
// Should use copyIntoFolder if possible
boolean isCollection = false;
ContentResource thisResource = null;
if (M_log.isDebugEnabled()) M_log.debug("copy(" + id + "," + new_id + ")");
// find the collection
ContentCollection thisCollection = null;
try
{
thisCollection = getCollection(id);
}
catch (TypeException e)
{
thisCollection = null;
}
catch (IdUnusedException e)
{
thisCollection = null;
}
if (thisCollection == null)
{
thisResource = getResource(id);
}
else
{
isCollection = true;
if (isRootCollection(id))
{
throw new PermissionException(null, null, null);
}
}
if (thisResource == null && thisCollection == null)
{
throw new IdUnusedException(id);
}
if (isCollection)
{
new_id = deepcopyCollection(thisCollection, new_id);
}
else
{
new_id = copyResource(thisResource, new_id);
}
return new_id;
}
/**
* Calculate a candidate for a resource id for a resource being copied/moved into a new folder.
*
* @param id
* @param folder_id
* @exception PermissionException
* if the user does not have permissions to read the properties for the existing resource.
* @exception IdUnusedException
* if the resource id is not found.
*/
protected String newName(String id, String folder_id) throws PermissionException, IdUnusedException
{
String filename = isolateName(id);
if (filename == null || filename.length() == 0)
{
ResourceProperties props = getProperties(id);
filename = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
filename = Validator.escapeResourceName(filename);
if(! folder_id.endsWith(Entity.SEPARATOR))
{
folder_id += Entity.SEPARATOR;
}
return folder_id + filename;
}
/**
* Move a resource or collection to a (different) folder. This may be accomplished by renaming the resource or by recursively renaming the collection and all enclosed members (no matter how deep) to effectively change their locations. Alternatively,
* it may be accomplished by copying the resource and recursively copying collections from their existing collection to the new collection and ultimately deleting the original resource(s) and/or collections(s).
*
* @param id
* The id of the resource or collection to be moved.
* @param folder_id
* The id of the folder to which the resource should be moved.
* @return The full id of the resource after the move is completed.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception InconsistentException
* if the containing collection does not exist.
* @exception InconsistentException
* if the destination folder (folder_id) is contained within the source folder (id).
* @exception IdUsedException
* if a unique resource id cannot be found after some arbitrary number of attempts (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
*/
public String moveIntoFolder(String id, String folder_id) throws PermissionException, IdUnusedException, TypeException,
InUseException, OverQuotaException, IdUsedException, InconsistentException, ServerOverloadException
{
if (folder_id.startsWith(id))
{
throw new InconsistentException(id + " is contained within " + folder_id);
}
String new_id = newName(id, folder_id);
// check security for delete existing resource (any or own)
if ( ! allowRemove(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_REMOVE_ANY, getReference(id));
// check security for read existing resource
unlock(AUTH_RESOURCE_READ, id);
// check security for add new resource
unlock(AUTH_RESOURCE_ADD, new_id);
boolean isCollection = false;
ContentResourceEdit thisResource = null;
ContentCollectionEdit thisCollection = null;
if (M_log.isDebugEnabled()) M_log.debug("moveIntoFolder(" + id + "," + new_id + ")");
if (m_storage.checkCollection(id))
{
isCollection = true;
// find the collection
thisCollection = editCollection(id);
if (isRootCollection(id))
{
cancelCollection(thisCollection);
throw new PermissionException(sessionManager.getCurrentSessionUserId(), null, null);
}
}
else
{
thisResource = editResource(id);
}
if (thisResource == null && thisCollection == null)
{
throw new IdUnusedException(id);
}
if (isCollection)
{
new_id = moveCollection(thisCollection, new_id);
}
else
{
new_id = moveResource(thisResource, new_id);
}
return new_id;
} // moveIntoFolder
/**
* Move a collection to a new folder. Moves the existing collection or creates a new collection with an id similar to the new_folder_id (in which case the original collection is removed) and recursively moves all nested collections and resources
* within thisCollection to the new collection. When finished, thisCollection no longer exists, but the collection identified by the return value has the same structure and all of the members the original had (or copies of them).
*
* @param thisCollection
* The collection to be copied
* @param new_folder_id
* The desired id of the collection after it is moved.
* @return The full id of the moved collection.
* @exception PermissionException
* if the user does not have permissions to perform the operations
* @exception IdUnusedException
* if the collection id is not found.
* @exception TypeException
* if the resource is not a collection.
* @exception InUseException
* if the collection is locked by someone else.
* @exception IdUsedException
* if a unique resource id cannot be found after some arbitrary number of attempts to find a unique variation of the new_id (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to save content bodies in the server's filesystem and an error occurs trying to access the filesystem.
*/
protected String moveCollection(ContentCollectionEdit thisCollection, String new_folder_id) throws PermissionException,
IdUnusedException, TypeException, InUseException, OverQuotaException, IdUsedException, ServerOverloadException
{
String name = isolateName(new_folder_id);
ResourceProperties properties = thisCollection.getProperties();
ResourcePropertiesEdit newProps = duplicateResourceProperties(properties, thisCollection.getId());
// newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
String displayName = newProps.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if (displayName == null && name != null)
{
newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
displayName = name;
}
if (M_log.isDebugEnabled()) M_log.debug("moveSCollection adding colletion=" + new_folder_id + " name=" + name);
String base_id = new_folder_id + "-";
boolean still_trying = true;
int attempt = 0;
try
{
while (still_trying && attempt < MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
try
{
ContentCollection newCollection = addCollection(new_folder_id, newProps);
// use the creator and creation-date of the original instead of the copy
BaseCollectionEdit collection = (BaseCollectionEdit) m_storage.editCollection(newCollection.getId());
ResourcePropertiesEdit props = collection.getPropertiesEdit();
String creator = properties.getProperty(ResourceProperties.PROP_CREATOR);
if (creator != null && !creator.trim().equals(""))
{
props.addProperty(ResourceProperties.PROP_CREATOR, creator);
}
String created = properties.getProperty(ResourceProperties.PROP_CREATION_DATE);
if (created != null)
{
props.addProperty(ResourceProperties.PROP_CREATION_DATE, created);
}
if (isPubView(thisCollection.getId()))
{
collection.setPublicAccess();
}
collection.setAvailability(thisCollection.isHidden(), thisCollection.getReleaseDate(), thisCollection.getReleaseDate());
m_storage.commitCollection(collection);
if (M_log.isDebugEnabled()) M_log.debug("moveCollection successful");
still_trying = false;
}
catch (IdUsedException e)
{
try
{
getCollection(new_folder_id);
}
catch (Exception ee)
{
throw e;
}
attempt++;
if (attempt >= MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
throw e;
}
new_folder_id = base_id + attempt;
// newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name + "-" + attempt);
newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName + "-" + attempt);
}
}
List<String> members = thisCollection.getMembers();
if (M_log.isDebugEnabled()) M_log.debug("moveCollection size=" + members.size());
Iterator<String> memberIt = members.iterator();
while (memberIt.hasNext())
{
String member_id = (String) memberIt.next();
moveIntoFolder(member_id, new_folder_id);
}
removeCollection(thisCollection);
}
catch (InconsistentException e)
{
throw new TypeException(new_folder_id);
}
catch (IdInvalidException e)
{
throw new TypeException(new_folder_id);
}
return new_folder_id;
} // moveCollection
/**
* Move a resource to a new folder. Either creates a new resource with an id similar to the new_folder_id and and removes the original resource, or renames the resource with an id similar to the new id, which effectively moves the resource to a new
* location.
*
* @param thisResource
* The resource to be copied
* @param new_id
* The desired id of the resource after it is moved.
* @return The full id of the moved resource (which may be a variation on the new_id to ensure uniqueness within the new folder.
* @throws IllegalArgumentException if the new_id is null
* @exception PermissionException
* if the user does not have permissions to perform the operations
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception IdUsedException
* if a unique resource id cannot be found after some arbitrary number of attempts to find a unique variation of the new_id (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to save content bodies in the server's filesystem and an error occurs trying to access the filesystem.
*/
protected String moveResource(ContentResourceEdit thisResource, String new_id) throws PermissionException, IdUnusedException,
TypeException, InUseException, OverQuotaException, IdUsedException, ServerOverloadException
{
if (StringUtils.isBlank(new_id)) {
throw new IllegalArgumentException("new_id must not be null");
}
String fileName = isolateName(new_id);
String folderId = isolateContainingId(new_id);
ResourceProperties properties = thisResource.getProperties();
String displayName = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if (displayName == null)
{
displayName = fileName;
}
String new_displayName = displayName;
if (M_log.isDebugEnabled()) M_log.debug("moveResource displayname=" + new_displayName + " fileName=" + fileName);
String basename = fileName;
String extension = "";
int index = fileName.lastIndexOf(".");
if (index >= 0)
{
basename = fileName.substring(0, index);
extension = fileName.substring(index);
}
boolean still_trying = true;
int attempt = 0;
while (still_trying && attempt < MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
// copy the resource to the new location
try
{
ContentResourceEdit edit = addResource(new_id);
edit.setContentType(thisResource.getContentType());
// NOTE: we always do a reference copy on a move if we can
boolean referenceCopy = false;
if (edit instanceof BaseResourceEdit) {
((BaseResourceEdit)edit).setReferenceCopy(thisResource.getId());
// need to manually update the content length or it ends up as 0
((BaseResourceEdit)edit).setContentLength(thisResource.getContentLength());
// need to manually update the file path or it will be regenerated
((BaseResourceEdit) edit).m_filePath = ((BaseResourceEdit) thisResource).m_filePath;
referenceCopy = true;
} else {
edit.setContent(thisResource.streamContent());
}
edit.setResourceType(thisResource.getResourceType());
edit.setAvailability(thisResource.isHidden(), thisResource.getReleaseDate(), thisResource.getRetractDate());
//((BaseResourceEdit) edit).m_filePath = ((BaseResourceEdit) thisResource).m_filePath;
//((BaseResourceEdit) thisResource).m_filePath = null;
// Collection groups = thisResource.getGroups();
// if(groups == null || groups.isEmpty())
// {
// // do nothing
// }
// else
// {
// edit.setGroupAccess(groups);
// }
ResourcePropertiesEdit props = edit.getPropertiesEdit();
Iterator<String> nameIt = properties.getPropertyNames();
while(nameIt.hasNext())
{
String name = nameIt.next();
props.addProperty(name, properties.getProperty(name));
}
//addProperties(props, properties);
// String creator = properties.getProperty(ResourceProperties.PROP_CREATOR);
// if (creator != null && !creator.trim().equals(""))
// {
// props.addProperty(ResourceProperties.PROP_CREATOR, creator);
// }
// String created = properties.getProperty(ResourceProperties.PROP_CREATION_DATE);
// if (created != null)
// {
// props.addProperty(ResourceProperties.PROP_CREATION_DATE, created);
// }
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, new_displayName);
String oldUuid = getUuid(thisResource.getId());
setUuidInternal(new_id, oldUuid);
m_storage.commitResource(edit);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
// track it (no notification)
String ref = edit.getReference(null);
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_ADD, ref, true,
NotificationService.NOTI_NONE));
// TODO - we don't know whether to post a future notification or not
postAvailableEvent(edit, ref, NotificationService.NOTI_NONE);
// we need to not remove the content if we just did a reference copy above (or remove the content when there was no reference copy)
m_storage.removeResource(thisResource, !referenceCopy);
// track it (no notification)
String thisRef = thisResource.getReference(null);
eventTrackingService.cancelDelays(thisRef);
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_REMOVE, thisRef, true,
NotificationService.NOTI_NONE));
if (M_log.isDebugEnabled()) M_log.debug("moveResource successful");
still_trying = false;
}
catch (InconsistentException e)
{
throw new TypeException(new_id);
}
catch (IdInvalidException e)
{
throw new TypeException(new_id);
}
catch (IdUsedException e)
{
try
{
getResource(new_id);
}
catch (Exception ee)
{
throw e;
}
if (attempt >= MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
throw e;
}
attempt++;
new_id = folderId + basename + "-" + attempt + extension;
new_displayName = displayName + " (" + attempt + ")";
}
}
//removeResource(thisResource);
return new_id;
} // moveResource
/**
* Copy a resource or collection.
*
* @param id
* The id of the resource.
* @param new_id
* The desired id of the new resource.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception IdUsedException
* if copied item is a collection and the new id is already in use or if the copied item is not a collection and a unique id cannot be found in some arbitrary number of attempts (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @see copyIntoFolder(String, String) method (preferred method for invocation from a tool).
*/
public String copy(String id, String new_id) throws PermissionException, IdUnusedException, TypeException, InUseException,
OverQuotaException, IdUsedException, ServerOverloadException
{
// Should use copyIntoFolder if possible
boolean isCollection = false;
ContentResource thisResource = null;
if (M_log.isDebugEnabled()) M_log.debug("copy(" + id + "," + new_id + ")");
// find the collection
ContentCollection thisCollection = findCollection(id);
if (thisCollection != null)
{
isCollection = true;
if (isRootCollection(id))
{
throw new PermissionException(null, null, null);
}
}
else
{
thisResource = findResource(id);
}
if (thisResource == null && thisCollection == null)
{
throw new IdUnusedException(id);
}
if (isCollection)
{
new_id = copyCollection(thisCollection, new_id);
}
else
{
new_id = copyResource(thisResource, new_id);
}
return new_id;
}
/**
* Get a duplicate copy of resource properties This copies everything except for the DISPLAYNAME - DISPLAYNAME is only copied if it is different than the file name as derived from the id (path) Note to Chuck - should the add operations check for empty
* Display and set it to the file name rather than putting all the code all over the place.
*/
private ResourcePropertiesEdit duplicateResourceProperties(ResourceProperties properties, String id)
{
ResourcePropertiesEdit resourceProperties = newResourceProperties();
if (properties == null) return resourceProperties;
// loop through the properties
Iterator<String> propertyNames = properties.getPropertyNames();
while (propertyNames.hasNext())
{
String propertyName = (String) propertyNames.next();
String propertyValue = properties.getProperty(propertyName);
M_log.debug("copying: " + propertyName + " with value " + propertyValue);
resourceProperties.addProperty(propertyName, propertyValue);
} // while
return resourceProperties;
} // duplicateResourceProperties
/**
* Copy a resource.
*
* @param resource The resource to be copied
* @param new_id The desired id of the new resource.
* @return The full id of the new copy of the resource.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception OverQuotaException
* if copying the resource would exceed the quota.
* @exception IdUsedException
* if a unique id cannot be found in some arbitrary number of attempts (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
*/
public String copyResource(ContentResource resource, String new_id) throws PermissionException, IdUnusedException,
TypeException, InUseException, OverQuotaException, IdUsedException, ServerOverloadException
{
return copyResource(resource, new_id, false);
}
/**
* Copy a resource with an option to do a reference copy
*
* @param resource
* @param new_id
* @param referenceCopy if true, then do not copy the actual content (only make a reference copy which points to it),
* if false, then copy like normal (duplicate the content)
* @return The full id of the new copy of the resource.
* @exception PermissionException
* if the user does not have permissions to read a containing collection, or to remove this resource.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the resource is a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception OverQuotaException
* if copying the resource would exceed the quota.
* @exception IdUsedException
* if a unique id cannot be found in some arbitrary number of attempts (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
*/
protected String copyResource(ContentResource resource, String new_id, boolean referenceCopy) throws PermissionException, IdUnusedException,
TypeException, InUseException, OverQuotaException, IdUsedException, ServerOverloadException
{
if (M_log.isDebugEnabled())
{
M_log.debug("copyResource: " + resource.getId() + " to " + new_id + ", reference="+referenceCopy);
}
if (StringUtils.isBlank(new_id)) {
throw new IllegalArgumentException("new_id must not be null");
}
String fileName = isolateName(new_id);
fileName = Validator.escapeResourceName(fileName);
String folderId = isolateContainingId(new_id);
ResourceProperties properties = resource.getProperties();
String displayName = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if (displayName == null)
{
displayName = fileName;
}
String new_displayName = displayName;
if (M_log.isDebugEnabled()) M_log.debug("copyResource displayname=" + new_displayName + " fileName=" + fileName);
String basename = fileName;
String extension = "";
int index = fileName.lastIndexOf(".");
if (index >= 0)
{
basename = fileName.substring(0, index);
extension = fileName.substring(index);
}
boolean still_trying = true;
int attempt = 0;
boolean destIsDropBox=false;
while (still_trying && attempt < MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
// copy the resource to the new location
ContentResourceEdit edit = null;
try
{
edit = addResource(new_id);
// this duplicates a lot of the code from BaseResourceEdit.set()
edit.setContentType(resource.getContentType());
if (isInDropbox(edit.getId()))
{
M_log.debug("We are copying to a dropbox folder :"+ edit.getId());
destIsDropBox = true;
}
if (referenceCopy && edit instanceof BaseResourceEdit) {
// do a reference copy so the actual content is not duplicated
((BaseResourceEdit)edit).setReferenceCopy(resource.getId());
if (M_log.isDebugEnabled()) M_log.debug("copyResource doing a reference copy of "+resource.getId());
} else {
// use stream instead of byte array
// edit.setContent(resource.getContent());
edit.setContent(resource.streamContent());
if (M_log.isDebugEnabled()) M_log.debug("copyResource doing a normal copy");
}
edit.setResourceType(resource.getResourceType());
ResourcePropertiesEdit newProps = edit.getPropertiesEdit();
addProperties(newProps, properties);
newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, new_displayName);
// Collection groups = resource.getGroups();
// if(groups == null || groups.isEmpty())
// {
// // do nothing
// }
// else
// {
// edit.setGroupAccess(groups);
// }
edit.setAvailability(resource.isHidden(), resource.getReleaseDate(), resource.getRetractDate());
commitResource(edit,destIsDropBox ? NotificationService.NOTI_OPTIONAL: NotificationService.NOTI_NONE);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
if (M_log.isDebugEnabled()) M_log.debug("copyResource successful");
still_trying = false;
}
catch (InconsistentException e)
{
throw new TypeException(new_id);
}
catch (IdInvalidException e)
{
throw new TypeException(new_id);
}
catch (IdUsedException e)
{
try
{
getResource(new_id);
}
catch (Exception ee)
{
throw e;
}
if (attempt >= MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
throw e;
}
attempt++;
new_id = folderId + basename + "-" + attempt + extension;
new_displayName = displayName + " (" + attempt + ")";
// Could come up with a naming convention to add versions here
}
}
return new_id;
} // copyResource
/**
* Copy a collection.
*
* @param thisCollection
* The collection to be copied
* @param new_id
* The desired id of the new collection.
* @return The full id of the new copy of the resource.
* @exception PermissionException
* if the user does not have permissions to perform the operations OR the collection has members in it
* @exception IdUnusedException
* if the collection id is not found.
* @exception TypeException
* if the resource is not a collection.
* @exception InUseException
* if the resource is locked by someone else.
* @exception IdUsedException
* if the new collection id is already in use.
*/
public String copyCollection(ContentCollection thisCollection, String new_id) throws PermissionException, IdUnusedException,
TypeException, InUseException, OverQuotaException, IdUsedException
{
List members = thisCollection.getMemberResources();
if (M_log.isDebugEnabled()) M_log.debug("copyCollection size=" + members.size());
if (members.size() > 0)
{
// recurse to copy everything in the folder?
throw new PermissionException(null, null, null);
}
String name = isolateName(new_id);
ResourceProperties properties = thisCollection.getProperties();
ResourcePropertiesEdit newProps = duplicateResourceProperties(properties, thisCollection.getId());
newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
if (M_log.isDebugEnabled()) M_log.debug("copyCollection adding colletion=" + new_id + " name=" + name);
boolean isHidden = false;
if (isPubView(thisCollection.getId()))
{
isHidden = true;
}
try
{
addCollection(new_id, newProps, null, isHidden, null, null);
if (M_log.isDebugEnabled()) M_log.debug("copyCollection successful");
}
catch (InconsistentException e)
{
throw new TypeException(new_id);
}
catch (IdInvalidException e)
{
throw new TypeException(new_id);
}
/*
* catch (IdUsedException e) // Why is this the case?? { throw new PermissionException(null, null); }
*/
return new_id;
} // copyCollection
/**
* Make a deep copy of a collection.
* Creates a new collection with an id similar to new_folder_id and recursively copies all nested collections and resources within thisCollection to the new collection.
* Only used in "copyIntoFolder" for now
*
* @param thisCollection
* The collection to be copied
* @param new_folder_id
* The desired id of the new collection.
* @return The full id of the copied collection (which may be a slight variation on the desired id to ensure uniqueness).
* @exception PermissionException
* if the user does not have permissions to perform the operations
* @exception IdUnusedException
* if the collection id is not found. ???
* @exception TypeException
* if the resource is not a collection.
* @exception InUseException
* if the collection is locked by someone else.
* @exception IdUsedException
* if a unique id cannot be found for the new collection after some arbitrary number of attempts to find a unique variation of the new_folder_id (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
* @exception ServerOverloadException
* if the server is configured to save content bodies in the server's filesystem and an error occurs trying to access the filesystem.
*/
protected String deepcopyCollection(ContentCollection thisCollection, String new_folder_id) throws PermissionException,
IdUnusedException, TypeException, InUseException, IdLengthException, IdUniquenessException, OverQuotaException,
IdUsedException, ServerOverloadException
{
String name = isolateName(new_folder_id);
ResourceProperties properties = thisCollection.getProperties();
ResourcePropertiesEdit newProps = duplicateResourceProperties(properties, thisCollection.getId());
if(newProps.getProperty(ResourceProperties.PROP_DISPLAY_NAME) == null)
{
name = Validator.escapeResourceName(name);
newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
}
if (M_log.isDebugEnabled()) M_log.debug("deepCopyCollection adding colletion=" + new_folder_id + " name=" + name);
String base_id = new_folder_id + "-";
boolean still_trying = true;
int attempt = 0;
ContentCollection newCollection = null;
try
{
try
{
newCollection = addCollection(new_folder_id, newProps);
// use the creator and creation-date of the original instead of the copy
BaseCollectionEdit collection = (BaseCollectionEdit) m_storage.editCollection(newCollection.getId());
if (isPubView(thisCollection.getId()))
{
collection.setPublicAccess();
}
collection.setAvailability(thisCollection.isHidden(), thisCollection.getReleaseDate(), thisCollection.getReleaseDate());
m_storage.commitCollection(collection);
if (M_log.isDebugEnabled()) M_log.debug("deepCopyCollection top level created successful");
still_trying = false;
}
catch (IdUsedException e)
{
try
{
checkCollection(new_folder_id);
}
catch (Exception ee)
{
throw new IdUniquenessException(new_folder_id);
}
}
String containerId = this.isolateContainingId(new_folder_id);
ContentCollection containingCollection = findCollection(containerId);
SortedSet<String> siblings = new TreeSet<String>();
siblings.addAll(containingCollection.getMembers());
while (still_trying)
{
attempt++;
if (attempt >= MAXIMUM_ATTEMPTS_FOR_UNIQUENESS)
{
throw new IdUniquenessException(new_folder_id);
}
new_folder_id = base_id + attempt;
if (!siblings.contains(new_folder_id))
{
newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name + "-" + attempt);
try
{
newCollection = addCollection(new_folder_id, newProps);
BaseCollectionEdit collection = (BaseCollectionEdit) m_storage.editCollection(newCollection.getId());
if (isPubView(thisCollection.getId()))
{
collection.setPublicAccess();
}
collection.setAvailability(thisCollection.isHidden(), thisCollection.getReleaseDate(), thisCollection.getReleaseDate());
m_storage.commitCollection(collection);
still_trying = false;
}
catch (IdUsedException inner_e)
{
// try again
}
}
}
List<String> members = thisCollection.getMembers();
if (M_log.isDebugEnabled()) M_log.debug("deepCopyCollection size=" + members.size());
Iterator<String> memberIt = members.iterator();
while (memberIt.hasNext())
{
String member_id = (String) memberIt.next();
if (isAvailable(member_id)){
copyIntoFolder(member_id, new_folder_id);
}
}
}
catch (InconsistentException e)
{
throw new TypeException(new_folder_id);
}
catch (IdInvalidException e)
{
throw new TypeException(new_folder_id);
}
return new_folder_id;
} // deepcopyCollection
private boolean hasContentType(String resourceId) {
String contentType = null;
try {
contentType = getResource(resourceId).getContentType();
} catch (PermissionException e) {
} catch (IdUnusedException e) {
} catch (TypeException e) {
}
return contentType != null && !contentType.isEmpty();
}
/**
* Commit the changes made, and release the lock. The Object is disabled, and not to be used after this call.
*
* @param edit
* The ContentResourceEdit object to commit.
* @exception OverQuotaException
* if this would result in being over quota (the edit is then cancled).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @exception PermissionException
* if the user is trying to make a change for which they lack permission.
*/
public void commitResource(ContentResourceEdit edit) throws OverQuotaException, ServerOverloadException
{
commitResource(edit, NotificationService.NOTI_OPTIONAL);
} // commitResource
/**
* Commit the changes made, and release the lock. The Object is disabled, and not to be used after this call.
*
* @param edit
* The ContentResourceEdit object to commit.
* @param priority
* The notification priority of this commit.
* @exception OverQuotaException
* if this would result in being over quota (the edit is then cancled).
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
*/
public void commitResource(ContentResourceEdit edit, int priority) throws OverQuotaException, ServerOverloadException, VirusFoundException
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("commitResource(): closed ContentResourceEdit", e);
return;
}
boolean hasContentTypeAlready = hasContentType(edit.getId());
//use magic to fix mimetype
//Don't process for special TYPE_URL type
String currentContentType = edit.getContentType();
m_useMimeMagic = m_serverConfigurationService.getBoolean("content.useMimeMagic", m_useMimeMagic);
m_ignoreExtensions = Arrays.asList(ArrayUtils.nullToEmpty(m_serverConfigurationService.getStrings("content.mimeMagic.ignorecontent.extensions")));
m_ignoreMimeTypes = Arrays.asList(ArrayUtils.nullToEmpty(m_serverConfigurationService.getStrings("content.mimeMagic.ignorecontent.mimetypes")));
if (m_useMimeMagic && DETECTOR != null && !ResourceProperties.TYPE_URL.equals(currentContentType) && !hasContentTypeAlready) {
try{
//we have to make the stream resetable so tika can read some of it and reset for saving.
//Also have to give the tika stream to the edit object since tika can invalidate the original
//stream and replace it with a new stream.
TikaInputStream buff = TikaInputStream.get(edit.streamContent());
edit.setContent(buff);
final Metadata metadata = new Metadata();
//This might not want to be set as it would advise the detector
metadata.set(Metadata.RESOURCE_NAME_KEY, edit.getId());
metadata.set(Metadata.CONTENT_TYPE, currentContentType);
String newmatch = "";
//If we are ignoring the content for this extension, don't give it any data
if (m_ignoreExtensions != null && m_ignoreExtensions.contains(FilenameUtils.getExtension(edit.getId()))) {
newmatch = DETECTOR.detect(null, metadata).toString();
}
else {
newmatch = DETECTOR.detect(TikaInputStream.get(buff), metadata).toString();
//Redetect without the content as we're ignoring this mime type
if (m_ignoreMimeTypes != null && m_ignoreMimeTypes.contains(newmatch)) {
newmatch = DETECTOR.detect(null, metadata).toString();
}
}
if (M_log.isDebugEnabled()) {
M_log.debug("Magic: Setting content type from " + currentContentType + " to " + newmatch);
}
edit.setContentType(newmatch);
} catch (Exception e) {
M_log.warn("Exception when trying to get the resource's data: " + e);
}
}
commitResourceEdit(edit, priority);
// Queue up content for virus scanning
if (virusScanner.getEnabled()) {
virusScanQueue.add(edit.getId());
}
/**
* check for over quota.
* We do this after the commit so we can actual tell its size
*/
if (overQuota(edit))
{
try {
//the edit is closed so we need to refetch it
ContentResourceEdit edit2 = editResource(edit.getId());
removeResource(edit2);
} catch (PermissionException e1) {
// we're unlikely to see this at this point
e1.printStackTrace();
} catch (IdUnusedException e1) {
// we're unlikely to see this at this point
e1.printStackTrace();
} catch (TypeException e1) {
// we're unlikely to see this at this point
e1.printStackTrace();
} catch (InUseException e1) {
// we're unlikely to see this at this point
e1.printStackTrace();
}
throw new OverQuotaException(edit.getReference());
}
if(! readyToUseFilesizeColumn())
{
addSizeCache(edit);
}
} // commitResource
/**
* This timer task is run by the timer thread based on the period set above
*/
protected class VirusTimerTask extends TimerTask {
public void run() {
try {
M_log.debug("running timer task");
enableAzgSecurityAdvisor();
processVirusQueue();
} catch (Exception e) {
M_log.error("Virus scan failure: " + e.getMessage(), e);
} finally {
disableAzgSecurityAdvisor();
}
}
}
public void processVirusQueue() {
// grab the queue - any new stuff will be processed next time
List<String> queue = new Vector();
synchronized (virusScanQueue)
{
queue.addAll(virusScanQueue);
virusScanQueue.clear();
}
Session session = sessionManager.getCurrentSession();
for (String contentId : queue) {
// process the queue of digest requests
try {
virusScanner.scanContent(contentId);
} catch (VirusFoundException e) {
//this file is infected we need to remove if
ContentResourceEdit edit2 = null;
try {
//the edit is closed so we need to refetch it
edit2 = editResource(contentId);
ResourceProperties props = edit2.getProperties();
// we need to set the session userId or removeResource fails
String owner = props.getProperty(ResourceProperties.PROP_CREATOR);
User user = userDirectoryService.getUser(owner);
session.setUserEid(user.getEid());
session.setUserId(user.getId());
removeResource(edit2);
} catch (PermissionException e1) {
M_log.error(e1.getMessage(), e1);
} catch (IdUnusedException e1) {
M_log.error(e1.getMessage(), e1);
} catch (TypeException e1) {
M_log.error(e1.getMessage(), e1);
} catch (InUseException e1) {
M_log.error(e1.getMessage(), e1);
} catch (UserNotDefinedException e1) {
M_log.error(e1.getMessage(), e1);
}
finally {
//safety first!
if (edit2 != null && edit2.isActiveEdit()) {
cancelResource(edit2);
}
}
} catch (VirusScanIncompleteException e1) {
M_log.info("virus scanning did not complete adding resource: " + contentId + " back to queue");
virusScanQueue.add(contentId);
}
}
}
private boolean checkUpdateContentEncoding(ContentResourceEdit edit) {
if (edit == null) {
return false;
}
M_log.debug("checkUpdateContentEncoding(" + edit.getId() + ")");
InputStream content = null;
boolean updated = false;
try
{
//no point in doing this for 0 size resources
if (edit.getContentLength() == 0)
{
return false;
}
String contentEncoding = edit.getProperties().getProperty(ResourceProperties.PROP_CONTENT_ENCODING);
if (contentEncoding == null)
{
contentEncoding = "";
}
String encoding = null;
CharsetDetector detector = new CharsetDetector();
content = edit.streamContent();
//we don't want the whole file the first couple of bytes should do
int len = 1000;
byte[] contentBytes = new byte[len];
if (content.markSupported())
{
detector.setText(content);
} else {
content.read(contentBytes);
detector.setText(contentBytes);
}
CharsetMatch match = detector.detect();
//KNL-714 match can be null -DH
if (match != null)
{
encoding = match.getName();
}
else
{
return false;
}
//KNL-682 do not set content as UTF-32LE or UTF-16
if (encoding.indexOf("UTF-16") > -1 || encoding.indexOf("UTF-32") > -1) {
encoding = "UTF-8";
}
int confidence = match.getConfidence();
//KNL-683 we need a relatively good confidence before we change the encoding
int threshold = m_serverConfigurationService.getInt("content.encodingDetection.threshold", 70);
M_log.debug("detected character encoding of " + encoding + " with confidence of " + confidence + " origional was" + contentEncoding);
if (encoding != null && !contentEncoding.equals(encoding) && (confidence >= threshold))
{
ResourcePropertiesEdit rpe = edit.getPropertiesEdit();
rpe.removeProperty(ResourceProperties.PROP_CONTENT_ENCODING);
rpe.addProperty(ResourceProperties.PROP_CONTENT_ENCODING, encoding);
updated = true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServerOverloadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (content != null) {
try {
content.close();
} catch (IOException e) {
//not much we can do
}
}
}
return updated;
}
/**
* Commit the changes made, and release the lock - no quota check. The Object is disabled, and not to be used after this call.
*
* @param edit
* The ContentResourceEdit object to commit.
* @param priority
* The notification priority of this commit.
* @throws PermissionException
*/
protected void commitResourceEdit(ContentResourceEdit edit, int priority) throws ServerOverloadException
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("commitResourceEdit(): closed ContentResourceEdit", e);
return;
}
if(this.m_prioritySortEnabled)
{
((BasicGroupAwareEdit) edit).setPriority();
}
// update the properties for update
addLiveUpdateResourceProperties(edit);
boolean titleUpdated = false;
if(edit instanceof BaseResourceEdit) {
String oldDisplayName = ((BaseResourceEdit) edit).getOldDisplayName();
ResourceProperties props = edit.getProperties();
if(props != null) {
String newDisplayName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(oldDisplayName == null || newDisplayName == null) {
// do nothing
} else if(! oldDisplayName.equals(newDisplayName)) {
// DisplayName has changed -- post event
titleUpdated = true;
}
}
}
// Flag whether we have a body update or not. This will save expensive DB/IO if we don't need to check the encoding.
boolean contentUpdated = ((BaseResourceEdit) edit).m_body != null || ((BaseResourceEdit) edit).m_contentStream != null;
// complete the edit
m_storage.commitResource(edit);
// Now that the data is committed, we can update the encoding if needed.
// Check the content type if this is an HTML or TEXT file upload.
if (contentUpdated && ResourceType.TYPE_UPLOAD.equals(edit.getResourceType()) &&
(ResourceType.MIME_TYPE_HTML.equals(edit.getContentType()) || ResourceType.MIME_TYPE_TEXT.equals(edit.getContentType()))) {
// Any body bytes lying around erroneously should be thrown away
// because they would already be committed. We also purge the stream
// reference because it would be used up. Additional calls to
// streamContent() will generate new ones from storage like we need.
((BaseResourceEdit) edit).m_body = null;
((BaseResourceEdit) edit).m_contentStream = null;
if (edit.isActiveEdit() && checkUpdateContentEncoding(edit)) {
// The encoding was changed, so we have to flush the metadata.
// Since we already cleaned up, we won't write the body again.
m_storage.commitResource(edit);
}
}
// close the edit object
((BaseResourceEdit) edit).closeEdit();
// must remove old version of this edit from thread-local cache
// so we get new version if we try to retrieve it in same thread
threadLocalManager.set("findResource@" + edit.getId(), null);
String containerId = isolateContainingId(edit.getId());
threadLocalManager.set("findCollection@" + containerId, null);
threadLocalManager.set("members@" + containerId, null);
//threadLocalManager.set("getCollections@" + containerId, null);
threadLocalManager.set("getResources@" + containerId, null);
// only send notifications if the resource is available
// an 'available' event w/ notification will be sent when the resource becomes available
String ref = edit.getReference(null);
// Cancel any previously scheduled delayed available events
eventTrackingService.cancelDelays(ref, ((BaseResourceEdit) edit).getEvent());
// Send a notification with the initial event if this is a revise event and the resource is already available
int immediate_priority = (EVENT_RESOURCE_WRITE.equals(((BaseResourceEdit) edit).getEvent()) && edit.isAvailable()) ?
priority : NotificationService.NOTI_NONE;
eventTrackingService.post(eventTrackingService.newEvent(((BaseResourceEdit) edit).getEvent(),
ref, true, immediate_priority));
// Post an available event for now or later
postAvailableEvent(edit, ref, priority);
if(titleUpdated) {
// post EVENT_RESOURCE_UPD_TITLE event
this.eventTrackingService.post(this.eventTrackingService.newEvent(EVENT_RESOURCE_UPD_TITLE, edit.getReference(), true, priority));
}
if(((BasicGroupAwareEdit) edit).isVisibilityUpdated()) {
// post EVENT_RESOURCE_UPD_VISIBILITY event
this.eventTrackingService.post(this.eventTrackingService.newEvent(EVENT_RESOURCE_UPD_VISIBILITY, edit.getReference(), true, priority));
}
if(((BasicGroupAwareEdit) edit).isAccessUpdated()) {
// post EVENT_RESOURCE_UPD_ACCESS event
this.eventTrackingService.post(this.eventTrackingService.newEvent(EVENT_RESOURCE_UPD_ACCESS, edit.getReference(), true, priority));
}
} // commitResourceEdit
/**
* Test a collection of Group object for the specified group reference
* @param groups The collection (Group) of groups
* @param groupRef The string group reference to find.
* @return true if found, false if not.
*/
protected boolean groupCollectionContainsRefString(Collection<Group> groups, String groupRef)
{
for (Iterator<Group> i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
if (group.getReference().equals(groupRef)) return true;
}
return false;
}
/**
* Cancel the changes made object, and release the lock. The Object is disabled, and not to be used after this call.
*
* @param edit
* The ContentResourceEdit object to commit.
*/
public void cancelResource(ContentResourceEdit edit)
{
// check for closed edit
if (!edit.isActiveEdit())
{
Exception e = new Exception();
M_log.error("cancelResource(): closed ContentResourceEdit", e);
return;
}
// release the edit lock
m_storage.cancelResource(edit);
// if the edit is newly created during an add resource process, remove it from the storage
if (((BaseResourceEdit) edit).getEvent().equals(EVENT_RESOURCE_ADD))
{
m_storage.removeResource(edit);
}
// close the edit object
((BaseResourceEdit) edit).closeEdit();
} // cancelResource
/**
* check permissions for getProperties().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to getProperties(id), false if not.
*/
public boolean allowGetProperties(String id)
{
return unlockCheck(AUTH_RESOURCE_READ, id);
} // allowGetProperties
/**
* Access the properties of a resource with this resource id, either collection or resource.
*
* @param id
* The resource id.
* @exception PermissionException
* if the user does not have permissions to read properties on this object or read through containing collections.
* @exception IdUnusedException
* if the resource id is not found.
* @return the ResourceProperties object for this resource.
*/
public ResourceProperties getProperties(String id) throws PermissionException, IdUnusedException
{
unlock(AUTH_RESOURCE_READ, id);
boolean collectionHint = id.endsWith(Entity.SEPARATOR);
Entity o = null;
try
{
if (collectionHint)
{
o = findCollection(id);
}
else
{
o = findResource(id);
}
}
catch (TypeException ignore)
{
}
// unlikely, but...
if (o == null) throw new IdUnusedException(id);
// track event - removed for clarity of the event log -ggolden
// eventTrackingService.post(eventTrackingService.newEvent(EVENT_PROPERTIES_READ, getReference(id)));
return o.getProperties();
} // getProperties
/**
* check permissions for addProperty().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to addProperty(id), false if not.
*/
public boolean allowAddProperty(String id)
{
boolean isAllowed = allowUpdate(id);
if(isAllowed)
{
try
{
checkExplicitLock(id);
}
catch (PermissionException e)
{
isAllowed = false;
}
}
return isAllowed;
} // allowAddProperty
/**
* Add / update a property for a resource, either collection or resource.
*
* @param id
* The resource id.
* @param name
* The properties name to add or update
* @param value
* The new value for the property.
* @exception PermissionException
* if the user does not have premissions to write properties on this object or read through containing collections.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if any property requested cannot be set (it may be live).
* @exception InUseException
* if the resource is locked by someone else.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @return the ResourceProperties object for this resource.
*/
public ResourceProperties addProperty(String id, String name, String value) throws PermissionException, IdUnusedException,
TypeException, InUseException, ServerOverloadException
{
// check security
checkExplicitLock(id);
if ( ! allowAddProperty(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_WRITE_ANY, getReference(id));
boolean collectionHint = id.endsWith(Entity.SEPARATOR);
Edit o = null;
if (collectionHint)
{
o = editCollection(id);
}
else
{
o = editResource(id);
}
// unlikely, but...
if (o == null) throw new IdUnusedException(id);
// get the properties
ResourcePropertiesEdit props = o.getPropertiesEdit();
// check for TypeException updating live properties
if (props.isLiveProperty(name)) throw new TypeException(name);
// add the property
props.addProperty(name, value);
// commit the change
if (o instanceof ContentResourceEdit)
{
commitResourceEdit((ContentResourceEdit) o, NotificationService.NOTI_NONE);
}
if (o instanceof ContentCollectionEdit)
{
commitCollection((ContentCollectionEdit) o);
}
return props;
} // addProperty
/**
* check permissions for removeProperty().
*
* @param id
* The id of the new resource.
* @return true if the user is allowed to removeProperty(id), false if not.
*/
public boolean allowRemoveProperty(String id)
{
boolean isAllowed = allowUpdate(id);
if(isAllowed)
{
try
{
checkExplicitLock(id);
}
catch(PermissionException e)
{
isAllowed = false;
}
}
return isAllowed;
} // allowRemoveProperty
/**
* Remove a property from a resource, either collection or resource.
*
* @param id
* The resource id.
* @param name
* The property name to be removed from the resource.
* @exception PermissionException
* if the user does not have premissions to write properties on this object or read through containing collections.
* @exception IdUnusedException
* if the resource id is not found.
* @exception TypeException
* if the property named cannot be removed.
* @exception InUseException
* if the resource is locked by someone else.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @return the ResourceProperties object for this resource.
*/
public ResourceProperties removeProperty(String id, String name) throws PermissionException, IdUnusedException, TypeException,
InUseException, ServerOverloadException
{
// check security
checkExplicitLock(id);
if ( ! allowRemoveProperty(id) )
throw new PermissionException(sessionManager.getCurrentSessionUserId(),
AUTH_RESOURCE_WRITE_ANY, getReference(id));
boolean collectionHint = id.endsWith(Entity.SEPARATOR);
Edit o = null;
if (collectionHint)
{
o = editCollection(id);
}
else
{
o = editResource(id);
}
// unlikely, but...
if (o == null) throw new IdUnusedException(id);
// get the properties
ResourcePropertiesEdit props = o.getPropertiesEdit();
// check for TypeException updating live properties
if (props.isLiveProperty(name)) throw new TypeException(name);
// remove the property
props.removeProperty(name);
// commit the change
if (o instanceof ContentResourceEdit)
{
commitResourceEdit((ContentResourceEdit) o, NotificationService.NOTI_NONE);
}
if (o instanceof ContentCollectionEdit)
{
commitCollection((ContentCollectionEdit) o);
}
return props;
} // removeProperty
/**
* Access the resource URL from a resource id.
*
* @param id
* The resource id.
* @return The resource URL.
*/
public String getUrl(String id)
{
// escape just the is part, not the access point
return getUrl(id, PROP_ALTERNATE_REFERENCE); // getAccessPoint(false) + Validator.escapeUrl(id);
} // getUrl
/**
* Access the alternate URL which can be used to access the entity.
*
* @param id
* The resource id.
* @param rootProperty
* The name of the entity property whose value controls which alternate reference URL is requested. If null, the native 'raw' URL is requested.
* @return The resource URL.
*/
public String getUrl(String id, String rootProperty)
{
// escape just the is part, not the access point
// return getAccessPoint(false) + Validator.escapeUrl(id);
return m_serverConfigurationService.getAccessUrl() + getAlternateReferenceRoot(id, rootProperty) + m_relativeAccessPoint
+ Validator.escapeUrl(convertIdToUserEid(id));
} // getUrl
/**
* Compute an alternate root for a reference, based on the value of the specified property.
*
* @param rootProperty
* The property name.
* @return The alternate root, or "" if there is none.
*/
protected String getAlternateReferenceRoot(String id, String rootProperty)
{
// null means don't do this
if (rootProperty == null) return "";
// if id is missing or blank or root, skip as well
if ((id == null) || id.equals("/") || id.equals("")) return "";
// find the property - "" if not found
String alternateRoot = null;
try
{
// TODO: Can this be done without a security check??
// findResource(id).getProperties().getProperty(...) ??
alternateRoot = StringUtils.trimToNull(getProperties(id).getProperty(rootProperty));
}
catch (PermissionException e)
{
// ignore
}
catch (IdUnusedException e)
{
// ignore
}
if (alternateRoot == null) return "";
// make sure it start with a separator and does not end with one
if (!alternateRoot.startsWith(Entity.SEPARATOR)) alternateRoot = Entity.SEPARATOR + alternateRoot;
if (alternateRoot.endsWith(Entity.SEPARATOR))
alternateRoot = alternateRoot.substring(0, alternateRoot.length() - Entity.SEPARATOR.length());
return alternateRoot;
}
/**
* Access the internal reference from a resource id.
*
* @param id
* The resource id.
* @return The internal reference from a resource id.
*/
public String getReference(String id)
{
return getAccessPoint(true) + id;
} // getReference
/**
* Access the resource id of the collection which contains this collection or resource.
*
* @param id
* The resource id (reference, or URL) of the ContentCollection or ContentResource
* @return the resource id (reference, or URL, depending on the id parameter) of the collection which contains this resource.
*/
public String getContainingCollectionId(String id)
{
return isolateContainingId(id);
} // getContainingCollectionId
/**
* Get the depth of the resource/collection object in the hireachy based on the given collection id
*
* @param resourceId
* The Id of the resource/collection object to be tested
* @param baseCollectionId
* The Id of the collection as the relative root level
* @return the integer value reflecting the relative hierarchy depth of the test resource/collection object based on the given base collection level
*/
public int getDepth(String resourceId, String baseCollectionId)
{
if (resourceId.indexOf(baseCollectionId) == -1)
{
// the resource object is not a member of base collection
return -1;
}
else
{
int i = 1;
// the resource object is a member of base collection
String s = resourceId.substring(baseCollectionId.length());
while (s.indexOf(Entity.SEPARATOR) != -1)
{
if (s.indexOf(Entity.SEPARATOR) != (s.length() - 1))
{
// the resource seperator character is not the last character
i++;
s = s.substring(s.indexOf(Entity.SEPARATOR) + 1);
}
else
{
s = "";
}
}
return i;
}
} // getDepth
/**
* Test if this id (reference, or URL) refers to the root collection.
*
* @param id
* The resource id (reference, or URL) of a ContentCollection
* @return true if this is the root collection
*/
public boolean isRootCollection(String id)
{
boolean rv = false;
// test for the root local id
if (id.equals("/"))
{
rv = true;
}
// test for the root reference
else if (id.equals(getAccessPoint(true) + "/"))
{
rv = true;
}
// test for the root URL
else if (id.equals(getAccessPoint(false) + "/"))
{
rv = true;
}
// if (M_log.isDebugEnabled()) M_log.debug("isRootCollection: id: " + id + " rv: " + rv);
return rv;
} // isRootCollection
/**
* Construct a stand-alone, not associated with any particular resource, ResourceProperties object.
*
* @return The new ResourceProperties object.
*/
public ResourcePropertiesEdit newResourceProperties()
{
return new BaseResourcePropertiesEdit();
} // newResourceProperties
/**
* @inheritDoc
*/
public Comparator newContentHostingComparator(String property, boolean ascending)
{
return new ContentHostingComparator(property, ascending, m_useSmartSort);
}
/**
* Return a map of Worksite collections roots that the user has access to.
*
* @return Map of worksite resource root id (String) to worksite title (String)
*/
public Map<String, String> getCollectionMap()
{
// the return map
Map<String, String> rv = new HashMap<String, String>();
// get the sites the user has access to
List<Site> mySites = m_siteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, null, null,
org.sakaiproject.site.api.SiteService.SortType.TITLE_ASC, null);
// add in the user's myworkspace site, if we can find it and if the user
// is not anonymous
String userId = sessionManager.getCurrentSessionUserId();
if ( userId != null )
{
try
{
mySites.add(m_siteService.getSite(m_siteService.getUserSiteId(userId)));
}
catch (IdUnusedException e)
{
}
}
// check each one for dropbox and resources
for (Iterator<Site> i = mySites.iterator(); i.hasNext();)
{
Site site = (Site) i.next();
// test dropbox
if (site.getToolForCommonId("sakai.dropbox") != null)
{
String collectionId = getDropboxCollection(site.getId());
String title = site.getTitle() + " " + rb.getString("gen.drop");
rv.put(collectionId, title);
}
// test resources
if (site.getToolForCommonId("sakai.resources") != null)
{
String collectionId = getSiteCollection(site.getId());
String title = site.getTitle() + " " + rb.getString("gen.reso");
rv.put(collectionId, title);
}
}
return rv;
}
/**********************************************************************************************************************************************************************************************************************************************************
* EntityProducer implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getLabel()
{
return "content";
}
/**
* {@inheritDoc}
*/
public boolean willArchiveMerge()
{
return true;
}
/** The chunk size used when streaming (100K). */
protected static final int STREAM_BUFFER_SIZE = 102400;
/**
* Process the access request for a resource.
*
* @param req
* @param req
* @param res
* @param ref
* @param copyrightAcceptedRefs
* @throws PermissionException
* @throws IdUnusedException
* @throws ServerOverloadException
* @throws CopyrightException
*/
protected void handleAccessResource(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection<String> copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
// we only access resources, not collections
if (ref.getId().endsWith(Entity.SEPARATOR)) throw new EntityNotDefinedException(ref.getReference());
// need read permission
if (!allowGetResource(ref.getId()))
throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(), AUTH_RESOURCE_READ, ref.getReference());
ContentResource resource = null;
try
{
resource = getResource(ref.getId());
}
catch (IdUnusedException e)
{
throw new EntityNotDefinedException(e.getId());
}
catch (PermissionException e)
{
throw new EntityPermissionException(e.getUser(), e.getLock(), e.getResource());
}
catch (TypeException e)
{
throw new EntityNotDefinedException(ref.getReference());
}
// if this entity requires a copyright agreement, and has not yet been set, get one
if (((BaseResourceEdit)resource).requiresCopyrightAgreement() && !copyrightAcceptedRefs.contains(resource.getReference()))
{
throw new EntityCopyrightException(ref.getReference());
}
// Wrap up the resource if we need to.
resource = m_contentFilterService.wrap(resource);
// Set some headers to tell browsers to revalidate and check for updated files
res.addHeader("Cache-Control", "must-revalidate, private");
res.addHeader("Expires", "-1");
try
{
long len = resource.getContentLength();
String contentType = resource.getContentType();
ResourceProperties rp = resource.getProperties();
long lastModTime = 0;
try {
Time modTime = rp.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
lastModTime = modTime.getTime();
} catch (Exception e1) {
M_log.info("Could not retrieve modified time for: " + resource.getId());
}
// KNL-1316 tell the browser when our file was last modified for caching reasons
if (lastModTime > 0) {
SimpleDateFormat rfc1123Date = new SimpleDateFormat(RFC1123_DATE, LOCALE_US);
rfc1123Date.setTimeZone(TimeZone.getTimeZone("GMT"));
res.addHeader("Last-Modified", rfc1123Date.format(lastModTime));
}
// for url content type, encode a redirect to the body URL
if (contentType.equalsIgnoreCase(ResourceProperties.TYPE_URL))
{
if (len < MAX_URL_LENGTH) {
byte[] content = resource.getContent();
if ((content == null) || (content.length == 0))
{
throw new IdUnusedException(ref.getReference());
}
// An invalid URI format will get caught by the outermost catch block
URI uri = new URI(new String(content, "UTF-8"));
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_READ, resource.getReference(null), false));
//SAK-23587 process any macros present in this URL
String decodedUrl = URLDecoder.decode(uri.toString(), "UTF-8");
decodedUrl = expandMacros(decodedUrl);
res.sendRedirect(decodedUrl);
} else {
// we have a text/url mime type, but the body is too long to issue as a redirect
throw new EntityNotDefinedException(ref.getReference());
}
}
else
{
// use the last part, the file name part of the id, for the download file name
String fileName = Validator.getFileName(ref.getId());
String disposition = null;
if (Validator.letBrowserInline(contentType))
{
// if this is an html file we have more checks
String lcct = contentType.toLowerCase();
if ( ( lcct.startsWith("text/") || lcct.startsWith("image/")
|| lcct.contains("html") || lcct.contains("script") ) &&
m_serverConfigurationService.getBoolean(SECURE_INLINE_HTML, true)) {
// increased checks to handle more mime-types - https://jira.sakaiproject.org/browse/KNL-749
boolean fileInline = false;
boolean folderInline = false;
try {
fileInline = rp.getBooleanProperty(ResourceProperties.PROP_ALLOW_INLINE);
}
catch (EntityPropertyNotDefinedException e) {
// we expect this so nothing to do!
}
if (!fileInline)
try
{
folderInline = resource.getContainingCollection().getProperties().getBooleanProperty(ResourceProperties.PROP_ALLOW_INLINE);
}
catch (EntityPropertyNotDefinedException e) {
// we expect this so nothing to do!
}
if (fileInline || folderInline) {
disposition = Web.buildContentDisposition(fileName, false);
}
} else {
disposition = Web.buildContentDisposition(fileName, false);
}
}
// drop through to attachment
if (disposition == null)
{
disposition = Web.buildContentDisposition(fileName, true);
}
// NOTE: Only set the encoding on the content we have to.
// Files uploaded by the user may have been created with different encodings, such as ISO-8859-1;
// rather than (sometimes wrongly) saying its UTF-8, let the browser auto-detect the encoding.
// If the content was created through the WYSIWYG editor, the encoding does need to be set (UTF-8).
String encoding = resource.getProperties().getProperty(ResourceProperties.PROP_CONTENT_ENCODING);
if (encoding != null && encoding.length() > 0)
{
contentType = contentType + "; charset=" + encoding;
}
// KNL-1316 let's see if the user already has a cached copy. Code copied and modified from Tomcat DefaultServlet.java
long headerValue = req.getDateHeader("If-Modified-Since");
if (headerValue != -1 && (lastModTime < headerValue + 1000)) {
// The entity has not been modified since the date specified by the client. This is not an error case.
res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
ArrayList<Range> ranges = parseRange(req, res, len);
res.addHeader("Accept-Ranges", "bytes");
if (req.getHeader("Range") == null || (ranges == null) || (ranges.isEmpty())) {
// stream the content using a small buffer to keep memory managed
InputStream content = null;
OutputStream out = null;
try
{
content = resource.streamContent();
if (content == null)
{
throw new IdUnusedException(ref.getReference());
}
res.setContentType(contentType);
res.addHeader("Content-Disposition", disposition);
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4187336
if (len <= Integer.MAX_VALUE){
res.setContentLength((int)len);
} else {
res.addHeader("Content-Length", Long.toString(len));
}
// set the buffer of the response to match what we are reading from the request
if (len < STREAM_BUFFER_SIZE)
{
res.setBufferSize((int)len);
}
else
{
res.setBufferSize(STREAM_BUFFER_SIZE);
}
out = res.getOutputStream();
copyRange(content, out, 0, len-1);
}
catch (ServerOverloadException e)
{
throw e;
}
catch (Exception ignore)
{
}
finally
{
// be a good little program and close the stream - freeing up valuable system resources
if (content != null)
{
content.close();
}
if (out != null)
{
try
{
out.close();
}
catch (Exception ignore)
{
}
}
}
// Track event - only for full reads
eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_READ, resource.getReference(null), false));
}
else
{
// Output partial content. Adapted from Apache Tomcat 5.5.27 DefaultServlet.java
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (ranges.size() == 1) {
// Single response
Range range = (Range) ranges.get(0);
res.addHeader("Content-Range", "bytes "
+ range.start
+ "-" + range.end + "/"
+ range.length);
long length = range.end - range.start + 1;
if (length < Integer.MAX_VALUE) {
res.setContentLength((int) length);
} else {
// Set the content-length as String to be able to use a long
res.setHeader("content-length", "" + length);
}
res.addHeader("Content-Disposition", disposition);
if (contentType != null) {
res.setContentType(contentType);
}
// stream the content using a small buffer to keep memory managed
InputStream content = null;
OutputStream out = null;
try
{
content = resource.streamContent();
if (content == null)
{
throw new IdUnusedException(ref.getReference());
}
// set the buffer of the response to match what we are reading from the request
if (len < STREAM_BUFFER_SIZE)
{
res.setBufferSize((int)len);
}
else
{
res.setBufferSize(STREAM_BUFFER_SIZE);
}
out = res.getOutputStream();
copyRange(content, out, range.start, range.end);
}
catch (ServerOverloadException e)
{
throw e;
}
catch (SocketException e)
{
//a socket exception usualy means the client aborted the connection or similar
if (M_log.isDebugEnabled())
{
M_log.debug("SocketExcetion", e);
}
}
catch (Exception ignore)
{
}
finally
{
// be a good little program and close the stream - freeing up valuable system resources
if (content != null)
{
content.close();
}
if (out != null)
{
try
{
out.close();
}
catch (IOException ignore)
{
// ignore
}
}
}
} else {
// Multipart response
res.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATOR);
// stream the content using a small buffer to keep memory managed
OutputStream out = null;
try
{
// set the buffer of the response to match what we are reading from the request
if (len < STREAM_BUFFER_SIZE)
{
res.setBufferSize((int)len);
}
else
{
res.setBufferSize(STREAM_BUFFER_SIZE);
}
out = res.getOutputStream();
copyRanges(resource, out, ranges.iterator(), contentType);
}
catch (SocketException e)
{
//a socket exception usualy means the client aborted the connection or similar
if (M_log.isDebugEnabled())
{
M_log.debug("SocketExcetion", e);
}
}
catch (Exception ignore)
{
M_log.error("Swallowing exception", ignore);
}
finally
{
// be a good little program and close the stream - freeing up valuable system resources
if (out != null)
{
try
{
out.close();
}
catch (IOException ignore)
{
// ignore
}
}
}
} // output multiple ranges
} // output partial content
} // output resource
}
catch (Exception t)
{
throw new EntityNotDefinedException(ref.getReference(), t);
}
}
/**
* Process the access request for a collection, producing the "apache" style HTML file directory listing (complete with index.html redirect if found).
*
* @param req
* @param res
* @param ref
* @param copyrightAcceptedRefs
* @throws PermissionException
* @throws IdUnusedException
* @throws ServerOverloadException
*/
protected void handleAccessCollection(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
// we only access resources, not collections
if (!ref.getId().endsWith(Entity.SEPARATOR)) throw new EntityNotDefinedException(ref.getReference());
// first, check for an index.html in the collection - redirect here if found
if (m_storage.checkResource(ref.getId() + "index.html"))
{
String addr = Web.returnUrl(req, req.getPathInfo()) + "index.html";
try
{
res.sendRedirect(addr);
return;
}
catch (IOException e)
{
M_log.warn("handleAccessCollection: redirecting to " + addr + " : " + e);
}
}
// need read permission
if (!allowGetResource(ref.getId()))
throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(), AUTH_RESOURCE_READ, ref.getReference());
BaseCollectionEdit collection = null;
try
{
collection = (BaseCollectionEdit) getCollection(ref.getId());
}
catch (IdUnusedException e)
{
throw new EntityNotDefinedException(e.getId());
}
catch (PermissionException e)
{
throw new EntityPermissionException(e.getUser(), e.getLock(), e.getResource());
}
catch (TypeException e)
{
throw new EntityNotDefinedException(ref.getReference());
}
try
{
// use the helper
m_collectionAccessFormatter.format(collection, ref, req, res, rb, this);
// track event
// eventTrackingService.post(eventTrackingService.newEvent(EVENT_RESOURCE_READ, collection.getReference(), false));
}
catch (Exception t)
{
throw new EntityNotDefinedException(ref.getReference());
}
}
/**
* {@inheritDoc}
*/
public HttpAccess getHttpAccess()
{
return new HttpAccess()
{
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
EntityAccessOverloadException, EntityCopyrightException
{
// if the id is null, the request was for just ".../content"
String refId = ref.getId();
if (refId == null) refId = "";
// test if the given reference is a resource
if (m_storage.checkResource(refId))
{
handleAccessResource(req, res, ref, copyrightAcceptedRefs);
return;
}
// test for a collection
if (m_storage.checkCollection(refId))
{
handleAccessCollection(req, res, ref, copyrightAcceptedRefs);
return;
}
// finally, try a collection that was missing it's final separator
if (!refId.endsWith(Entity.SEPARATOR))
{
// would it be a collection if we added the missing separator?
if (m_storage.checkCollection(refId + Entity.SEPARATOR))
{
// redirect to this
// Note: if the request had no trailing separator, getPathInfo still returns "/" - avoid ending up with "...//" -ggolden
String addr = Web.returnUrl(req, req.getPathInfo())
+ ("/".equals(req.getPathInfo()) ? "" : Entity.SEPARATOR);
try
{
res.sendRedirect(addr);
return;
}
catch (IOException e)
{
M_log.warn("handleAccess: redirecting to " + addr + " : " + e);
throw new EntityNotDefinedException(ref.getReference());
}
}
// nothing we know of...
throw new EntityNotDefinedException(ref.getReference());
}
}
};
}
/**
* {@inheritDoc}
*/
public Entity getEntity(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
Entity rv = null;
ResourceProperties props = null;
try
{
props = getProperties(ref.getId());
boolean isCollection = false;
try
{
isCollection = props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
}
catch (EntityPropertyNotDefinedException ignore)
{
// do nothing -- it's not a collection unless PROP_IS_COLLECTION is defined
}
catch (EntityPropertyTypeException e)
{
// Log this and assume it's not a collection
M_log.warn("EntityPropertyTypeException: PROP_IS_COLLECTION not boolean for " + ref.getReference());
}
if (isCollection)
{
try
{
rv = getCollection(ref.getId());
}
catch (TypeException e)
{
// in that case try to get it as a resource
rv = getResource(ref.getId());
}
}
else
{
try
{
rv = getResource(ref.getId());
}
catch (TypeException e)
{
// in that case try to get it as a collection
rv = getCollection(ref.getId());
}
}
}
catch (PermissionException e)
{
M_log.warn("PermissionException " + ref.getReference());
}
catch (IdUnusedException e)
{
M_log.warn("IdUnusedException " + ref.getReference());
}
catch (TypeException e)
{
// TODO Auto-generated catch block
M_log.warn("TypeException " + ref.getReference());
}
return rv;
}
/**
* {@inheritDoc}
*/
public String getEntityUrl(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
return getUrl(convertIdToUserEid(ref.getId()));
}
/**
* {@inheritDoc}
*/
public Collection getEntityAuthzGroups(Reference ref, String userId)
{
// static code review possible NPE fix -AZ
if (ref == null || ref.getId() == null) {
M_log.warn("ref passed into getEntityAuthzGroups is not valid (ref or ref.getId is null): " + ref);
return null;
}
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
// form a key for thread-local caching
String threadLocalKey = "getEntityAuthzGroups@" + userId + "@" + ref.getReference();
Collection rv = (Collection) threadLocalManager.get(threadLocalKey);
if (rv != null)
{
return new ArrayList(rv);
}
// use the resources realm, all container (folder) realms
rv = new ArrayList();
rv.addAll(getEntityHierarchyAuthzGroups(ref));
try
{
boolean isDropbox = false;
boolean attachmentOverride = false;
// special check for group-user : the grant's in the user's My Workspace site
String parts[] = StringUtil.split(ref.getId(), Entity.SEPARATOR);
if ((parts.length > 3) && (parts[1].equals("group-user")))
{
rv.add(m_siteService.siteReference(m_siteService.getUserSiteId(parts[3])));
isDropbox = true;
}
// If this is a site-scoped attachment, use the site grant as the only grant
// Old attachments format: (use /content/attachment realm)
// /content/attachment/guid/filename.pd
// New attachment format:
// /content/attachment/siteid/type/guid/filename.pd
// But since we need to protect all paths from
// /content/attachment/siteid/
// and below we simply check to see f the guid is a valid site ID.
if ( m_siteAttachments && (parts.length >= 3) && (parts[1].equals("attachment")))
{
String siteId = parts[2];
if ( m_siteService.siteExists(siteId) )
{
rv.clear(); // Ignore the hierarchical inheritance in /attachment
rv.add(m_siteService.siteReference(siteId));
rv.add(getReference(ref.getId())); // SAK-15657
attachmentOverride = true; // Nothing else is needed
}
}
ContentEntity entity = null;
if(ref.getId().endsWith(Entity.SEPARATOR))
{
entity = findCollection(ref.getId());
}
else
{
entity = findResource(ref.getId());
}
// this piece of code only comes into effect when the ref id is not resolveable as is
if(entity == null)
{
String refId = ref.getId();
while (entity == null && refId != null && ! refId.trim().equals(""))
{
refId = isolateContainingId(refId);
if(refId != null && ! refId.trim().equals(""))
{
entity = findCollection(refId);
}
}
}
// this will ensure the NPE does not happen
if (entity == null) {
M_log.warn("ref ("+ref+") is not resolveable as an entity (it is null)");
return null;
}
boolean inherited = false;
AccessMode access = entity.getAccess();
if ( attachmentOverride )
{
// No further inheritance
}
else if(AccessMode.INHERITED.equals(access))
{
inherited = true;
access = entity.getInheritedAccess();
}
if(isDropbox || AccessMode.SITE == access || AccessMode.INHERITED == access)
{
// site
ref.addSiteContextAuthzGroup(rv);
}
else if(AccessMode.GROUPED.equals(access))
{
String siteReference = m_siteService.siteReference(ref.getContext());
boolean useSiteAsContext = false;
if(siteReference != null && userId != null)
{
useSiteAsContext = m_securityService.unlock(userId, AUTH_RESOURCE_ALL_GROUPS, siteReference);
}
if(useSiteAsContext)
{
ref.addSiteContextAuthzGroup(rv);
}
else if(inherited)
{
rv.addAll(entity.getInheritedGroups());
}
else
{
rv.addAll(entity.getGroups());
}
}
}
catch (Exception e)
{
}
// cache in the thread
threadLocalManager.set(threadLocalKey, new ArrayList(rv));
if (M_log.isDebugEnabled())
{
M_log.debug("getEntityAuthzGroups for: ref: " + ref.getReference() + " user: " + userId);
for (Iterator i = rv.iterator(); i.hasNext();)
{
M_log.debug("** -- " + i.next());
}
}
return rv;
}
protected Collection getEntityHierarchyAuthzGroups(Reference ref)
{
Collection<String> rv = new TreeSet<String>();
// add the root
rv.add(getReference("/"));
// try the resource, all the folders above it (don't include /)
String paths[] = StringUtil.split(ref.getId(), Entity.SEPARATOR);
boolean container = ref.getId().endsWith(Entity.SEPARATOR);
if (paths.length > 1)
{
String root = getReference(Entity.SEPARATOR + paths[1] + Entity.SEPARATOR);
rv.add(root);
StringBuilder rootBuilder = new StringBuilder();
rootBuilder.append(root);
for (int next = 2; next < paths.length; next++)
{
rootBuilder.append(paths[next]);
if ((next < paths.length - 1) || container)
{
rootBuilder.append(Entity.SEPARATOR);
}
rv.add(rootBuilder.toString());
}
}
return rv;
}
/**
* {@inheritDoc}
*/
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// start with an element with our very own name
Element element = doc.createElement(ContentHostingService.class.getName());
((Element) stack.peek()).appendChild(element);
stack.push(element);
// the root collection for the site
String siteCollectionId = getSiteCollection(siteId);
try
{
// get the collection for the site
ContentCollection collection = getCollection(siteCollectionId);
archiveCollection(collection, doc, stack, archivePath, siteCollectionId, results);
}
catch (Exception any)
{
results.append("Error archiving collection from site: " + siteId + " " + any.toString() + "\n");
}
stack.pop();
return results.toString();
} // archive
/**
* {@inheritDoc}
*/
public String archiveResources(List attachments, Document doc, Stack stack, String archivePath)
{
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
// start with an element with our very own name
Element element = doc.createElement(ContentHostingService.class.getName());
((Element) stack.peek()).appendChild(element);
stack.push(element);
for (Iterator i = attachments.iterator(); i.hasNext();)
{
Reference ref = (Reference) i.next();
try
{
ContentResource resource = (ContentResource) ref.getEntity();
if (resource != null)
{
results.append(archiveResource(resource, doc, stack, archivePath, null));
}
}
catch (Exception any)
{
results.append("Error archiving resource: " + ref + " " + any.toString() + "\n");
M_log.warn("archveResources: exception archiving resource: " + ref + ": ", any);
}
}
stack.pop();
return results.toString();
}
/**
* Replace the WT user id with the new qualified id
*
* @param el
* The XML element holding the perproties
* @param useIdTrans
* The HashMap to track old WT id to new CTools id
*/
protected void WTUserIdTrans(Element el, Map userIdTrans)
{
NodeList children4 = el.getChildNodes();
int length4 = children4.getLength();
for (int i4 = 0; i4 < length4; i4++)
{
Node child4 = children4.item(i4);
if (child4.getNodeType() == Node.ELEMENT_NODE)
{
Element element4 = (Element) child4;
if (element4.getTagName().equals("property"))
{
String creatorId = "";
String modifierId = "";
if (element4.hasAttribute("CHEF:creator"))
{
if ("BASE64".equalsIgnoreCase(element4.getAttribute("enc")))
{
creatorId = Xml.decodeAttribute(element4, "CHEF:creator");
}
else
{
creatorId = element4.getAttribute("CHEF:creator");
}
String newCreatorId = (String) userIdTrans.get(creatorId);
if (newCreatorId != null)
{
Xml.encodeAttribute(element4, "CHEF:creator", newCreatorId);
element4.setAttribute("enc", "BASE64");
}
}
else if (element4.hasAttribute("CHEF:modifiedby"))
{
if ("BASE64".equalsIgnoreCase(element4.getAttribute("enc")))
{
modifierId = Xml.decodeAttribute(element4, "CHEF:modifiedby");
}
else
{
modifierId = element4.getAttribute("CHEF:modifiedby");
}
String newModifierId = (String) userIdTrans.get(modifierId);
if (newModifierId != null)
{
Xml.encodeAttribute(element4, "CHEF:creator", newModifierId);
element4.setAttribute("enc", "BASE64");
}
}
}
}
}
} // WTUserIdTrans
/**
* Merge the resources from the archive into the given site.
*
* @param siteId
* The id of the site getting imported into.
* @param root
* The XML DOM tree of content to merge.
* @param archviePath
* The path to the folder where we are reading auxilary files.
* @return A log of status messages from the archive.
*/
public String merge(String siteId, Element root, String archivePath, String mergeId, Map attachmentNames, Map userIdTrans,
Set userListAllowImport)
{
// get the system name: FROM_WT, FROM_CT, FROM_SAKAI
String source = "";
// root: <service> node
Node parent = root.getParentNode(); // parent: <archive> node containing "system"
if (parent.getNodeType() == Node.ELEMENT_NODE)
{
Element parentEl = (Element) parent;
source = parentEl.getAttribute("system");
}
// prepare the buffer for the results log
StringBuilder results = new StringBuilder();
try
{
NodeList children = root.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// for "collection" kids
if (element.getTagName().equals("collection"))
{
// replace the WT userid when needed
if (!userIdTrans.isEmpty())
{
// replace the WT user id with new user id
WTUserIdTrans(element, userIdTrans);
}
// from the relative id form a full id for the target site,
// updating the xml element
String relId = StringUtils.trimToNull(element.getAttribute("rel-id"));
if (relId == null)
{
// Note: the site's root collection will have a "" rel-id, which will be null.
continue;
}
String id = getSiteCollection(siteId) + relId;
element.setAttribute("id", id);
// collection: add if missing, else merge in
ContentCollection c = mergeCollection(element);
if (c == null)
{
results.append("collection: " + id + " already exists and was not replaced.\n");
}
else
{
results.append("collection: " + id + " imported.\n");
}
}
// for "resource" kids
else if (element.getTagName().equals("resource"))
{
// a flag showing if continuing merging this resource
boolean goAhead = true;
// check if the person who last modified this source has the right role
// if not, set the goAhead flag to be false when fromSakai or fromCT
if (source.equalsIgnoreCase("Sakai 1.0") || source.equalsIgnoreCase("CT"))
{
NodeList children2 = element.getChildNodes();
int length2 = children2.getLength();
for (int i2 = 0; i2 < length2; i2++)
{
Node child2 = children2.item(i2);
if (child2.getNodeType() == Node.ELEMENT_NODE)
{
Element element2 = (Element) child2;
// get the "channel" child
if (element2.getTagName().equals("properties"))
{
NodeList children3 = element2.getChildNodes();
final int length3 = children3.getLength();
for (int i3 = 0; i3 < length3; i3++)
{
Node child3 = children3.item(i3);
if (child3.getNodeType() == Node.ELEMENT_NODE)
{
Element element3 = (Element) child3;
// for "message" children
if (element3.getTagName().equals("property"))
{
if (element3.getAttribute("name").equalsIgnoreCase("CHEF:modifiedby"))
{
if ("BASE64".equalsIgnoreCase(element3.getAttribute("enc")))
{
String creatorId = Xml.decodeAttribute(element3, "value");
if (!userListAllowImport.contains(creatorId)) goAhead = false;
}
else
{
String creatorId = element3.getAttribute("value");
if (!userListAllowImport.contains(creatorId)) goAhead = false;
}
}
}
}
}
}
}
}
} // the end to if fromSakai or fromCT
if (goAhead)
{
// replace the WT userid when needed
if (!userIdTrans.isEmpty())
{
// replace the WT user id with new user id
WTUserIdTrans(element, userIdTrans);
}
// from the relative id form a full id for the target site,
// updating the xml element
String id = StringUtils.trimToNull(element.getAttribute("id"));
String relId = StringUtils.trimToNull(element.getAttribute("rel-id"));
// escape the invalid characters
id = Validator.escapeQuestionMark(id);
relId = Validator.escapeQuestionMark(relId);
// if it's attachment, assign a new attachment folder
if (id.startsWith(ATTACHMENTS_COLLECTION))
{
String oldRef = getReference(id);
// take the name from after /attachment/whatever/
id = ATTACHMENTS_COLLECTION + idManager.createUuid()
+ id.substring(id.indexOf('/', ATTACHMENTS_COLLECTION.length()));
// record the rename
attachmentNames.put(oldRef, id);
}
// otherwise move it into the site
else
{
if (relId == null)
{
M_log.warn("mergeContent(): no rel-id attribute in resource");
continue;
}
id = getSiteCollection(siteId) + relId;
}
element.setAttribute("id", id);
ContentResource r = null;
// if the body-location attribute points at another file for the body, get this
String bodyLocation = StringUtils.trimToNull(element.getAttribute("body-location"));
if (bodyLocation != null)
{
// the file name is relative to the archive file
String bodyPath = StringUtil.fullReference(archivePath, bodyLocation);
// get a stream from the file
FileInputStream in = new FileInputStream(bodyPath);
// resource: add if missing
r = mergeResource(element, in);
}
else
{
// resource: add if missing
r = mergeResource(element);
}
if (r == null)
{
results.append("resource: " + id + " already exists and was not replaced.\n");
}
else
{
results.append("resource: " + id + " imported.\n");
}
}
}
}
}
catch (Exception any)
{
results.append("import interrputed: " + any.toString() + "\n");
M_log.error("mergeContent(): exception: ", any);
}
return results.toString();
} // merge
/**
* {@inheritDoc}
*/
public void updateEntityReferences(String toContext, Map transversalMap){
//TODO: is there any content that needs reference updates?
String fromContext = (String) transversalMap.get("/fromContext");
String thisKey = null;
try {
List thisTargetResourceList = getAllResources(fromContext);
Iterator sourceResourceIterator = thisTargetResourceList.iterator();
String tId;
String rContent;
while(sourceResourceIterator.hasNext()){
ContentResource thisContentResource = (ContentResource) sourceResourceIterator.next();
tId = thisContentResource.getId();
String sourceType = thisContentResource.getContentType();
if(sourceType.startsWith("text/html")){
String oldReference = tId;
tId = siteIdSplice(tId, toContext);
ContentResource oldSiteContentResource = getResource(oldReference);
byte[] thisResourceContentRaw = oldSiteContentResource.getContent();
rContent = new String(thisResourceContentRaw);
StringBuffer saveOldEntity = new StringBuffer(rContent);
Iterator contentKeys = transversalMap.keySet().iterator();
while(contentKeys.hasNext()){
String oldValue = (String) contentKeys.next();
if(!oldValue.equals("/fromContext")){
String newValue = "";
newValue = (String) transversalMap.get(oldValue);
if(newValue.length()>0){
rContent = linkMigrationHelper.migrateOneLink(oldValue, newValue, rContent);
}
}
}
try {
rContent = linkMigrationHelper.bracketAndNullifySelectedLinks(rContent);
} catch (Exception e) {
// TODO Auto-generated catch block
M_log.debug ("Forums LinkMigrationHelper.editLinks failed" + e);
}
try {
if(!saveOldEntity.toString().equals(rContent)){
ContentResourceEdit edit = editResource(tId);
edit.setContent(rContent.getBytes());
m_storage.commitResource(edit);
}
} catch (InUseException e6) {
// TODO Auto-generated catch block
M_log.error(this + thisKey, e6);
}catch (PermissionException e1) {
M_log.error(this + thisKey, e1);
} catch (IdUnusedException e2) {
M_log.error(this + thisKey, e2);
} catch (TypeException e3) {
M_log.error(this + thisKey, e3);
}
}
}
} catch (PermissionException e1) {
M_log.error(this + thisKey, e1);
} catch (IdUnusedException e2) {
M_log.error(this + thisKey, e2);
} catch (TypeException e3) {
M_log.error(this + thisKey, e3);
} catch (ServerOverloadException e4) {
M_log.error(this + thisKey, e4);
}
}
private String siteIdExtract(String ref){
String[] components = ref.split("/");
return components[2];
}
private String siteIdSplice(String ref, String siteId){
String[] components = ref.split("/");
StringBuffer splicedString = new StringBuffer();
for(int i=1;i< components.length;i++){
splicedString.append("/");
if(i==2){
splicedString.append(siteId);
}else{
splicedString.append(components[i]);
}
}
return splicedString.toString();
}
/**
* {@inheritDoc}
*/
public void transferCopyEntities(String fromContext, String toContext, List resourceIds){
transferCopyEntitiesRefMigrator(fromContext, toContext, resourceIds);
}
public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List resourceIds)
{
Map transversalMap = new HashMap();
// default to import all resources
boolean toBeImported = true;
// set up the target collection
ContentCollection toCollection = null;
try
{
toCollection = getCollection(toContext);
}
catch(IdUnusedException e)
{
ContentCollectionEdit toCollectionEdit = null;
// not such collection yet, add one
try
{
toCollectionEdit = addCollection(toContext);
m_storage.commitCollection(toCollectionEdit);
((BaseCollectionEdit) toCollectionEdit).closeEdit();
//try this again now to get an activated collection
try
{
toCollection = getCollection(toContext);
}
catch (IdUnusedException eee)
{
M_log.error(this + toContext, eee);
}
catch (TypeException eee)
{
M_log.error(this + toContext, eee);
}
}
catch(IdUsedException ee)
{
M_log.error(this + toContext, ee);
}
catch(IdInvalidException ee)
{
M_log.error(this + toContext, ee);
}
catch (PermissionException ee)
{
M_log.error(this + toContext, ee);
}
catch (InconsistentException ee)
{
M_log.error(this + toContext, ee);
}
finally
{
//safety first!
if (toCollectionEdit != null && toCollectionEdit.isActiveEdit()) {
((BaseCollectionEdit) toCollectionEdit).closeEdit();
}
}
}
catch (TypeException e)
{
M_log.error(this + toContext, e);
}
catch (PermissionException e)
{
M_log.error(this + toContext, e);
}
if (toCollection != null)
{
// get the list of all resources for importing
try
{
// get the root collection
ContentCollection oCollection = getCollection(fromContext);
// Get the collection members from the 'new' collection
List oResources = oCollection.getMemberResources();
for (int i = 0; i < oResources.size(); i++)
{
// get the original resource
Entity oResource = (Entity) oResources.get(i);
String oId = oResource.getId();
if (resourceIds != null && resourceIds.size() > 0)
{
// only import those with ids inside the list
toBeImported = false;
for (int j = 0; j < resourceIds.size() && !toBeImported; j++)
{
if (((String) resourceIds.get(j)).equals(oId))
{
toBeImported = true;
}
}
}
if (toBeImported)
{
String oId2 = oResource.getId();
String nId = "";
String nUrl = "";
int ind = oId2.indexOf(fromContext);
if (ind != -1)
{
String str1 = "";
String str2 = "";
if (ind != 0)
{
// the substring before the fromContext string
str1 = oId2.substring(0, ind);
}
if (!((ind + fromContext.length()) > oId2.length()))
{
// the substring after the fromContext string
str2 = oId2.substring(ind + fromContext.length(), oId2.length());
}
// get the new resource id; fromContext is replaced with toContext
nId = str1 + toContext + str2;
}
ResourceProperties oProperties = oResource.getProperties();
boolean isCollection = false;
try
{
isCollection = oProperties.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
}
catch (Exception e)
{
}
if (isCollection)
{
// add collection
try
{
ContentCollectionEdit edit = addCollection(nId);
// import properties
ResourcePropertiesEdit p = edit.getPropertiesEdit();
p.clear();
p.addAll(oProperties);
edit.setAvailability(((ContentCollection) oResource).isHidden(), ((ContentCollection) oResource).getReleaseDate(), ((ContentCollection) oResource).getRetractDate());
// SAK-23305
hideImportedContent(edit);
// complete the edit
m_storage.commitCollection(edit);
((BaseCollectionEdit) edit).closeEdit();
nUrl = edit.getUrl();
}
catch (IdUsedException e)
{
}
catch (IdInvalidException e)
{
}
catch (PermissionException e)
{
}
catch (InconsistentException e)
{
}
transversalMap.put(oResource.getId(), nId);
transversalMap.put(oResource.getUrl(), nUrl);
transversalMap.putAll(transferCopyEntitiesRefMigrator(oResource.getId(), nId, resourceIds));
}
else
{
try
{
// add resource
ContentResourceEdit edit = addResource(nId);
edit.setContentType(((ContentResource) oResource).getContentType());
edit.setResourceType(((ContentResource) oResource).getResourceType());
edit.setContent(((ContentResource) oResource).streamContent());
edit.setAvailability(((ContentResource) oResource).isHidden(), ((ContentResource) oResource).getReleaseDate(), ((ContentResource) oResource).getRetractDate());
//edit.setContent(((ContentResource) oResource).getContent());
// import properties
ResourcePropertiesEdit p = edit.getPropertiesEdit();
p.clear();
p.addAll(oProperties);
// SAK-23305
hideImportedContent(edit);
// complete the edit
m_storage.commitResource(edit);
((BaseResourceEdit) edit).closeEdit();
nUrl = edit.getUrl();
transversalMap.put(oResource.getId(), nId);
transversalMap.put(oResource.getUrl(), nUrl);
}
catch (PermissionException e)
{
}
catch (IdUsedException e)
{
}
catch (IdInvalidException e)
{
}
catch (InconsistentException e)
{
}
catch (ServerOverloadException e)
{
}
} // if
} // if
} // for
}
catch (IdUnusedException e)
{
}
catch (TypeException e)
{
}
catch (PermissionException e)
{
}
}
transversalMap.put("/fromContext", fromContext);
return transversalMap;
} // importResources
/**
* Hide imported content -- SAK-23305
* @param edit Object either a ContentResourceEdit or ContentCollectionEdit object
*/
private void hideImportedContent(Object edit)
{
if (m_serverConfigurationService.getBoolean("content.import.hidden", false))
{
ContentResourceEdit resource = null;
ContentCollectionEdit collection = null;
String containingCollectionId = null;
if (edit instanceof ContentResourceEdit)
{
resource = (ContentResourceEdit) edit;
containingCollectionId = resource.getContainingCollection().getId();
}
else if (edit instanceof ContentCollectionEdit)
{
collection = (ContentCollectionEdit) edit;
containingCollectionId = collection.getContainingCollection().getId();
}
if (resource != null || collection != null)
{
/*
* If this is "reuse content" during worksite setup, the site collection at this time is
* /group/!admin/ for all content including ones in the folders, so count how many "/" in
* the collection ID. If <= 3, then it's a top-level item and needs to be hidden.
*/
int slashcount = StringUtils.countMatches(containingCollectionId, "/");
if (slashcount <= 3)
{
if (resource != null)
{
resource.setHidden();
}
else if (collection != null)
{
collection.setHidden();
}
}
}
}
}
/**
* {@inheritDoc}
*/
public boolean parseEntityReference(String reference, Reference ref)
{
String id = null;
String context = "";
// for content hosting resources and collections
if (reference.startsWith(REFERENCE_ROOT))
{
// parse out the local resource id
id = reference.substring(REFERENCE_ROOT.length(), reference.length());
}
// not mine
else
{
return false;
}
// recognize a short reference
if (m_shortRefs)
{
// ignoring the first separator, get the first item separated from the rest
String prefix[] = StringUtil.splitFirst((id.length() > 1) ? id.substring(1) : "", Entity.SEPARATOR);
if (prefix.length > 0)
{
// the following are recognized as full reference prefixe; if seen, the short ref feature is not applied
if (!(prefix[0].equals("group") || prefix[0].equals("user") || prefix[0].equals("group-user")
|| prefix[0].equals("public") || prefix[0].equals("private") || prefix[0].equals("attachment")))
{
String newPrefix = null;
// a "~" starts a /user/ reference
if (prefix[0].startsWith("~"))
{
newPrefix = Entity.SEPARATOR + "user" + Entity.SEPARATOR + prefix[0].substring(1);
}
// otherwise a /group/ reference
else
{
newPrefix = Entity.SEPARATOR + "group" + Entity.SEPARATOR + prefix[0];
}
// reattach the tail (if any) to get the new id (if no taik, make sure we end with a separator if id started out with one)
id = newPrefix
+ ((prefix.length > 1) ? (Entity.SEPARATOR + prefix[1])
: (id.endsWith(Entity.SEPARATOR) ? Entity.SEPARATOR : ""));
}
}
}
// parse out the associated site id, with alias checking
String parts[] = StringUtil.split(id, Entity.SEPARATOR);
boolean checkForAlias = true;
boolean checkForUserIdEid = false;
if (parts.length >= 3)
{
if (parts[1].equals("group"))
{
context = parts[2];
}
else if (parts[1].equals("user"))
{
context = m_siteService.getUserSiteId(parts[2]);
// for user sites, don't check for alias
checkForAlias = false;
// enable user id/eid checking
checkForUserIdEid = true;
}
else if (parts[1].equals("group-user"))
{
// use just the group context
context = parts[2];
}
// if a user site, recognize ID or EID
if (checkForUserIdEid && (parts[2] != null) && (parts[2].length() > 0))
{
try
{
// if successful, the context is already a valid user id
userDirectoryService.getUser(parts[2]);
}
catch (UserNotDefinedException tryEid)
{
try
{
// try using it as an EID
String userId = userDirectoryService.getUserId(parts[2]);
// switch to the ID
parts[2] = userId;
context = m_siteService.getUserSiteId(userId);
String newId = StringUtil.unsplit(parts, Entity.SEPARATOR);
// add the trailing separator if needed
if (id.endsWith(Entity.SEPARATOR)) newId += Entity.SEPARATOR;
id = newId;
}
catch (UserNotDefinedException notEid)
{
// if context was not a valid EID, leave it alone
}
}
}
// recognize alias for site id - but if a site id exists that matches the requested site id, that's what we will use
if (m_siteAlias && checkForAlias && (context != null) && (context.length() > 0))
{
if (!m_siteService.siteExists(context))
{
try
{
String target = m_aliasService.getTarget(context);
// just to stay well clear of infinite looping (the newReference will call us for content references)
// ignore any targets that are to the content service -ggolden
if (!(target.startsWith(REFERENCE_ROOT) || target.startsWith(getUrl(""))))
{
Reference targetRef = m_entityManager.newReference(target);
boolean changed = false;
// for a site reference
if (SiteService.APPLICATION_ID.equals(targetRef.getType()))
{
// use the ref's id, i.e. the site id
context = targetRef.getId();
changed = true;
}
// for mail archive reference
// TODO: taken from MailArchiveService.APPLICATION_ID to (fake) reduce a dependency -ggolden
else if ("sakai:mailarchive".equals(targetRef.getType()))
{
// use the ref's context as the site id
context = targetRef.getContext();
changed = true;
}
// if changed, update the id
if (changed)
{
parts[2] = context;
String newId = StringUtil.unsplit(parts, Entity.SEPARATOR);
// add the trailing separator if needed
if (id.endsWith(Entity.SEPARATOR)) newId += Entity.SEPARATOR;
id = newId;
}
}
}
catch (IdUnusedException noAlias)
{
}
}
}
}
// if we end up with no id, or blank, use the root
if ((id == null) || (id.length() == 0)) id = "/";
ref.set(APPLICATION_ID, null, id, null, context);
// because short refs or id/eid or alias processing may recognize a reference that is not the real reference,
// update the ref's string to reflect the real reference
ref.updateReference(REFERENCE_ROOT + id);
return true;
}
/**
* {@inheritDoc}
*/
public String getEntityDescription(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
String rv = "Content: " + ref.getId();
try {
ResourceProperties props;
props = getProperties(ref.getId());
if (props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION))
{
ContentCollection c = getCollection(ref.getId());
rv = "Collection: " + c.getProperties().getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME) + " ("
+ c.getId() + ")\n" + " Created: "
+ c.getProperties().getPropertyFormatted(ResourceProperties.PROP_CREATION_DATE) + " by "
+ c.getProperties().getPropertyFormatted(ResourceProperties.PROP_CREATOR) + "(User Id:"
+ c.getProperties().getProperty(ResourceProperties.PROP_CREATOR) + ")\n"
+ StringUtil.limit(c.getProperties().getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION), 30);
}
else
{
ContentResource r = getResource(ref.getId());
rv = "Resource: " + r.getProperties().getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME) + " (" + r.getId()
+ ")\n" + " Created: " + r.getProperties().getPropertyFormatted(ResourceProperties.PROP_CREATION_DATE)
+ " by " + r.getProperties().getPropertyFormatted(ResourceProperties.PROP_CREATOR) + "(User Id:"
+ r.getProperties().getProperty(ResourceProperties.PROP_CREATOR) + ")\n"
+ StringUtil.limit(r.getProperties().getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION), 30);
}
} catch (PermissionException e) {
M_log.error("PermissionEception:", e);
} catch (IdUnusedException e) {
M_log.error("IdUnusedException:", e);
} catch (EntityPropertyNotDefinedException e) {
M_log.error("EntityPropertyNotDefinedException:", e);
} catch (EntityPropertyTypeException e) {
M_log.error("EntityPropertyTypeException:", e);
} catch (TypeException e) {
M_log.error("TypeException:", e);
}
return rv;
}
/**
* {@inheritDoc}
*/
public ResourceProperties getEntityResourceProperties(Reference ref)
{
// double check that it's mine
if (!APPLICATION_ID.equals(ref.getType())) return null;
ResourceProperties props = null;
try
{
props = getProperties(ref.getId());
}
catch (PermissionException e)
{
}
catch (IdUnusedException e)
{
}
return props;
}
/**
* {@inheritDoc}
*/
public String[] myToolIds()
{
String[] toolIds = { "sakai.resources" };
return toolIds;
}
/**
* {@inheritDoc}
*/
public void contextCreated(String context, boolean toolPlacement)
{
if (toolPlacement)
{
enableResources(context);
}
}
/**
* {@inheritDoc}
*/
public void contextUpdated(String context, boolean toolPlacement)
{
if (toolPlacement)
{
enableResources(context);
}
}
/**
* {@inheritDoc}
*/
public void contextDeleted(String context, boolean toolPlacement)
{
// TODO This avoids disabling the collection if the tool still exists, but ...
// does it catch the case where the tool is being deleted from the site?
if (toolPlacement)
{
disableResources(context);
}
}
/**
* Make sure a home in resources exists for the site.
*
* @param site
* The site.
*/
protected void enableResources(String context)
{
unlockCheck(SITE_UPDATE_ACCESS, context);
// it would be called
String id = getSiteCollection(context);
// does it exist?
try
{
Site site = m_siteService.getSite(context);
try
{
ContentCollection collection = findCollection(id); // getCollection(id); //
if(collection == null)
{
// make it
try
{
ContentCollectionEdit edit = addValidPermittedCollection(id);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, site.getTitle());
commitCollection(edit);
collection = findCollection(id);
}
catch (IdUsedException e)
{
M_log.warn("enableResources: " + e);
collection = findCollection(id);
}
catch (InconsistentException e)
{
// Because the id is coming from getSiteCollection(), this will never occur.
// If it does, we better get alerted to it.
M_log.warn("enableResources: " + e);
throw new RuntimeException(e);
}
}
// do we need to update the title?
if (!site.getTitle().equals(collection.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)))
{
try
{
ContentCollectionEdit edit = editCollection(id);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, site.getTitle());
commitCollection(edit);
}
catch (IdUnusedException e)
{
M_log.warn("enableResources: " + e);
throw new RuntimeException(e);
}
catch (PermissionException e)
{
M_log.warn("enableResources: " + e);
throw new RuntimeException(e);
}
catch (InUseException e)
{
M_log.warn("enableResources: " + e);
throw new RuntimeException(e);
}
}
}
catch (TypeException e)
{
M_log.warn("enableResources: " + e);
throw new RuntimeException(e);
}
}
catch (IdUnusedException e)
{
// TODO: -ggolden
M_log.warn("enableResources: " + e);
throw new RuntimeException(e);
}
}
/**
* Remove resources area for a site.
*
* @param site
* The site.
*/
protected void disableResources(String context)
{
// TODO: we do nothing now - resources hang around after the tool is removed from the site or the site is deleted -ggolden
}
/**
* Make sure a home in resources for dropbox exists for the site.
*
* @param site
* The site.
*/
protected void enableDropbox(String context)
{
// create it and the user folders within
createDropboxCollection(context);
}
/**
* Remove resources area for a site.
*
* @param site
* The site.
*/
protected void disableDropbox(String context)
{
// TODO: we do nothing now - dropbox resources hang around after the tool is removed from the site or the site is deleted -ggolden
}
/**********************************************************************************************************************************************************************************************************************************************************
* etc
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Archive the collection, then the members of the collection - recursively for collection members.
*
* @param collection
* The collection whose members are to be archived.
* @param doc
* The document to contain the xml.
* @param stack
* The stack of elements, the top of which will be the containing element of the "collection" or "resource" element.
* @param storagePath
* The path to the folder where we are writing files.
* @param siteCollectionId
* The resource id of the site collection.
* @param results
* A log of messages from the archive.
*/
protected void archiveCollection(ContentCollection collection, Document doc, Stack stack, String storagePath,
String siteCollectionId, StringBuilder results)
{
// first the collection
Element el = collection.toXml(doc, stack);
// store the relative file id in the xml
el.setAttribute("rel-id", collection.getId().substring(siteCollectionId.length()));
results.append("archiving collection: " + collection.getId() + "\n");
// now each member
List members = collection.getMemberResources();
if ((members == null) || (members.size() == 0)) return;
for (int i = 0; i < members.size(); i++)
{
Object member = members.get(i);
if (member instanceof ContentCollection)
{
archiveCollection((ContentCollection) member, doc, stack, storagePath, siteCollectionId, results);
}
else if (member instanceof ContentResource)
{
results.append(archiveResource((ContentResource) member, doc, stack, storagePath, siteCollectionId));
}
}
} // archiveCollection
/**
* Archive a singe resource
*
* @param resource
* The content resource to archive
* @param doc
* The XML document.
* @param stack
* The stack of elements.
* @param storagePath
* The path to the folder where we are writing files.
* @param siteCollectionId
* The resource id of the site collection (optional).
* @return A log of messages from the archive.
*/
protected String archiveResource(ContentResource resource, Document doc, Stack stack, String storagePath,
String siteCollectionId)
{
// form the xml
Element el = resource.toXml(doc, stack);
// remove the content from the xml
el.removeAttribute("body");
// write the content to a file
String fileName = idManager.createUuid();
InputStream stream = null;
FileOutputStream out = null;
try
{
stream = resource.streamContent();
out = new FileOutputStream(storagePath + fileName);
byte[] chunk = new byte[STREAM_BUFFER_SIZE];
int lenRead;
while ((lenRead = stream.read(chunk)) != -1)
{
out.write(chunk, 0, lenRead);
}
}
catch (IOException e)
{
M_log.warn("archiveResource(): while writing body for: " + resource.getId() + " : " + e);
} catch (ServerOverloadException e) {
M_log.warn("archiveResource(): while writing body for: " + resource.getId() + " : " + e);
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (IOException e)
{
M_log.error("IOException ", e);
}
}
if (out != null)
{
try
{
out.close();
}
catch (IOException e)
{
M_log.error("IOException ", e);
}
}
}
// store the file name in the xml
el.setAttribute("body-location", fileName);
// store the relative file id in the xml
if (siteCollectionId != null)
{
el.setAttribute("rel-id", resource.getId().substring(siteCollectionId.length()));
}
return "archiving resource: " + resource.getId() + " body in file: " + fileName + "\n";
}
/**
* Merge in a collection from an XML DOM definition. Take whole if not defined already. Ignore if already here.
*
* @param element
* The XML DOM element containing the collection definition.
* @exception PermissionException
* if the user does not have permission to add a collection.
* @exception InconsistentException
* if the containing collection does not exist.
* @exception IdInvalidException
* if the id is not valid.
* @return a new ContentCollection object, or null if it was not created.
*/
protected ContentCollection mergeCollection(Element element) throws PermissionException, InconsistentException,
IdInvalidException
{
// read the collection object
BaseCollectionEdit collectionFromXml = new BaseCollectionEdit(element);
String id = collectionFromXml.getId();
// add it
BaseCollectionEdit edit = null;
try
{
edit = (BaseCollectionEdit) addCollection(id);
}
catch (IdUsedException e)
{
// ignore if it exists
return null;
}
// transfer from the XML read object to the edit
edit.set(collectionFromXml);
try
{
Time createTime = edit.getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
}
catch(EntityPropertyNotDefinedException epnde)
{
String now = timeService.newTime().toString();
edit.getProperties().addProperty(ResourceProperties.PROP_CREATION_DATE, now);
}
catch(EntityPropertyTypeException epte)
{
M_log.error(epte);
}
// setup the event
edit.setEvent(EVENT_RESOURCE_ADD);
// commit the change
commitCollection(edit);
return edit;
} // mergeCollection
/**
* Merge in a resource from an XML DOM definition. Ignore if already defined. Take whole if not.
*
* @param element
* The XML DOM element containing the collection definition.
* @exception PermissionException
* if the user does not have permission to add a resource.
* @exception InconsistentException
* if the containing collection does not exist.
* @exception IdInvalidException
* if the id is not valid.
* @exception OverQuotaException
* if this would result in being over quota.
* @exception ServerOverloadException
* if the server is configured to write the resource body to the filesystem and the save fails.
* @return a new ContentResource object, or null if it was not created.
* @deprecated Use {@link #mergeResource(Element, InputStream)}. (KNL-898)
*/
protected ContentResource mergeResource(Element element) throws PermissionException, InconsistentException, IdInvalidException,
OverQuotaException, ServerOverloadException
{
return mergeResource(element, (InputStream) null);
} // mergeResource
/**
* Merge in a resource from an XML DOM definition and a body bytes array. Ignore if already defined. Take whole if not.
*
* @param element
* The XML DOM element containing the collection definition.
* @param in
* The body bytes.
* @exception PermissionException
* if the user does not have permission to add a resource.
* @exception InconsistentException
* if the containing collection does not exist.
* @exception IdInvalidException
* if the id is not valid.
* @exception OverQuotaException
* if this would result in being over quota.
* @return a new ContentResource object, or null if it was not created.
*/
protected ContentResource mergeResource(Element element, InputStream in) throws PermissionException, InconsistentException,
IdInvalidException, OverQuotaException, ServerOverloadException
{
// make the resource object
BaseResourceEdit resourceFromXml = new BaseResourceEdit(element);
String id = resourceFromXml.getId();
// get it added
BaseResourceEdit edit = null;
try
{
edit = (BaseResourceEdit) addResource(id);
}
catch (IdUsedException e)
{
// ignore the add if it exists already
return null;
}
// transfer the items of interest (content type, properties) from the XML read object to the edit.
edit.setContentType(resourceFromXml.getContentType());
ResourcePropertiesEdit p = edit.getPropertiesEdit();
p.clear();
p.addAll(resourceFromXml.getProperties());
// if input stream is provided, use it
if (in != null)
{
edit.setContent(in);
}
// setup the event
edit.setEvent(EVENT_RESOURCE_ADD);
// commit the change - Note: we do properties differently
assureResourceProperties(edit);
// check for over quota.
if (overQuota(edit))
{
throw new OverQuotaException(edit.getReference());
}
// complete the edit
m_storage.commitResource(edit);
if(! readyToUseFilesizeColumn())
{
addSizeCache(edit);
}
// track it
String ref = edit.getReference(null);
eventTrackingService.post(eventTrackingService.newEvent(((BaseResourceEdit) edit).getEvent(), ref, true,
NotificationService.NOTI_NONE));
postAvailableEvent(edit, ref, NotificationService.NOTI_NONE);
// close the edit object
((BaseResourceEdit) edit).closeEdit();
return edit;
} // mergeResource
/**
* Find the containing collection id of a given resource id.
*
* @param id
* The resource id.
* @return the containing collection id.
*/
protected String isolateContainingId(String id)
{
// take up to including the last resource path separator, not counting one at the very end if there
return id.substring(0, id.lastIndexOf('/', id.length() - 2) + 1);
} // isolateContainingId
/**
* Find the resource name of a given resource id.
*
* @param id
* The resource id.
* @return the resource name.
*/
protected String isolateName(String id)
{
if (id == null) return null;
if (id.length() == 0) return null;
// take after the last resource path separator, not counting one at the very end if there
boolean lastIsSeparator = id.charAt(id.length() - 1) == '/';
return id.substring(id.lastIndexOf('/', id.length() - 2) + 1, (lastIsSeparator ? id.length() - 1 : id.length()));
} // isolateName
/**
* Check the fixed type and id infomation: The same or better content type based on the known type for this id's extension, if any. The same or added extension id based on the know MIME type, if any Only if the type is the unknown type already.
*
* @param id
* The resource id with possible file extension to check.
* @param type
* The content type.
* @return the best guess content type based on this resource's id and resource id with extension based on this resource's MIME type.
*/
protected Map fixTypeAndId(String id, String type)
{
// the HashMap holds the id and mime type
HashMap extType = new HashMap();
extType.put("id", id);
if (type == null) type = "";
extType.put("type", type);
String extension = Validator.getFileExtension(id);
if (extension.length() != 0)
{
// if there's a file extension and a blank, null or unknown(application/binary) mime type,
// fix the mime type by doing a lookup based on the extension
if (((type == null) || (type.length() == 0) || (contentTypeImageService.isUnknownType(type))))
{
extType.put("type", contentTypeImageService.getContentType(extension));
}
}
else
{
// if there is no file extension, but a non-null, non-blank mime type, do a lookup based on the mime type and add an extension
// if there is no extension, find one according to the MIME type and add it.
if ((type != null) && (!type.equals("")) && (!contentTypeImageService.isUnknownType(type)))
{
extension = contentTypeImageService.getContentTypeExtension(type);
if (extension.length() > 0)
{
id = id + "." + extension;
extType.put("id", id);
}
}
else
{
// if mime type is null or mime type is empty or mime and there is no extension
if ((type == null) || (type.equals("")))
{
extType.put("type", "application/binary");
}
// htripath- SAK-1811 remove '.bin' extension from binary file without any extension e.g makeFile
// id = id + ".bin";
extType.put("id", id);
}
}
return extType;
} // fixTypeAndId
/**
* Test if this resource edit would place the account" over quota.
*
* @param edit
* The proposed resource edit.
* @return true if this change would palce the "account" over quota, false if not.
*/
protected boolean overQuota(ContentResourceEdit edit)
{
// Note: This implementation is hard coded to just check for a quota in the "/user/"
// or "/group/" area. -ggolden
// Note: this does NOT count attachments (/attachments/*) nor dropbox (/group-user/<site id>/<user id>/*) -ggolden
// quick exits if we are not doing site quotas
// if (m_siteQuota == 0)
// return false;
// some quick exits, if we are not doing user quota, or if this is not a user or group resource
// %%% These constants should be from somewhere else -ggolden
if (!((edit.getId().startsWith(COLLECTION_USER)) || (edit.getId().startsWith(COLLECTION_SITE)) || edit.getId().startsWith(COLLECTION_DROPBOX))) return false;
// expect null, "user" | "group", user/groupid, rest...
String[] parts = StringUtil.split(edit.getId(), Entity.SEPARATOR);
if (parts.length <= 2) return false;
// get this collection
String id = Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR;
ContentCollection collection = null;
try
{
collection = findCollection(id);
// Limit size per user inside dropbox
if (edit.getId().startsWith(COLLECTION_DROPBOX)) {
try {
// if successful, the context is already a valid user id
userDirectoryService.getUser(parts[3]);
collection = findCollection(id + parts[3] + Entity.SEPARATOR);
} catch (UserNotDefinedException tryEid) {
// Nothing to do
}
}
}
catch (TypeException ignore)
{
}
if (collection == null) return false;
long quota = getQuota(collection);
if (quota == 0)
{
return false;
}
long size = 0;
if(readyToUseFilesizeColumn())
{
size = collection.getBodySizeK();
}
else
{
M_log.error("File size column is not ready. Unable to calculate size of collection. Something is wrong with this instance of Sakai. Please check for other startup errors.");
return false;
}
// find the resource being edited
ContentResource inThere = null;
try
{
inThere = findResource(edit.getId());
}
catch (TypeException ignore)
{
}
if (inThere != null)
{
// reduce the size by the existing size
size -= bytes2k(inThere.getContentLength());
}
// add in the new size
size += bytes2k(edit.getContentLength());
return (size >= quota);
} // overQuota
/**
* @param collection
* @return
*/
/*
* Size Cache.
* This caches the size of the collection and all children for 10 miutes from first
* created, keeping a track of addtions and removals to the collection.
*
* It only works where the same collection id is supplied and does not
* consider the size under nested collections or update modifcations
* on all nested collections.
*
* It is a temporary fix to eliminate GC collection issues with the size calculations
*/
protected static class SizeHolder {
public long ttl = System.currentTimeMillis()+600000L;
public long size = 0;
}
private Map<String, SizeHolder> quotaMap = new ConcurrentHashMap<String, SizeHolder>();
private Map<String, SiteContentAdvisorProvider> siteContentAdvisorsProviders = new HashMap<String, SiteContentAdvisorProvider>();
/**
* @param collection
* @return
*/
protected void removeSizeCache(ContentResourceEdit edit)
{
// Note: This implementation is hard coded to just check for a quota in the "/user/"
// or "/group/" area. -ggolden
// Note: this does NOT count attachments (/attachments/*) nor dropbox (/group-user/<site id>/<user id>/*) -ggolden
// quick exits if we are not doing site quotas
// if (m_siteQuota == 0)
// return false;
// some quick exits, if we are not doing user quota, or if this is not a user or group resource
// %%% These constants should be from somewhere else -ggolden
if (!((edit.getId().startsWith("/user/")) || (edit.getId().startsWith("/group/")))) return;
// expect null, "user" | "group", user/groupid, rest...
String[] parts = StringUtil.split(edit.getId(), Entity.SEPARATOR);
if (parts.length <= 2) return;
// get this collection
String id = Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR;
ContentCollection collection = null;
try
{
collection = findCollection(id);
}
catch (TypeException ignore)
{
}
if (collection == null) return;
} // updateSizeCache();
protected void addSizeCache(ContentResourceEdit edit)
{
// Note: This implementation is hard coded to just check for a quota in the "/user/"
// or "/group/" area. -ggolden
// Note: this does NOT count attachments (/attachments/*) nor dropbox (/group-user/<site id>/<user id>/*) -ggolden
// quick exits if we are not doing site quotas
// if (m_siteQuota == 0)
// return false;
// some quick exits, if we are not doing user quota, or if this is not a user or group resource
// %%% These constants should be from somewhere else -ggolden
if (!((edit.getId().startsWith("/user/")) || (edit.getId().startsWith("/group/")))) return;
// expect null, "user" | "group", user/groupid, rest...
String[] parts = StringUtil.split(edit.getId(), Entity.SEPARATOR);
if (parts.length <= 2) return;
// get this collection
String id = Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR;
ContentCollection collection = null;
try
{
collection = findCollection(id);
}
catch (TypeException ignore)
{
}
if (collection == null) return;
} // updateSizeCache();
/**
* Convert bytes to Kbytes, rounding up, and counting even 0 bytes as 1 k.
*
* @param bytes
* The size in bytes.
* @return The size in Kbytes, rounded up.
*/
protected long bytes2k(long bytes)
{
return ((bytes - 1) / 1024) + 1;
} // bytes2k
/**
* gets the quota for a site collection or for a user's my workspace collection
*
* @param collection the collection on which to test for a quota. this can be the collection for a site
* or a user's workspace collection
* @return the quota in kb
*/
public long getQuota(ContentCollection collection) {
long quota = m_siteQuota;
String default_quota = DEFAULT_RESOURCE_QUOTA;
ContentCollection parentCollection = null;
// parse a string like /user/344454534543534535353543535
String[] parts = StringUtil.split(collection.getId(), Entity.SEPARATOR);
if (parts.length >= 3) {
String siteId = null;
// SITE_ID come in 2 forms (~siteid||siteid)
if (parts[1].equals("user")) {
siteId = "~" + parts[2];
} else {
siteId = parts[2];
}
if (collection.getId().startsWith(COLLECTION_DROPBOX)) {
default_quota = DEFAULT_DROPBOX_QUOTA;
quota = m_dropBoxQuota;
try {
parentCollection = findCollection(Entity.SEPARATOR + parts[1] + Entity.SEPARATOR + parts[2] + Entity.SEPARATOR);
} catch (TypeException tex) {
}
}
String siteType = null;
// get the site type
try {
siteType = m_siteService.getSite(siteId).getType();
} catch (IdUnusedException e) {
M_log.error("Quota calculation could not find the site '"+ siteId + "' to determine the type.", e);
}
// use this quota unless we have one more specific
if (siteType != null) {
quota = Long.parseLong(m_serverConfigurationService.getString(default_quota + siteType, Long.toString(collection.getId().startsWith(COLLECTION_DROPBOX)?m_dropBoxQuota:m_siteQuota)));
}
}
// see if this collection has a quota property
try
{
long siteSpecific = collection.getProperties().getLongProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
quota = siteSpecific;
}
catch (EntityPropertyNotDefinedException ignore)
{
// don't log or anything, this just means that this site doesn't have this quota property.
// Look for dropBox quota in parent collection
try {
if (parentCollection!=null) {
long siteSpecific = parentCollection.getProperties().getLongProperty(
ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
quota = siteSpecific;
}
} catch (EntityPropertyTypeException ignoretex) {
// don't log or anything, this just means that this site doesn't have this quota property.
} catch (EntityPropertyNotDefinedException ignoreex) {
// don't log or anything, this just means that this site doesn't have this quota property.
}
}
catch (Exception ignore)
{
M_log.warn("getQuota: reading quota property of : " + collection.getId() + " : " + ignore);
}
return quota;
}
/**
* Attempt to create any collections needed so that the parameter collection exists.
*
* @param target
* The collection that we want to exist.
*/
protected void generateCollections(String target)
{
try
{
// check each collection from the root
String[] parts = StringUtil.split(target, "/");
String id = "/";
StringBuilder idBuilder = new StringBuilder();
idBuilder.append(id);
for (int i = 1; i < parts.length; i++)
{
// grow the id to the next collection
idBuilder.append(parts[i] + "/");
// does it exist?
ContentCollection collection = findCollection(idBuilder.toString());
// if not, can we make it
if (collection == null)
{
ContentCollectionEdit edit = addValidPermittedCollection(idBuilder.toString());
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, parts[i]);
commitCollection(edit);
}
}
}
// if we cannot, give up
catch (Exception any)
{
M_log.error("generateCollections: " + any.getMessage(), any);
}
} // generateCollections
/**
* {@inheritDoc}
*/
public String getSiteCollection(String siteId)
{
String rv = null;
if (m_siteService.isUserSite(siteId))
{
rv = COLLECTION_USER + m_siteService.getSiteUserId(siteId) + "/";
}
else if (!m_siteService.isSpecialSite(siteId))
{
rv = COLLECTION_SITE + siteId + "/";
}
else
{
// ???
rv = "/";
}
return rv;
}
/**
* {@inheritDoc}
*/
public boolean isPubView(String id)
{
boolean pubView = m_securityService.unlock(userDirectoryService.getAnonymousUser(), AUTH_RESOURCE_READ, getReference(id));
return pubView;
}
/**
* {@inheritDoc}
*/
public boolean isInheritingPubView(String id)
{
// the root does not inherit... and makes a bad ref if we try to isolateContainingId()
if (isRootCollection(id)) return false;
// check for pubview on the container
String containerId = isolateContainingId(id);
boolean pubView = m_securityService.unlock(userDirectoryService.getAnonymousUser(), AUTH_RESOURCE_READ,
getReference(containerId));
return pubView;
}
/**
* Set this resource or collection to the pubview setting.
*
* @param id
* The resource or collection id.
* @param pubview
* The desired public view setting.
*/
public void setPubView(String id, boolean pubview)
{
// TODO: check efficiency here -ggolden
String ref = getReference(id);
// edit the realm
AuthzGroup edit = null;
try
{
edit = m_authzGroupService.getAuthzGroup(ref);
}
catch (GroupNotDefinedException e)
{
// if no realm yet, and we need one, make one
if (pubview)
{
try
{
edit = m_authzGroupService.addAuthzGroup(ref);
}
catch (Exception ee)
{
M_log.warn("Failed to add AZG ("+ref+") for pubview: " + ee);
}
}
}
// if we have no realm and don't need one, we are done
// if we need a realm and didn't get an edit, exception
if (edit == null) {
return;
}
// this makes no sense... -AZ
// // if we have no realm and don't need one, we are done
// if ((edit == null) && (!pubview)) return;
//
// // if we need a realm and didn't get an edit, exception
// if ((edit == null) && pubview) return;
boolean changed = false;
boolean delete = false;
// align the realm with our positive setting
if (pubview)
{
// make sure the anon role exists and has "content.read" - the only client of pubview
Role role = edit.getRole(AuthzGroupService.ANON_ROLE);
if (role == null)
{
try
{
role = edit.addRole(AuthzGroupService.ANON_ROLE);
// moved from below as part of NPE cleanup -AZ
if (!role.isAllowed(AUTH_RESOURCE_READ))
{
role.allowFunction(AUTH_RESOURCE_READ);
changed = true;
}
}
catch (RoleAlreadyDefinedException ignore)
{
role = null;
}
}
}
// align the realm with our negative setting
else
{
// get the role
Role role = edit.getRole(AuthzGroupService.ANON_ROLE);
if (role != null)
{
if (role.isAllowed(AUTH_RESOURCE_READ))
{
changed = true;
role.disallowFunction(AUTH_RESOURCE_READ);
}
if (role.allowsNoFunctions())
{
edit.removeRole(role.getId());
changed = true;
}
}
// if "empty", we can delete the realm
if (edit.isEmpty()) delete = true;
}
// if we want the realm deleted
if (delete)
{
try
{
m_authzGroupService.removeAuthzGroup(edit);
}
catch (AuthzPermissionException e)
{
}
}
// if we made a change
else if (changed)
{
try
{
m_authzGroupService.save(edit);
}
catch (GroupNotDefinedException e)
{
// TODO: IdUnusedException
}
catch (AuthzPermissionException e)
{
// TODO: PermissionException
}
}
}
/**
* {@inheritDoc}
*/
public List<ContentResource> findResources(String type, String primaryMimeType, String subMimeType, Set<String> contextIds)
{
List globalList = new ArrayList();
Iterator siteIt = contextIds.iterator();
while (siteIt.hasNext())
{
String collId = getSiteCollection( (String)siteIt.next() );
List artifacts = getFlatResources(collId);
globalList.addAll(filterArtifacts(artifacts, type, primaryMimeType, subMimeType, true));
}
return globalList;
}
/**
* {@inheritDoc}
*/
public List<ContentResource> findResources(String type, String primaryMimeType, String subMimeType)
{
List globalList = new ArrayList();
Map othersites = getCollectionMap();
Iterator siteIt = othersites.entrySet().iterator();
while (siteIt.hasNext())
{
Entry entry = (Entry) siteIt.next();
String collId = (String) entry.getKey();
List artifacts = getFlatResources(collId);
globalList.addAll(filterArtifacts(artifacts, type, primaryMimeType, subMimeType, true));
}
return globalList;
}
/**
* get all the resources under a given directory.
*
* @param parentId
* @return List of all the ContentResource objects under this directory.
*/
protected List getFlatResources(String parentId)
{
return getAllResources(parentId);
}
/**
* Eliminate from the collection any duplicates as well as any items that are contained within another item whose resource-id is in the collection.
*
* @param resourceIds
* A collection of strings (possibly empty) identifying items and/or collections.
*/
public void eliminateDuplicates(Collection resourceIds)
{
// eliminate exact duplicates
Set others = new TreeSet(resourceIds);
// eliminate items contained in other items
Iterator itemIt = resourceIds.iterator();
while (itemIt.hasNext())
{
String item = (String) itemIt.next();
Iterator otherIt = others.iterator();
while (otherIt.hasNext())
{
String other = (String) otherIt.next();
if (other.startsWith(item))
{
if (item.equals(other))
{
continue;
}
// item contains other
otherIt.remove();
}
}
}
// if any items have been removed, update the original collection
if (resourceIds.size() > others.size())
{
resourceIds.clear();
resourceIds.addAll(others);
}
} // eliminate duplicates
protected List filterArtifacts(List artifacts, String type, String primaryMimeType, String subMimeType)
{
return filterArtifacts(artifacts, type, primaryMimeType, subMimeType, false);
}
protected List filterArtifacts(List artifacts, String type, String primaryMimeType, String subMimeType, boolean checkPerms)
{
for (Iterator i = artifacts.iterator(); i.hasNext();)
{
ContentResource resource = (ContentResource) i.next();
//check for read permissions...
if (!checkPerms || unlockCheck(AUTH_RESOURCE_READ, resource.getId()))
{
String currentType = resource.getProperties().getProperty(ResourceProperties.PROP_STRUCTOBJ_TYPE);
String mimeType = resource.getProperties().getProperty(ResourceProperties.PROP_CONTENT_TYPE);
if (type != null && !type.equals(ResourceProperties.FILE_TYPE))
{
// process StructuredObject type
if (currentType == null)
{
i.remove();
}
else if (!currentType.equals(type))
{
i.remove();
}
}
else if (currentType != null && type != null && type.equals(ResourceProperties.FILE_TYPE))
{
// this one is a structured object, get rid of it
i.remove();
}
else
{
String[] parts = mimeType.split("/");
String currentPrimaryType = parts[0];
String currentSubtype = null;
if (parts.length > 1) currentSubtype = parts[1];
// check the mime type match
if (primaryMimeType != null && !primaryMimeType.equals(currentPrimaryType))
{
i.remove();
}
else if (subMimeType != null && !subMimeType.equals(currentSubtype))
{
i.remove();
}
}
}
else {
i.remove();
}
}
return artifacts;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Dropbox Stuff
*********************************************************************************************************************************************************************************************************************************************************/
protected static final String DEFAULT_RESOURCECLASS = "org.sakaiproject.localization.util.ContentProperties";
protected static final String DEFAULT_RESOURCEBUNDLE = "org.sakaiproject.localization.bundle.content.content";
protected static final String RESOURCECLASS = "resource.class.content";
protected static final String RESOURCEBUNDLE = "resource.bundle.content";
private ResourceLoader rb = null;
protected static final String DROPBOX_ID = " Drop Box";
public static final String SITE_UPDATE_ACCESS = "site.upd";
protected static final String GROUP_LIST = "sakai:authzGroup";
protected static final String GROUP_NAME = "sakai:group_name";
public static final String ACCESS_MODE = "sakai:access_mode";
public static final String RELEASE_DATE = "sakai:release_date";
public static final String RETRACT_DATE = "sakai:retract_date";
public static final String HIDDEN = "sakai:hidden";
public static final String CUSTOM_ORDER = "sakai:custom_order";
public static final String CUSTOM_RANK = "sakai:rank_element";
public static final String MEMBER_ID = "sakai:member_id";
public static final String RANK = "sakai:rank";
/**
* @inheritDoc
*/
public String getDropboxCollection()
{
return getDropboxCollection(toolManager.getCurrentPlacement().getContext());
}
/**
* @inheritDoc
*/
public String getDropboxCollection(String siteId)
{
String rv = null;
// make sure we are in a worksite, not a workspace
if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId))
{
return rv;
}
// form the site's dropbox collection
rv = COLLECTION_DROPBOX + siteId + "/";
// for maintainers or users with groups access, use the site level
if ((isDropboxMaintainer(siteId))||(isDropboxGroups(siteId)))
{
// return the site's dropbox collection
return rv;
}
// Anonymous users do not get drop boxes
String userId = sessionManager.getCurrentSessionUserId();
if ( userId == null ) return rv;
// form the current user's dropbox collection within this site's
rv += StringUtil.trimToZero(userId) + "/";
return rv;
}
/**
* Access the default dropbox collection display name for the current request. If the current user has permission to modify the site's dropbox collection, this is returned. Otherwise, the current user's collection within the site's dropbox is
* returned.
*
* @return The default dropbox collection display name for the current request.
*/
public String getDropboxDisplayName()
{
return getDropboxDisplayName(toolManager.getCurrentPlacement().getContext());
}
/**
* Access the default dropbox collection display name for the site. If the current user has permission to modify the site's dropbox collection, this is returned. Otherwise, the current user's collection within the site's dropbox is returned.
*
* @param siteId
* the Site id.
* @return The default dropbox collection display name for the site.
*/
public String getDropboxDisplayName(String siteId)
{
// make sure we are in a worksite, not a workspace
if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId))
{
return null;
}
// form the site's dropbox collection
String id = COLLECTION_DROPBOX + siteId + "/";
// for maintainers, use the site level dropbox
if (isDropboxMaintainer(siteId))
{
// return the site's dropbox collection
return siteId + DROPBOX_ID;
}
// return the current user's sort name
return userDirectoryService.getCurrentUser().getSortName();
}
/**
* Create the site's dropbox collection and one for each qualified user that the current user can make.
*/
public void createDropboxCollection()
{
createDropboxCollection(toolManager.getCurrentPlacement().getContext());
}
/**
* Create the site's dropbox collection and one for each qualified user that the current user can make.
*
* @param siteId
* the Site id.
*/
public void createDropboxCollection(String siteId)
{
// make sure we are in a worksite, not a workspace
if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId))
{
return;
}
// do our ONE security check to see if the current user can create the
// dropbox and all inner folders
if (!isDropboxMaintainer(siteId))
{
createIndividualDropbox(siteId);
return;
}
// form the site's dropbox collection
String dropbox = COLLECTION_DROPBOX + siteId + "/";
try
{
// try to create if it doesn't exist
if (findCollection(dropbox) == null)
{
ContentCollectionEdit edit = addValidPermittedCollection(dropbox);
ResourcePropertiesEdit props = edit.getPropertiesEdit();
try
{
Site site = m_siteService.getSite(siteId);
}
catch (IdUnusedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// these need to be moved to language bundle
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, siteId + DROPBOX_ID);
props.addProperty(ResourceProperties.PROP_DESCRIPTION, rb.getString("use2"));
// props.addProperty(ResourceProperties.PROP_DESCRIPTION, PROP_SITE_DROPBOX_DESCRIPTION);
commitCollection(edit);
}
}
catch (TypeException e)
{
M_log.warn("createDropboxCollection: TypeException: " + dropbox);
return;
}
catch (IdUsedException e)
{
M_log.warn("createDropboxCollection: IdUsedException: " + dropbox);
return;
}
catch (InconsistentException e)
{
M_log.warn("createDropboxCollection(): InconsistentException: " + dropbox);
M_log.warn("createDropboxCollection(): InconsistentException: " + e.getMessage());
return;
}
// catch (PermissionException e)
// {
// M_log.warn("createDropboxCollection(): PermissionException: " + dropbox);
// return;
// }
SortedSet<String> members = new TreeSet<String>();
try
{
ContentCollection topDropbox = findCollection(dropbox);
members.addAll((List<String>) topDropbox.getMembers());
}
catch(TypeException e)
{
M_log.warn("createDropboxCollection(): File exists where dropbox collection is expected: "+ dropbox);
}
// The AUTH_DROPBOX_OWN is granted within the site, so we can ask for all the users who have this ability
// using just the dropbox collection
List users = m_securityService.unlockUsers(AUTH_DROPBOX_OWN, getReference(dropbox));
for (Iterator it = users.iterator(); it.hasNext();)
{
User user = (User) it.next();
// the folder id for this user's dropbox in this group
String userFolder = dropbox + user.getId() + "/";
// see if it exists - add if it doesn't
try
{
if (!members.remove(userFolder))
{
if (findCollection(userFolder) == null) // This check it probably redundant
{
ContentCollectionEdit edit = addValidPermittedCollection(userFolder);
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, user.getSortName());
props.addProperty(ResourceProperties.PROP_DESCRIPTION, rb.getString("use1"));
commitCollection(edit);
}
}
}
catch (TypeException e)
{
M_log.warn("createDropboxCollectionn(): TypeException: " + userFolder);
}
catch (IdUsedException e)
{
M_log.warn("createDropboxCollectionn(): idUsedException: " + userFolder);
}
catch (InconsistentException e)
{
M_log.warn("createDropboxCollection(): InconsistentException: " + userFolder);
}
}
// Attempt to remove all empty dropboxes that are no longer members of the site.
for(String member : members) {
try
{
ContentCollection folder = getCollection(member);
if (folder.getMemberCount() == 0)
{
removeCollection(member);
M_log.info("createDropboxCollection(): Removed the empty dropbox collection for member: " + member);
} else {
M_log.warn("createDropboxCollection(): Could not remove the dropbox collection for member (" + member +") because the root contains "+folder.getMemberCount()+" members");
}
}
catch(IdUnusedException e)
{
M_log.warn("createDropboxCollection(): Could not find collection to delete: " + member);
}
catch(PermissionException e)
{
M_log.warn("createDropboxCollection(): Unable to delete collection due to lack of permission: " + member);
}
catch(InUseException e)
{
M_log.warn("createDropboxCollection(): Unable to delete collection as collection is in use: " + member);
}
catch(ServerOverloadException e)
{
M_log.warn("createDropboxCollection(): Unable to delete collection as server is overloaded: " + member);
}
catch(TypeException e)
{
M_log.warn("createDropboxCollection(): Unable to delete as it doesn't appear to be a collection: " + member);
}
}
}
/**
* Create an individual dropbox collection for the current user if the site-level dropbox exists
* and the current user has AUTH_DROPBOX_OWN for the site.
*
* @param siteId
* the Site id.
*/
public void createIndividualDropbox(String siteId)
{
String dropbox = COLLECTION_DROPBOX + siteId + "/";
try
{
if (findCollection(dropbox) == null)
{
try
{
ContentCollectionEdit edit = addValidPermittedCollection(dropbox);
commitCollection(edit);
}
catch(IdUsedException e)
{
// hmmmm ... couldn't find it, but it's already in use??? let's bail out.
return;
}
catch(InconsistentException e)
{
return;
}
}
User user = userDirectoryService.getCurrentUser();
// the folder id for this user's dropbox in this group
String userFolder = dropbox + user.getId() + "/";
if(m_securityService.unlock(AUTH_DROPBOX_OWN, getReference(dropbox)))
{
// see if it exists - add if it doesn't
try
{
if (findCollection(userFolder) == null)
{
ContentCollectionEdit edit = addValidPermittedCollection(userFolder);
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, user.getSortName());
props.addProperty(ResourceProperties.PROP_DESCRIPTION, rb.getString("use1"));
// props.addProperty(ResourceProperties.PROP_DESCRIPTION, PROP_MEMBER_DROPBOX_DESCRIPTION);
commitCollection(edit);
}
}
catch (TypeException e)
{
M_log.warn("createIndividualDropbox(): TypeException: " + userFolder);
}
catch (IdUsedException e)
{
M_log.warn("createIndividualDropbox(): idUsedException: " + userFolder);
}
catch (InconsistentException e)
{
M_log.warn("createIndividualDropbox(): InconsistentException: " + userFolder);
}
// catch (PermissionException e)
// {
// M_log.warn("createIndividualDropbox(): PermissionException: " + userFolder);
// }
}
}
catch (TypeException e)
{
M_log.warn("createIndividualDropbox(): TypeException: " + dropbox);
}
}
/**
* Determine whether the default dropbox collection id for this user in this site
* is the site's entire dropbox collection or just the current user's collection
* within the site's dropbox.
* @return True if user sees all dropboxes in the site, false otherwise.
*/
public boolean isDropboxMaintainer()
{
return isDropboxMaintainer(toolManager.getCurrentPlacement().getContext());
}
/**
* Determine whether the default dropbox collection id for this user in some site is the site's entire dropbox collection or just the current user's collection within the site's dropbox.
*
* @return True if user sees all dropboxes in the site, false otherwise.
*/
public boolean isDropboxMaintainer(String siteId)
{
String dropboxId = null;
// make sure we are in a worksite, not a workspace
if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId))
{
return false;
}
// if the user has dropbox maintain in the site, they are the dropbox maintainer
// (dropbox maintain in their myWorkspace just gives them access to their own dropbox)
return m_securityService.unlock(AUTH_DROPBOX_MAINTAIN, m_siteService.siteReference(siteId));
}
/**
* Determine whether the user has the dropbox.groups permission
*
* @return True if user has dropbox.groups permission, false otherwise.
*/
public boolean isDropboxGroups(String siteId)
{
String dropboxId = null;
// make sure we are in a worksite, not a workspace
if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId))
{
return false;
}
// if the user has dropbox maintain in the site, they are the dropbox maintainer
// (dropbox maintain in their myWorkspace just gives them access to their own dropbox)
return m_securityService.unlock(AUTH_DROPBOX_GROUPS, m_siteService.siteReference(siteId));
}
/******************************************************************************************************************************************************************************************************************************************************
* Group awareness implementation
*****************************************************************************************************************************************************************************************************************************************************/
/**
* Access a collection (Group) of groups to which this user has access and whose members have "content.read" permission in the collection.
* In effect, this method returns a collection that identifies groups that are defined for the collection (locally or inherited) that
* this user can access. If access to the collection is determined by group-membership, the return is limited to groups that have
* access to the specified collection. If access is not defined by groups (i.e. it is "site" access), the return includes all groups
* defined in the site for which this user has read permission.
*
* @param collectionId
* The id for the collection.
*/
public Collection getGroupsWithReadAccess(String collectionId)
{
Collection rv = new ArrayList();
String refString = getReference(collectionId);
Reference ref = m_entityManager.newReference(refString);
Collection groups = getGroupsAllowFunction(AUTH_RESOURCE_READ, ref.getReference());
if(groups != null && ! groups.isEmpty())
{
rv.addAll(groups);
}
return rv;
}
/**
* Access a collection (Group) of groups to which this user has access and whose members have "content.new" permission in the collection.
* In effect, this method returns a collection that identifies groups that are defined for the collection (locally or inherited) in which
* this user has permission to add content entities. If access to the collection is determined by group-membership, the return is limited
* to groups that have "add" permission in the specified collection. If access is not defined by groups (i.e. it is "site" access), the return
* includes all groups defined in the site for which this user has add permission in this collection.
*
* @param collectionId
* The id for the collection.
*/
public Collection getGroupsWithAddPermission(String collectionId)
{
Collection rv = new ArrayList();
String refString = getReference(collectionId);
Reference ref = m_entityManager.newReference(refString);
Collection groups = getGroupsAllowFunction(AUTH_RESOURCE_ADD, ref.getReference());
if(groups != null && ! groups.isEmpty())
{
rv.addAll(groups);
}
return rv;
}
/**
* Access a collection (Group) of groups to which this user has access and whose members have "content.delete" permission in the collection.
* In effect, this method returns a collection that identifies groups that are defined for the collection (locally or inherited) in which
* this user has permission to remove content entities. If access to the collection is determined by group-membership, the return is limited
* to groups that have "remove" permission in the specified collection. If access is not defined by groups (i.e. it is "site" access), the return
* includes all groups defined in the site for which this user has remove permission in this collection.
*
* @param collectionId
* The id for the collection.
*/
public Collection getGroupsWithRemovePermission(String collectionId)
{
Collection rv = new ArrayList();
String owner = "";
String currentUser = sessionManager.getCurrentSessionUserId();
try
{
ResourceProperties props = getProperties(collectionId);
owner = props.getProperty(ResourceProperties.PROP_CREATOR);
}
catch ( Exception e )
{
// assume user is not owner
}
String refString = getReference(collectionId);
Reference ref = m_entityManager.newReference(refString);
Collection groups = null;
if ( currentUser != null && currentUser.equals(owner) )
groups = getGroupsAllowFunction(AUTH_RESOURCE_REMOVE_OWN, ref.getReference());
else if ( currentUser == null && owner == null )
groups = getGroupsAllowFunction(AUTH_RESOURCE_REMOVE_OWN, ref.getReference());
else
groups = getGroupsAllowFunction(AUTH_RESOURCE_REMOVE_ANY, ref.getReference());
if(groups != null && ! groups.isEmpty())
{
rv.addAll(groups);
}
return rv;
}
/**
* Get a collection (Group) of groups that are defined in the containing context of a resource and that this user can access
* in the way described by a function string.
*
* @param function
* The function to check
* @param refString
* The reference for the resource.
*/
protected Collection getGroupsAllowFunction(String function, String refString)
{
Collection rv = new ArrayList();
Collection groups = new ArrayList();
Collection groupRefs = new TreeSet();
if(this.m_allowGroupResources)
{
ContentEntity entity;
try
{
Reference ref = m_entityManager.newReference(refString);
Site site = m_siteService.getSite(ref.getContext());
if(ref.getId().endsWith(Entity.SEPARATOR))
{
entity = findCollection(ref.getId());
}
else
{
entity = findResource(ref.getId());
}
if(entity != null)
{
if(AccessMode.INHERITED == entity.getAccess())
{
groups.addAll(entity.getInheritedGroupObjects());
groupRefs.addAll(entity.getInheritedGroups());
}
else
{
groups.addAll(entity.getGroupObjects());
groupRefs.addAll(entity.getGroups());
}
}
if(groups.isEmpty())
{
// get the channel's site's groups
groups.addAll(site.getGroups());
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
groupRefs.add(group.getReference());
}
}
if(m_securityService.isSuperUser())
{
rv.addAll(groups);
}
else if(m_securityService.unlock(AUTH_RESOURCE_ALL_GROUPS, site.getReference()) && entity != null && unlockCheck(function, entity.getId()))
{
rv.addAll(groups);
}
else
{
Collection hierarchy = getEntityHierarchyAuthzGroups(ref);
String userId = sessionManager.getCurrentSessionUserId();
for (Iterator i = groups.iterator(); i.hasNext();)
{
Group group = (Group) i.next();
if(group == null)
{
continue;
}
Collection azGroups = new ArrayList(hierarchy);
azGroups.add(group.getReference());
// check whether this user can take this action (function) on this resource
// based on membership in this group. If so, add the group.
if (m_authzGroupService.isAllowed(userId, function, azGroups))
{
rv.add(group);
}
}
}
}
catch (TypeException e1)
{
// ignore
}
catch(IdUnusedException e)
{
// ignore
}
}
return rv;
}
/**
* If the id is to the /user/ area, make an id that is based on the user EID not ID, if the EID is available.
* @param id The resource id.
* @return The modified id.
*/
protected String convertIdToUserEid(String id)
{
//SAK-18908/KNL-584 id could be null
if (id == null) {
return null;
}
if (id.startsWith("/user/"))
{
try
{
int pos = id.indexOf('/', 6);
String userId = id.substring(6, pos);
String userEid = userDirectoryService.getUserEid(userId);
String rv = "/user/" + userEid + id.substring(pos);
return rv;
}
catch (StringIndexOutOfBoundsException e) {}
catch (UserNotDefinedException e) {}
}
return id;
}
/**********************************************************************************************************************************************************************************************************************************************************
* ContentEntity implementation
*********************************************************************************************************************************************************************************************************************************************************/
public abstract class BasicGroupAwareEdit implements GroupAwareEdit, ThreadBound
{
/** Store the resource id */
protected String m_id = null;
/** The properties. */
protected ResourcePropertiesEdit m_properties = null;
/** The event code for this edit. */
protected String m_event = null;
/** Active flag. */
protected boolean m_active = false;
/** When true, the collection has been removed. */
protected boolean m_isRemoved = false;
/** The access mode for this entity (e.g., "group" vs "site") */
protected AccessMode m_access = AccessMode.INHERITED;
/** The date/time after which the entity should no longer be generally available */
protected Time m_retractDate = null;
/** The date/time before which the entity should not be generally available */
protected Time m_releaseDate = null;
/** The availability of the item */
protected boolean m_hidden = false;
/** The Collection of group-ids for groups with access to this entity. */
protected Collection m_groups = new ArrayList();
/** The "priority" of this entity in its containing collection, if a custom sort order is defined for that collection */
protected int m_customOrderRank = 0;
/** The "type" in the ResourceTypeRegistry that defines properties of this ContentEntity */
protected String m_resourceType;
protected boolean m_visibilityUpdated = false;
protected boolean m_accessUpdated;;
/**
* @inheritDoc
*/
public Collection getGroups()
{
return new ArrayList(m_groups);
}
/**
* @param context
* @return
*/
public String getContext()
{
String context = null;
Matcher contextMatcher = contextPattern.matcher(this.m_id);
if(contextMatcher.find())
{
String root = contextMatcher.group(1);
context = contextMatcher.group(2);
if(! root.equals("group/"))
{
context = "~" + context;
}
}
return context;
}
/**
* @inheritDoc
*/
public void clearGroupAccess() throws InconsistentException, PermissionException
{
if(this.m_access != AccessMode.GROUPED)
{
throw new InconsistentException(this.getReference());
}
if(this.m_groups.size() > 0) {
this.m_accessUpdated = true;
}
this.m_access = AccessMode.INHERITED;
this.m_groups.clear();
}
/**
* @inheritDoc
*/
public void clearPublicAccess() throws InconsistentException, PermissionException
{
if(isPubView(this.m_id)) {
this.m_accessUpdated = true;
}
setPubView(this.m_id, false);
this.m_access = AccessMode.INHERITED;
this.m_groups.clear();
}
public void setPublicAccess() throws PermissionException
{
if(! isPubView(this.m_id)) {
this.m_accessUpdated = true;
}
setPubView(this.m_id, true);
this.m_access = AccessMode.INHERITED;
this.m_groups.clear();
}
/**
* @inheritDoc
*/
public void setGroupAccess(Collection groups) throws InconsistentException, PermissionException
{
if (groups == null || groups.isEmpty())
{
throw new InconsistentException(this.getReference());
}
if(isInheritingPubView(this.m_id))
{
throw new InconsistentException(this.getReference());
}
if(isPubView(this.m_id))
{
setPubView(this.m_id, false);
}
SortedSet groupRefs = new TreeSet();
if(this.getInheritedAccess() == AccessMode.GROUPED)
{
this.m_accessUpdated = true;
groupRefs.addAll(this.getInheritedGroups());
}
else
{
try
{
Reference ref = m_entityManager.newReference(this.getReference());
Site site = m_siteService.getSite(ref.getContext());
Iterator iterator = site.getGroups().iterator();
while(iterator.hasNext())
{
Group group = (Group) iterator.next();
groupRefs.add(group.getReference());
}
}
catch (IdUnusedException e)
{
}
}
Collection newGroups = new ArrayList();
Iterator groupIt = groups.iterator();
while(groupIt.hasNext())
{
String groupRef = null;
Object obj = groupIt.next();
if(obj instanceof String)
{
groupRef = (String) obj;
}
else if(obj instanceof Group)
{
groupRef = ((Group) obj).getReference();
}
if(! groupRefs.contains(groupRef))
{
throw new InconsistentException(this.getReference());
}
newGroups.add(groupRef);
}
if(this.m_access != AccessMode.GROUPED || !(newGroups.containsAll(this.m_groups) && this.m_groups.containsAll(newGroups))) {
this.m_accessUpdated = true;
this.m_access = AccessMode.GROUPED;
this.m_groups.clear();
this.m_groups.addAll(newGroups);
}
}
/**
* Loads a collection of group references. Any items not found aren't
* included in the returned collection;
* @param groupRefs The group references to load.
* @return The group objects corresponding to the group references. Will
* not contain <code>null</code>.
*/
private Collection<Group> findGroupObjects(Collection<String> groupRefs)
{
Collection<Group> groups = new ArrayList<Group>();
for (String groupRef: groupRefs)
{
Group group = m_siteService.findGroup(groupRef);
if (group != null)
{
groups.add(group);
}
}
return groups;
}
/**
* @inheritDoc
* @see org.sakaiproject.content.api.GroupAwareEntity#getGroupObjects()
*/
public Collection getGroupObjects()
{
if(m_groups == null)
{
m_groups = new ArrayList();
}
return findGroupObjects(m_groups);
}
/**
* @inheritDoc
*/
public AccessMode getAccess()
{
return m_access;
}
/**
* @inheritDoc
* @see org.sakaiproject.content.api.GroupAwareEntity#getInheritedGroups()
*/
public Collection getInheritedGroups()
{
Collection groups = new ArrayList();
ContentEntity next = ((ContentEntity) this).getContainingCollection();
while(next != null && AccessMode.INHERITED.equals(next.getAccess()))
{
next = next.getContainingCollection();
}
if(next != null && AccessMode.GROUPED.equals(next.getAccess()))
{
groups.addAll(next.getGroups());
}
return groups;
}
/**
* @inheritDoc
* @see org.sakaiproject.content.api.GroupAwareEntity#getInheritedAccess()
*/
public AccessMode getInheritedAccess()
{
AccessMode access = AccessMode.INHERITED;
ContentCollection parent = ((ContentEntity) this).getContainingCollection();
if(parent != null)
{
access = parent.getAccess();
}
while(AccessMode.INHERITED == access && parent != null)
{
access = parent.getAccess();
parent = parent.getContainingCollection();
}
if(AccessMode.INHERITED == access)
{
access = AccessMode.SITE;
}
return access;
}
/**
* @inheritDoc
* @see org.sakaiproject.content.api.GroupAwareEntity#getInheritedGroupObjects()
*/
public Collection getInheritedGroupObjects()
{
return findGroupObjects(getInheritedGroups());
}
/**
* Determine whether current user can update the group assignments (add/remove groups) for the current resource.
* This is based on whether the user has adequate rights defined for the group (AUTH_RESOURCE_ADD) or for the
* containing collection of the resource (AUTH_RESOURCE_ADD).
* @param group The group ionvolved in the query.
* @return true if allowed, false otherwise.
*/
protected boolean allowGroupUpdate(Group group)
{
String resourceRef = getReference();
return allowGroupUpdate(group, resourceRef);
}
/**
* Determine whether current user can update the group assignments (add/remove groups) for a specified resource.
* This is based on whether the user has adequate rights defined for the group (AUTH_RESOURCE_ADD) or for the
* containing collection of the resource (AUTH_RESOURCE_ADD).
* @param group The group ionvolved in the query.
* @param resourceRef A reference string for the resource.
* @return true if allowed, false otherwise.
*/
protected boolean allowGroupUpdate(Group group, String resourceRef)
{
String collectionId = getContainingCollectionId(resourceRef);
return unlockCheck(AUTH_RESOURCE_ADD, group.getReference()) || unlockCheck(AUTH_RESOURCE_ADD, collectionId);
}
public Time getReleaseDate()
{
return m_releaseDate;
}
public Date getReleaseTime()
{
return new Date(m_releaseDate.getTime());
}
public Time getRetractDate()
{
return m_retractDate;
}
public Date getRetractTime()
{
return new Date(m_retractDate.getTime());
}
/**
* @return true if a change has been maded in any settings affecting visibility
* for this resource, or false otherwise.
*/
public boolean isVisibilityUpdated() {
return m_visibilityUpdated;
}
/**
* @return true if a change has been made in any settings affecting whether this
* entity can be accessed publicly, by members of a single site, or by members of
* one or more authz groups, or false otherwise.
*/
public boolean isAccessUpdated() {
return m_accessUpdated;
}
private boolean isConditionallyReleased(ContentEntity entity) {
return StringUtils.equalsIgnoreCase("true", entity.getProperties().getProperty(ConditionService.PROP_CONDITIONAL_RELEASE));
}
public boolean isAvailable()
{
boolean available = !this.isHidden();
boolean isHiddenWebFolder = false;
ContentEntity currentEntity = null;
try {
currentEntity = isCollection(this.m_id)?findCollection(m_id):findResource(m_id);
} catch (TypeException te) {
return false;
}
while (available && currentEntity != null) {
if(available && (currentEntity.getReleaseDate() != null || currentEntity.getRetractDate() != null || isConditionallyReleased(currentEntity)))
{
Time now = timeService.newTime();
if (currentEntity.getReleaseDate() != null) {
available = currentEntity.getReleaseDate().before(now);
}
if (available && currentEntity.getRetractDate() != null) {
available = currentEntity.getRetractDate().after(now);
}
if (available && isConditionallyReleased(currentEntity)) {
// first check for global rule satisfaction
String satisfiesRule = currentEntity.getProperties().getProperty("resource.satisfies.rule");
if (satisfiesRule == null) {
Collection<?> acl = (Collection<?>) currentEntity.getProperties().get("conditional_access_list");
if (acl == null) {
available = false;
} else {
// acl acts as a white list for availability
available = acl.contains(sessionManager.getCurrentSessionUserId());
}
} else {
available = Boolean.parseBoolean(satisfiesRule);
}
}
}
if (!available) {
return available;
}
if (available && !isHiddenWebFolder && currentEntity.getId().endsWith(Entity.SEPARATOR)) {
isHiddenWebFolder = "true".equals(currentEntity.getProperties().getProperty(ResourceProperties.PROP_HIDDEN_WITH_ACCESSIBLE_CONTENT));
}
currentEntity = currentEntity.getContainingCollection();
available = currentEntity!=null?!currentEntity.isHidden():available;
}
return (available && isHiddenWebFolder && this.getId().endsWith(Entity.SEPARATOR))?!available:available;
}
public boolean isHidden()
{
return this.m_hidden;
}
public void setReleaseDate(Time time)
{
if(time == null)
{
if(m_releaseDate != null) {
this.m_visibilityUpdated = true;
}
m_releaseDate = null;
}
else
{
if(m_releaseDate == null || m_releaseDate.compareTo(time) != 0) {
this.m_visibilityUpdated = true;
}
m_releaseDate = timeService.newTime(time.getTime());
}
m_hidden = false;
}
public void setReleaseTime(Date date)
{
setReleaseDate(timeService.newTime(date.getTime()));
}
public void setRetractDate(Time time)
{
if(time == null)
{
if(m_retractDate != null) {
this.m_visibilityUpdated = true;
}
m_retractDate = null;
}
else
{
if(m_retractDate == null || m_retractDate.compareTo(time) != 0) {
this.m_visibilityUpdated = true;
}
m_retractDate = timeService.newTime(time.getTime());
}
m_hidden = false;
}
public void setRetractTime(Date time)
{
setRetractDate(timeService.newTime(time.getTime()));
}
public void setAvailability(boolean hidden, Time releaseDate, Time retractDate)
{
if(m_hidden != hidden) {
this.m_visibilityUpdated = true;
} else if(releaseDate == null && m_releaseDate != null) {
this.m_visibilityUpdated = true;
} else if(releaseDate != null && m_releaseDate == null) {
this.m_visibilityUpdated = true;
} else if(m_releaseDate != null && releaseDate != null && m_releaseDate.compareTo(releaseDate) != 0) {
this.m_visibilityUpdated = true;
} else if(retractDate == null && m_retractDate != null) {
this.m_visibilityUpdated = true;
} else if(retractDate != null && m_retractDate == null) {
this.m_visibilityUpdated = true;
} else if(m_retractDate != null && retractDate != null && m_retractDate.compareTo(retractDate) != 0) {
this.m_visibilityUpdated = true;
}
m_hidden = hidden;
if(hidden)
{
this.m_releaseDate = null;
this.m_retractDate = null;
}
else
{
if(releaseDate == null)
{
this.m_releaseDate = null;
}
else
{
this.m_releaseDate = timeService.newTime(releaseDate.getTime());
}
if(retractDate == null)
{
this.m_retractDate = null;
}
else
{
this.m_retractDate = timeService.newTime(retractDate.getTime());
}
}
}
public void setHidden()
{
if(!m_hidden) {
this.m_visibilityUpdated = true;
}
m_hidden = true;
this.m_releaseDate = null;
this.m_retractDate = null;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.api.ContentEntity#getResourceType()
*/
public String getResourceType()
{
return m_resourceType;
}
public ContentCollection getContainingCollection()
{
ContentCollection container = null;
String containerId = isolateContainingId(this.getId());
try
{
container = findCollection(containerId);
}
catch (TypeException e)
{
}
return container;
}
public void setPriority()
{
ResourcePropertiesEdit props = getPropertiesEdit();
String sortBy = props.getProperty(ResourceProperties.PROP_CONTENT_PRIORITY);
if(sortBy == null)
{
// add a default value that sorts new items after existing items, with new folders before new resources
String containingCollectionId = isolateContainingId(this.m_id);
int count = 1;
if(containingCollectionId != null)
{
try
{
count = getCollectionSize(containingCollectionId) + 1;
}
catch (IdUnusedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (TypeException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (PermissionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(! m_id.endsWith(Entity.SEPARATOR))
{
count += ContentHostingService.CONTENT_RESOURCE_PRIORITY_OFFSET;
}
props.addProperty(ResourceProperties.PROP_CONTENT_PRIORITY, Integer.toString(count));
}
}
/* (non-Javadoc)
* @see org.sakaiproject.content.api.ContentResourceEdit#setResourceType(java.lang.String)
*/
public void setResourceType(String type)
{
m_resourceType = type;
}
public boolean isConditionallyReleased() {
try {
return this.m_properties.getBooleanProperty(ConditionService.PROP_CONDITIONAL_RELEASE);
} catch (EntityPropertyNotDefinedException e) {
return false;
} catch (EntityPropertyTypeException e) {
return false;
}
}
public void setConditionallyReleased(boolean isConditionallyReleased) {
try {
Boolean oldValue = this.m_properties.getBooleanProperty(ConditionService.PROP_CONDITIONAL_RELEASE);
if(oldValue.booleanValue() != isConditionallyReleased) {
this.m_visibilityUpdated = true;
}
} catch (EntityPropertyNotDefinedException e) {
// oldValue is false
if(isConditionallyReleased) {
this.m_visibilityUpdated = true;
}
} catch (EntityPropertyTypeException e) {
// assume oldValue is false
if(isConditionallyReleased) {
this.m_visibilityUpdated = true;
}
}
m_properties.addProperty(ConditionService.PROP_CONDITIONAL_RELEASE, Boolean.toString(isConditionallyReleased));
}
} // BasicGroupAwareEntity
/**********************************************************************************************************************************************************************************************************************************************************
* ContentCollection implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseCollectionEdit extends BasicGroupAwareEdit implements ContentCollectionEdit, SessionBindingListener, SerializableEntity, SerializableCollectionAccess
{
private boolean m_sessionBound = false;
/**
* Construct with an id.
*
* @param id
* The unique channel id.
*/
public BaseCollectionEdit(String id)
{
// set the id
m_id = id;
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_resourceType = ResourceType.TYPE_FOLDER;
} // BaseCollectionEdit
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("collection".equals(qName) && entity == null)
{
m_id = attributes.getValue("id");
m_resourceType = ResourceType.TYPE_FOLDER;
String refStr = getReference(m_id);
Reference ref = m_entityManager.newReference(refStr);
String context = ref.getContext();
Site site = null;
try
{
site = m_siteService.getSite(ref.getContext());
}
catch (IdUnusedException e)
{
}
// extract access
AccessMode access = AccessMode.INHERITED;
String access_mode = attributes.getValue(ACCESS_MODE);
if (access_mode != null && !access_mode.trim().equals(""))
{
access = AccessMode.fromString(access_mode);
}
m_access = access;
if (m_access == null || AccessMode.SITE == m_access)
{
m_access = AccessMode.INHERITED;
}
// extract release date
// m_releaseDate = timeService.newTime(0);
String date0 = attributes.getValue(RELEASE_DATE);
if (date0 != null && !date0.trim().equals(""))
{
m_releaseDate = timeService.newTimeGmt(date0);
if (m_releaseDate.getTime() <= START_OF_TIME)
{
m_releaseDate = null;
}
}
// extract retract date
// m_retractDate = timeService.newTimeGmt(9999,12,
// 31, 23, 59, 59, 999);
String date1 = attributes.getValue(RETRACT_DATE);
if (date1 != null && !date1.trim().equals(""))
{
m_retractDate = timeService.newTimeGmt(date1);
if (m_retractDate.getTime() >= END_OF_TIME)
{
m_retractDate = null;
}
}
String hidden = attributes.getValue(HIDDEN);
m_hidden = hidden != null && !hidden.trim().equals("")
&& !Boolean.FALSE.toString().equalsIgnoreCase(hidden);
entity = thisEntity;
}
else if (GROUP_LIST.equals(qName))
{
String groupRef = attributes.getValue(GROUP_NAME);
if (groupRef != null)
{
m_groups.add(groupRef);
}
}
else if ("rightsAssignment".equals(qName))
{
}
else
{
M_log.warn("Unexpected Element " + qName);
}
}
}
};
}
/**
* Construct as a copy of another.
*
* @param other
* The other to copy.
*/
public BaseCollectionEdit(ContentCollection other)
{
set(other);
m_resourceType = ResourceType.TYPE_FOLDER;
} // BaseCollectionEdit
/**
* Construct from info in XML in a DOM element.
*
* @param el
* The XML DOM element.
*/
public BaseCollectionEdit(Element el)
{
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_id = el.getAttribute("id");
m_resourceType = ResourceType.TYPE_FOLDER;
// String refStr = getReference(m_id);
// Reference ref = m_entityManager.newReference(refStr);
// String context = ref.getContext();
// Site site = null;
// try
// {
// site = m_siteService.getSite(ref.getContext());
// }
// catch (IdUnusedException e)
// {
//
// }
// the children (properties)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
if(m_prioritySortEnabled)
{
setPriority();
}
}
// look for groups
else if(element.getTagName().equals(GROUP_LIST))
{
String groupRef = element.getAttribute(GROUP_NAME);
if(groupRef != null)
{
m_groups.add(groupRef);
}
}
else if(element.getTagName().equals("rightsAssignment"))
{
}
}
// extract access
AccessMode access = AccessMode.INHERITED;
String access_mode = el.getAttribute(ACCESS_MODE);
if(access_mode != null && !access_mode.trim().equals(""))
{
access = AccessMode.fromString(access_mode);
}
m_access = access;
if(m_access == null || AccessMode.SITE == m_access)
{
m_access = AccessMode.INHERITED;
}
// extract release date
// m_releaseDate = timeService.newTime(0);
String date0 = el.getAttribute(RELEASE_DATE);
if(date0 != null && !date0.trim().equals(""))
{
m_releaseDate = timeService.newTimeGmt(date0);
if(m_releaseDate.getTime() <= START_OF_TIME)
{
m_releaseDate = null;
}
}
// extract retract date
// m_retractDate = timeService.newTimeGmt(9999,12, 31, 23, 59, 59, 999);
String date1 = el.getAttribute(RETRACT_DATE);
if(date1 != null && !date1.trim().equals(""))
{
m_retractDate = timeService.newTimeGmt(date1);
if(m_retractDate.getTime() >= END_OF_TIME)
{
m_retractDate = null;
}
}
String hidden = el.getAttribute(HIDDEN);
m_hidden = hidden != null && ! hidden.trim().equals("") && ! Boolean.FALSE.toString().equalsIgnoreCase(hidden);
} // BaseCollectionEdit
/**
*
*/
public BaseCollectionEdit()
{
m_properties = new BaseResourcePropertiesEdit();
}
/**
* Take all values from this object.
*
* @param user
* The other object to take values from.
*/
protected void set(ContentCollection other)
{
// set the id
m_id = other.getId();
// copy other's access mode and list of groups
m_access = other.getAccess();
m_groups.clear();
m_groups.addAll(other.getGroups());
chh = other.getContentHandler();
chh_vce = other.getVirtualContentEntity();
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
m_hidden = other.isHidden();
if(m_hidden || other.getReleaseDate() == null)
{
m_releaseDate = null;
}
else
{
m_releaseDate = timeService.newTime(other.getReleaseDate().getTime());
}
if(m_hidden || other.getRetractDate() == null)
{
m_retractDate = null;
}
else
{
m_retractDate = timeService.newTime(other.getRetractDate().getTime());
}
} // set
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelCollection(this);
}
} // finalize
/* (non-Javadoc)
* @see org.sakaiproject.content.api.ContentEntity#getUrl(boolean)
*/
public String getUrl(boolean relative)
{
return getAccessPoint(relative) + Web.escapeUrl(convertIdToUserEid(m_id));
}
/**
* Access the URL which can be used to access the resource.
*
* @return The URL which can be used to access the resource.
*/
public String getUrl()
{
return getUrl(false);
} // getUrl
/**
* Access the internal reference which can be used to access the resource from within the system.
*
* @return The the internal reference which can be used to access the resource from within the system.
*/
public String getReference()
{
return getAccessPoint(true) + m_id;
} // getReference
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getReference();
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl();
}
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
} // getId
/**
* Access a List of the collection's internal members, each a resource id string.
*
* @return a List of the collection's internal members, each a resource id string (may be empty).
*/
public List getMembers()
{
// get the objects
Collection<String> memberResourceIds = m_storage.getMemberResourceIds(this.m_id);
Collection<String> memberCollectionIds = m_storage.getMemberCollectionIds(this.m_id);
// form the list of just ids
List<String> mbrs = new ArrayList<String>();
if(memberResourceIds != null)
{
mbrs.addAll(memberResourceIds);
}
if(memberCollectionIds != null)
{
mbrs.addAll(memberCollectionIds);
}
//if (mbrs.size() == 0) return mbrs;
// sort? %%%
// Collections.sort(mbrs);
return mbrs;
} // getMembers
/**
* Access the size of all the resource body bytes within this collection in Kbytes.
*
* @return The size of all the resource body bytes within this collection in Kbytes.
*/
public long getBodySizeK()
{
long size = 0;
if(readyToUseFilesizeColumn())
{
String context = getContext();
if(context != null || m_id.startsWith(COLLECTION_DROPBOX))
{
size = getSizeForContext(context!=null?context:m_id)/1000L;
}
}
else
{
// get the member objects
List members = getMemberResources();
// for each member
for (Iterator it = members.iterator(); it.hasNext();)
{
Object obj = it.next();
if (obj == null) continue;
// do not count the size of virtual objects
if (obj instanceof BaseCollectionEdit && ((BaseCollectionEdit)obj).getVirtualContentEntity() != null) continue;
// if a resource, add the body size
if (obj instanceof ContentResource)
{
size += bytes2k(((ContentResource) obj).getContentLength());
}
// if a collection, count it's size
else
{
size += ((BaseCollectionEdit) obj).getBodySizeK();
}
}
}
// if (M_log.isDebugEnabled())
// M_log.debug("getBodySizeK(): collection: " + getId() + " size: " + size);
return size;
} // getBodySizeK
/**
* Access a List of the collections' internal members as full ContentResource or ContentCollection objects.
*
* @return a List of the full objects of the members of the collection.
*/
public List<ContentEntity> getMemberResources()
{
List<ContentEntity> mbrs = (List<ContentEntity>) threadLocalManager.get("members@" + this.m_id);
if(mbrs == null)
{
mbrs = new ArrayList();
// TODO: current service caching
mbrs.addAll(m_storage.getCollections(this));
mbrs.addAll(m_storage.getResources(this));
threadLocalManager.set("members@" + this.m_id, mbrs);
}
//if (mbrs.size() == 0) return mbrs;
// sort %%%
// Collections.sort(mbrs);
cacheEntities(mbrs);
return mbrs;
} // getMemberResources
protected List copyEntityList(List entities)
{
List list = new ArrayList();
for(ContentEntity entity : (List<ContentEntity>)entities)
{
ContentEntity copy = null;
if(entity instanceof ContentResource)
{
copy = new BaseResourceEdit((ContentResource) entity);
threadLocalManager.set("findResource@" + entity.getId(), entity); // new BaseResourceEdit((ContentResource) entity));
}
else if(entity instanceof ContentCollection)
{
copy = new BaseCollectionEdit((ContentCollection) entity);
threadLocalManager.set("findCollection@" + entity.getId(), entity); // new BaseCollectionEdit((ContentCollection) entity));
}
if(copy != null)
{
list.add(copy);
}
}
return list;
}
/**
* Access the collection's properties.
*
* @return The collection's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
} // getProperties
/**
* Set the collection as removed.
*/
protected void setRemoved()
{
m_isRemoved = true;
} // setRemoved
/**
* Clear all the members of the collection, all the way down. Security has already been checked!
*/
protected void clear() throws IdUnusedException, PermissionException, InconsistentException, TypeException, InUseException,
ServerOverloadException
{
// get this collection's members
List mbrs = getMemberResources();
for (int i = 0; i < mbrs.size(); i++)
{
Object mbr = mbrs.get(i);
if (mbr == null) continue;
// for a contained collection, clear its members first - if any are in use, the show's over
if (mbr instanceof ContentCollection)
{
((BaseCollectionEdit) mbr).clear();
}
// now remove this member
if (mbr instanceof ContentCollection)
{
// if this is not allowed or in use, we throw and the show's over.
removeCollection(((ContentCollection) mbr).getId());
}
else if (mbr instanceof ContentResource)
{
// if this is not allowed or in use, we throw and the show's over.
removeResource(((ContentResource) mbr).getId());
}
}
} // clear
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element collection = doc.createElement("collection");
if (stack.isEmpty())
{
doc.appendChild(collection);
}
else
{
((Element) stack.peek()).appendChild(collection);
}
stack.push(collection);
collection.setAttribute("id", m_id);
collection.setAttribute("resource-type", ResourceType.TYPE_FOLDER);
if(m_access == null || AccessMode.SITE == m_access)
{
m_access = AccessMode.INHERITED;
}
collection.setAttribute(ACCESS_MODE, m_access.toString());
collection.setAttribute(HIDDEN, Boolean.toString(m_hidden));
if(!m_hidden && m_releaseDate != null)
{
// add release-date
collection.setAttribute(RELEASE_DATE, m_releaseDate.toString());
}
if(!m_hidden && m_retractDate != null)
{
// add retract-date
collection.setAttribute(RETRACT_DATE, m_retractDate.toString());
}
// properties
m_properties.toXml(doc, stack);
stack.pop();
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
Iterator groupIt = m_groups.iterator();
while( groupIt.hasNext())
{
// how does this get to be a Group instead of a groupRef???
String groupRef = (String) groupIt.next();
Element sect = doc.createElement(GROUP_LIST);
sect.setAttribute(GROUP_NAME, groupRef);
collection.appendChild(sect);
}
}
return collection;
} // toXml
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
m_sessionBound = true;
}
public void valueUnbound(SessionBindingEvent event)
{
m_sessionBound = false;
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelCollection(this);
}
} // valueUnbound
/**
* @inheritDoc
* @see org.sakaiproject.content.api.ContentEntity#isResource()
*/
public boolean isResource()
{
// TODO: this may need a different implementation in the handler
return false;
}
/**
* @inheritDoc
* @see org.sakaiproject.content.api.ContentEntity#isCollection()
*/
public boolean isCollection()
{
// TODO: this may need a different implementation in the handler
return true;
}
public void setPriorityMap(Map<String, Integer> priorities)
{
if(m_prioritySortEnabled)
{
ResourcePropertiesEdit myProps = getPropertiesEdit();
myProps.addProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT, Boolean.TRUE.toString());
Iterator nameIt = priorities.entrySet().iterator();
while(nameIt.hasNext())
{
Entry entry = (Entry) nameIt.next();
String name = (String) entry.getKey();
Integer priority = (Integer) entry.getValue();
try
{
if(name.endsWith(Entity.SEPARATOR))
{
ContentCollectionEdit entity = editCollection(name);
ResourcePropertiesEdit props = entity.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_CONTENT_PRIORITY, priority.toString());
//commitCollection(entity);
// complete the edit
m_storage.commitCollection(entity);
// close the edit object
((BaseCollectionEdit) entity).closeEdit();
// the collection has changed so we must remove the old version from thread-local cache
threadLocalManager.set("findCollection@" + entity.getId(), null);
}
else
{
ContentResourceEdit entity = editResource(name);
ResourcePropertiesEdit props = entity.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_CONTENT_PRIORITY, priority.toString());
// complete the edit
m_storage.commitResource(entity);
// close the edit object
((BaseResourceEdit) entity).closeEdit();
// must remove old version of this edit from thread-local cache
// so we get new version if we try to retrieve it in same thread
threadLocalManager.set("findResource@" + entity.getId(), null);
// close the edit object
((BaseResourceEdit) entity).closeEdit();
}
}
catch(TypeException e)
{
// TODO Auto-generated catch block
M_log.error("TypeException",e);
}
catch (IdUnusedException e)
{
// TODO Auto-generated catch block
M_log.error("IdUnusedException",e);
}
catch (PermissionException e)
{
// TODO Auto-generated catch block
M_log.error("PermissionException",e);
}
catch (InUseException e)
{
// TODO Auto-generated catch block
M_log.error("InUseException",e);
}
catch (ServerOverloadException e)
{
// TODO Auto-generated catch block
M_log.error("ServerOverloadException",e);
}
}
}
}
public int getMemberCount()
{
int count = 0;
Integer countObj = (Integer) threadLocalManager.get("getMemberCount@" + this.m_id);
if(countObj == null)
{
count = m_storage.getMemberCount(this.m_id);
threadLocalManager.set("getMemberCount@" + this.m_id, Integer.valueOf(count));
}
else
{
count = countObj.intValue();
}
return count;
}
/*************************************************************************************************************************************************************
* ContentHostingHandler Support
*/
/**
* Real storage does not have handlers
*/
private ContentHostingHandler chh = null;
private ContentEntity chh_vce = null; // the wrapped virtual content entity
public ContentHostingHandler getContentHandler() {return chh;}
public void setContentHandler(ContentHostingHandler chh) {this.chh = chh;}
public ContentEntity getVirtualContentEntity() {return chh_vce;}
public void setVirtualContentEntity(ContentEntity ce) {this.chh_vce = ce;}
public ContentEntity getMember(String nextId)
{
ContentEntity ce = m_storage.getCollection(nextId);
if ( ce == null ) {
try
{
ce = m_storage.getResource(nextId);
}
catch (TypeException e)
{
M_log.error("Type Exception ",e);
}
}
return ce;
/*
List l = getMemberResources();
for ( Iterator li = l.iterator(); li.hasNext(); ) {
ContentEntity ce = (ContentEntity) li.next();
if ( nextId.equals(ce.getId())) {
return ce;
}
}
return null;
*/
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableAccess()
*/
public AccessMode getSerializableAccess()
{
return m_access;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableGroup()
*/
public Collection<String> getSerializableGroup()
{
return m_groups;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableHidden()
*/
public boolean getSerializableHidden()
{
return m_hidden;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableId()
*/
public String getSerializableId()
{
return m_id;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableProperties()
*/
public SerializableEntity getSerializableProperties()
{
return (SerializableEntity)m_properties;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableReleaseDate()
*/
public Time getSerializableReleaseDate()
{
return m_releaseDate;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#getSerializableRetractDate()
*/
public Time getSerializableRetractDate()
{
return m_retractDate;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableAccess(org.sakaiproject.content.api.GroupAwareEntity.AccessMode)
*/
public void setSerializableAccess(AccessMode access)
{
m_access = access;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableGroups(java.util.List)
*/
public void setSerializableGroups(Collection<String> groups)
{
m_groups = groups;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableHidden(boolean)
*/
public void setSerializableHidden(boolean hidden)
{
m_hidden = hidden;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableId(java.lang.String)
*/
public void setSerializableId(String id)
{
m_id = id;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableReleaseDate(org.sakaiproject.time.api.Time)
*/
public void setSerializableReleaseDate(Time releaseDate)
{
m_releaseDate = releaseDate;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableResourceType(java.lang.String)
*/
public void setSerializableResourceType(String resourceType)
{
m_resourceType = resourceType;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableCollectionAccess#setSerializableRetractDate(org.sakaiproject.time.api.Time)
*/
public void setSerializableRetractDate(Time retractDate)
{
m_retractDate = retractDate;
}
public void unbind() {
if ( !m_sessionBound && m_active ) {
//M_log.warn("Edit Object not closed correctly, Cancelling "+this.getId());
cancelCollection(this);
}
}
} // class BaseCollectionEdit
/**********************************************************************************************************************************************************************************************************************************************************
* ContentResource implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseResourceEdit extends BasicGroupAwareEdit implements ContentResourceEdit, SessionBindingListener, SerializableEntity, SerializableResourceAccess
{
/** The content type. */
protected String m_contentType = null;
/** The body. May be missing - not yet read (null) */
protected byte[] m_body = null;
/** The content length of the body, consult only if the body is missing (null) */
protected long m_contentLength = 0;
/** When true, someone changed the body content with setContent() */
protected boolean m_bodyUpdated = false;
/** The file system path, post root, for file system stored body binary. */
protected String m_filePath = null;
protected InputStream m_contentStream;
private boolean m_sessionBound = true;
protected String m_oldDisplayName = null;
/**
* Indicates this resource is a reference copy of an existing resource,
* this id will be the resource it is a copy of
*/
protected String referenceCopy = null;
/**
* Indicates this resource is a reference copy of an existing resource,
* this id will be the resource it is a copy of
* WARNING: this will null out the content values (stream and body)
*
* @param referenceCopy the id of the resource this is a copy of
*/
public void setReferenceCopy(String referenceCopy) {
this.referenceCopy = referenceCopy;
this.m_contentStream = null;
this.m_body = null;
}
/**
* Construct.
*
* @param id
* The local resource id.
*/
public BaseResourceEdit(String id)
{
m_id = id;
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
// allocate a file path if needed
if (m_bodyPath != null)
{
setFilePath(timeService.newTime());
}
} // BaseResourceEdit
/**
* Construct as a copy of another
*
* @param other
* The other to copy.
*/
public BaseResourceEdit(ContentResource other)
{
set(other);
} // BaseResourceEdit
public BaseResourceEdit(ContentResource other, boolean reference) {
set(other, reference);
} // BaseResourceEdit
/**
* Set the file path for this resource
*
* @param time
* The time on which to based the path.
*/
protected void setFilePath(Time time)
{
// compute file path: use now in ms mod m_bodyVolumes.length to pick a volume from m_bodyVolumes (if defined)
// add /yyyy/DDD/HH year / day of year / hour / and a unique id for the final file name.
// Don't include the body path.
String volume = "/";
if ((m_bodyVolumes != null) && (m_bodyVolumes.length > 0))
{
volume += m_bodyVolumes[(int) (Math.abs(time.getTime()) % ((long) m_bodyVolumes.length))];
volume += "/";
}
m_filePath = volume + time.toStringFilePath() + idManager.createUuid();
}
/**
* Take all values from this object
*
* @param other
* The other object to take values from.
*/
protected void set(ContentResource other) {
set(other, false);
}
/**
* Set the values in this edit to equal the values in the passing object
*
* @param other the object to take values from.
* @param reference if true then make a reference copy (i.e. do not duplicate the actual
*/
protected void set(ContentResource other, boolean reference) {
m_id = other.getId();
m_contentType = other.getContentType();
m_contentLength = other.getContentLength();
m_resourceType = other.getResourceType();
chh = other.getContentHandler();
chh_vce = other.getVirtualContentEntity();
if (reference && other.getId() != null) {
// populate the reference copy key, skip populating the actual content
this.referenceCopy = other.getId();
this.m_contentStream = null;
this.m_body = null;
} else {
// copy the actual content
this.referenceCopy = null;
this.m_contentStream = ((BaseResourceEdit) other).m_contentStream;
// if there's a body in the other, reference it, else leave this one null
// Note: this treats the body byte array as immutable, so to update it one
// *must* call setContent() not just getContent and mess with the bytes. -ggolden
byte[] content = ((BaseResourceEdit) other).m_body;
if (content != null)
{
m_contentLength = content.length;
m_body = content;
}
}
m_filePath = ((BaseResourceEdit) other).m_filePath;
// copy other's access mode and list of groups
m_access = other.getAccess();
m_groups.clear();
m_groups.addAll(other.getGroups());
// setup for properties
m_properties = new BaseResourcePropertiesEdit();
m_properties.addAll(other.getProperties());
m_hidden = other.isHidden();
if(m_hidden || other.getReleaseDate() == null)
{
m_releaseDate = null;
}
else
{
m_releaseDate = timeService.newTime(other.getReleaseDate().getTime());
}
if(m_hidden || other.getRetractDate() == null)
{
m_retractDate = null;
}
else
{
m_retractDate = timeService.newTime(other.getRetractDate().getTime());
}
} // set
/**
*
*/
public BaseResourceEdit()
{
// we ignore the container
m_properties = new BaseResourcePropertiesEdit();
}
/**
* Construct from information in XML in a DOM element. Limited to body size of <= 2G.
*
* @param el
* The XML DOM element.
*/
public BaseResourceEdit(Element el)
{
m_properties = new BaseResourcePropertiesEdit();
m_id = el.getAttribute("id");
String contentType = StringUtils.trimToNull(el.getAttribute("content-type"));
setContentType(contentType);
m_contentLength = 0;
try
{
m_contentLength = Long.parseLong(el.getAttribute("content-length"));
}
catch (Exception ignore)
{
}
ResourceTypeRegistry registry = getResourceTypeRegistry();
String typeId = StringUtils.trimToNull(el.getAttribute("resource-type"));
if(typeId == null || registry.getType(typeId) == null)
{
typeId = registry.mimetype2resourcetype(contentType);
}
setResourceType(typeId);
if (m_contentLength <= Integer.MAX_VALUE)
{
String enc = StringUtils.trimToNull(el.getAttribute("body"));
if (enc != null)
{
byte[] decoded = null;
try
{
decoded = Base64.decodeBase64(enc.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e)
{
M_log.error(e);
}
m_body = new byte[(int) m_contentLength];
System.arraycopy(decoded, 0, m_body, 0, (int) m_contentLength);
}
}
m_filePath = StringUtils.trimToNull(el.getAttribute("filePath"));
// the children (properties)
NodeList children = el.getChildNodes();
final int length = children.getLength();
for (int i = 0; i < length; i++)
{
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) child;
// look for properties
if (element.getTagName().equals("properties"))
{
// re-create properties
m_properties = new BaseResourcePropertiesEdit(element);
if(m_prioritySortEnabled)
{
setPriority();
}
}
// look for groups
else if(element.getTagName().equals(GROUP_LIST))
{
m_groups.add(element.getAttribute(GROUP_NAME));
}
// extract access
AccessMode access = AccessMode.INHERITED;
String access_mode = el.getAttribute(ACCESS_MODE);
if(access_mode != null && !access_mode.trim().equals(""))
{
access = AccessMode.fromString(access_mode);
}
m_access = access;
if(m_access == null || AccessMode.SITE == m_access)
{
m_access = AccessMode.INHERITED;
}
String hidden = el.getAttribute(HIDDEN);
m_hidden = hidden != null && ! hidden.trim().equals("") && ! Boolean.FALSE.toString().equalsIgnoreCase(hidden);
if(m_hidden)
{
m_releaseDate = null;
m_retractDate = null;
}
else
{
// extract release date
String date0 = el.getAttribute(RELEASE_DATE);
if(date0 != null && !date0.trim().equals(""))
{
m_releaseDate = timeService.newTimeGmt(date0);
if(m_releaseDate.getTime() <= START_OF_TIME)
{
m_releaseDate = null;
}
}
// extract retract date
String date1 = el.getAttribute(RETRACT_DATE);
if(date1 != null && !date1.trim().equals(""))
{
m_retractDate = timeService.newTimeGmt(date1);
if(m_retractDate.getTime() >= END_OF_TIME)
{
m_retractDate = null;
}
}
}
}
} // BaseResourceEdit
/**
* @param services
* @return
*/
public ContentHandler getContentHandler(Map<String, Object> services)
{
final Entity thisEntity = this;
return new DefaultEntityHandler()
{
/*
* (non-Javadoc)
*
* @see org.sakaiproject.util.DefaultEntityHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String,
* org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (doStartElement(uri, localName, qName, attributes))
{
if ("resource".equals(qName) && entity == null)
{
m_id = attributes.getValue("id");
String contentType = StringUtils.trimToNull(attributes
.getValue("content-type"));
setContentType(contentType);
m_contentLength = 0;
try
{
m_contentLength = Long.parseLong(attributes
.getValue("content-length"));
}
catch (Exception ignore)
{
}
ResourceTypeRegistry registry = getResourceTypeRegistry();
String typeId = StringUtils.trimToNull(attributes
.getValue("resource-type"));
if (typeId == null || registry.getType(typeId) == null)
{
typeId = registry.mimetype2resourcetype(contentType);
}
setResourceType(typeId);
if (m_contentLength <= Integer.MAX_VALUE)
{
String enc = StringUtils.trimToNull(attributes
.getValue("body"));
if (enc != null)
{
byte[] decoded = null;
try
{
decoded = Base64.decodeBase64(enc.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e)
{
M_log.error(e);
}
m_body = new byte[(int) m_contentLength];
System.arraycopy(decoded, 0, m_body, 0, (int) m_contentLength);
}
}
m_filePath = StringUtils.trimToNull(attributes
.getValue("filePath"));
AccessMode access = AccessMode.INHERITED;
String access_mode = attributes.getValue(ACCESS_MODE);
if (access_mode != null && !access_mode.trim().equals(""))
{
access = AccessMode.fromString(access_mode);
}
m_access = access;
if (m_access == null || AccessMode.SITE == m_access)
{
m_access = AccessMode.INHERITED;
}
String hidden = attributes.getValue(HIDDEN);
m_hidden = hidden != null && !hidden.trim().equals("")
&& !Boolean.FALSE.toString().equalsIgnoreCase(hidden);
if (m_hidden)
{
m_releaseDate = null;
m_retractDate = null;
}
else
{
// extract release date
String date0 = attributes.getValue(RELEASE_DATE);
if (date0 != null && !date0.trim().equals(""))
{
m_releaseDate = timeService.newTimeGmt(date0);
if (m_releaseDate.getTime() <= START_OF_TIME)
{
m_releaseDate = null;
}
}
// extract retract date
String date1 = attributes.getValue(RETRACT_DATE);
if (date1 != null && !date1.trim().equals(""))
{
m_retractDate = timeService.newTimeGmt(date1);
if (m_retractDate.getTime() >= END_OF_TIME)
{
m_retractDate = null;
}
}
}
entity = thisEntity;
}
else if (GROUP_LIST.equals(qName))
{
m_groups.add(attributes.getValue(GROUP_NAME));
}
else
{
M_log.warn("Unexpected Element " + qName);
}
}
}
};
}
/**
* Clean up.
*/
protected void finalize()
{
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelResource(this);
}
} // finalize
/**
* @inheritDoc
*/
public String getUrl()
{
return getUrl(false, PROP_ALTERNATE_REFERENCE);
}
/**
* @inheritDoc
*/
public String getReference()
{
return getReference(PROP_ALTERNATE_REFERENCE);
}
/* (non-Javadoc)
* @see org.sakaiproject.content.api.ContentEntity#getUrl(boolean)
*/
public String getUrl(boolean relative)
{
return getUrl(relative, PROP_ALTERNATE_REFERENCE);
}
/**
* @inheritDoc
*/
public String getUrl(boolean relative, String rootProperty)
{
return (relative ? m_serverConfigurationService.getAccessPath() : m_serverConfigurationService.getAccessUrl())
+ Web.escapeUrl(getAlternateReferenceRoot(rootProperty) + m_relativeAccessPoint
+ convertIdToUserEid(m_id));
}
/**
* @inheritDoc
*/
public String getUrl(String rootProperty)
{
return getUrl(false, rootProperty);
}
/**
* @inheritDoc
*/
public String getReference(String rootProperty)
{
return getAlternateReferenceRoot(rootProperty) + m_relativeAccessPoint + m_id;
}
/**
* Compute an alternate root for a reference, based on the value of the specified property.
*
* @param rootProperty
* The property name.
* @return The alternate root, or "" if there is none.
*/
protected String getAlternateReferenceRoot(String rootProperty)
{
// null means don't do this
if (rootProperty == null) return "";
// find the property - "" if not found
String alternateRoot = StringUtils.trimToNull(getProperties().getProperty(PROP_ALTERNATE_REFERENCE));
if (alternateRoot == null) return "";
// make sure it start with a separator and does not end with one
if (!alternateRoot.startsWith(SEPARATOR)) alternateRoot = SEPARATOR + alternateRoot;
if (alternateRoot.endsWith(SEPARATOR))
alternateRoot = alternateRoot.substring(0, alternateRoot.length() - SEPARATOR.length());
return alternateRoot;
}
/**
* @inheritDoc
*/
protected boolean requiresCopyrightAgreement()
{
// check my properties
return m_properties.getProperty(ResourceProperties.PROP_COPYRIGHT_ALERT) != null;
}
/**
* Access the id of the resource.
*
* @return The id.
*/
public String getId()
{
return m_id;
} // getId
/**
* Access the content byte length.
*
* @return The content byte length.
*/
public long getContentLength()
{
// Use the CHH delegate, if there is one.
if (chh_vce != null) return ((ContentResource)chh_vce).getContentLength();
// if we have a body, use it's length
if (m_body != null) return m_body.length;
// otherwise, use the content length
return m_contentLength;
} // getContentLength
/**
* Access the resource MIME type.
*
* @return The resource MIME type.
*/
public String getContentType()
{
// Use the CHH delegate, if there is one.
if (chh_vce != null && chh_vce instanceof ContentResource) return ((ContentResource)chh_vce).getContentType();
return ((m_contentType == null) ? "" : m_contentType);
} // getContentType
/**
* Access the content bytes of the resource. As this reads the entire content into memory, only use this method
* when the resource is known to be relatively small. For larger files and all files that exceed 2G in size, use
* streamContent() instead.
*
* @return An array containing the bytes of the resource's content.
* @exception ServerOverloadException
* if server is configured to store resource body in filesystem and error occurs trying to read from filesystem,
* or the file is too large to read into a byte array (exceeds 2G in size).
*/
public byte[] getContent() throws ServerOverloadException
{
// Use the CHH delegate, if there is one.
if (chh_vce != null) return ((ContentResource)chh_vce).getContent();
// return the body bytes
byte[] rv = m_body;
if (rv == null)
{
// todo: try to get the body from the stream
if (m_contentLength == 0)
{
rv = new byte[0];
}
else if (m_contentLength > 0)
{
// TODO: we do not store the body with the object, so as not to cache the body bytes -ggolden
rv = m_storage.getResourceBody(this);
// m_body = rv;
}
}
return rv;
} // getContent
/**
* Access the content as a stream. Please close the stream when done as it may be holding valuable system resources.
*
* @return an InputStream through which the bytes of the resource can be read.
*/
public InputStream streamContent() throws ServerOverloadException
{
InputStream rv = null;
if (m_body != null)
{
rv = new ByteArrayInputStream(m_body);
}
else if (m_contentStream != null)
{
return m_contentStream;
}
else
{
rv = m_storage.streamResourceBody(this);
}
return rv;
}
/**
* Access the resource's properties.
*
* @return The resource's properties.
*/
public ResourceProperties getProperties()
{
return m_properties;
} // getProperties
/**
* Set the resource as removed.
*/
protected void setRemoved()
{
m_isRemoved = true;
} // setRemoved
/**
* Set the content byte length.
*
* @param length
* The content byte length.
*/
public void setContentLength(long length)
{
m_contentLength = length;
} // setContentLength
/**
* Set the resource MIME type.
*
* @param type
* The resource MIME type.
*/
public void setContentType(String type)
{
type = (String) fixTypeAndId(getId(), type).get("type");
m_contentType = type;
} // setContentType
/**
* Set the resource content.
*
* @param content
* An array containing the bytes of the resource's content.
*/
public void setContent(byte[] content)
{
if (content == null)
{
M_log.warn("setContent(): null content");
return;
}
// only if different
if (StringUtil.different(content, m_body))
{
// take the new body and length
m_body = content;
m_contentLength = m_body.length;
// mark me as having a changed body
m_bodyUpdated = true;
}
} // setContent
/* (non-Javadoc)
* @see org.sakaiproject.content.api.ContentResourceEdit#setContent(java.io.OutputStream)
*/
public void setContent(InputStream stream)
{
if (stream == null)
{
M_log.warn("setContent(): null stream");
return;
}
m_contentStream = stream;
// m_contentLength =
}
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element resource = doc.createElement("resource");
if (stack.isEmpty())
{
doc.appendChild(resource);
}
else
{
((Element) stack.peek()).appendChild(resource);
}
stack.push(resource);
resource.setAttribute("id", m_id);
resource.setAttribute("content-type", m_contentType);
resource.setAttribute("resource-type", m_resourceType);
// body may not be loaded; if not use m_contentLength
long contentLength = m_contentLength;
if (m_body != null) contentLength = m_body.length;
resource.setAttribute("content-length", Long.toString(contentLength));
if (m_filePath != null) resource.setAttribute("filePath", m_filePath);
// if there's no body bytes (len = 0?) m_body will still be null, so just skip it
if (m_body != null)
{
String enc = null;
try
{
enc = new String(Base64.encodeBase64(m_body),"UTF-8");
}
catch (UnsupportedEncodingException e)
{
M_log.error(e);
}
resource.setAttribute("body", enc);
}
// add access
if(m_access == null || AccessMode.SITE == m_access)
{
m_access = AccessMode.INHERITED;
}
resource.setAttribute(ACCESS_MODE, m_access.toString());
resource.setAttribute(HIDDEN, Boolean.toString(m_hidden));
if(!m_hidden && m_releaseDate != null)
{
// add release-date
resource.setAttribute(RELEASE_DATE, m_releaseDate.toString());
}
if(!m_hidden && m_retractDate != null)
{
// add retract-date
resource.setAttribute(RETRACT_DATE, m_retractDate.toString());
}
// properties
m_properties.toXml(doc, stack);
stack.pop();
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
Iterator groupIt = m_groups.iterator();
while( groupIt.hasNext())
{
String groupRef = (String) groupIt.next();
Element sect = doc.createElement(GROUP_LIST);
sect.setAttribute(GROUP_NAME, groupRef);
resource.appendChild(sect);
}
}
return resource;
} // toXml
/**
* Access the event code for this edit.
*
* @return The event code for this edit.
*/
protected String getEvent()
{
return m_event;
}
/**
* Set the event code for this edit.
*
* @param event
* The event code for this edit.
*/
protected void setEvent(String event)
{
m_event = event;
}
/**
* Access the resource's properties for modification
*
* @return The resource's properties.
*/
public ResourcePropertiesEdit getPropertiesEdit()
{
return m_properties;
} // getPropertiesEdit
/**
* Enable editing.
*/
protected void activate()
{
m_active = true;
} // activate
/**
* Check to see if the edit is still active, or has already been closed.
*
* @return true if the edit is active, false if it's been closed.
*/
public boolean isActiveEdit()
{
return m_active;
} // isActiveEdit
/**
* Close the edit object - it cannot be used after this.
*/
protected void closeEdit()
{
m_active = false;
} // closeEdit
/******************************************************************************************************************************************************************************************************************************************************
* SessionBindingListener implementation
*****************************************************************************************************************************************************************************************************************************************************/
public void valueBound(SessionBindingEvent event)
{
m_sessionBound = true;
}
public void valueUnbound(SessionBindingEvent event)
{
m_sessionBound = false;
if (M_log.isDebugEnabled()) M_log.debug("valueUnbound()");
// catch the case where an edit was made but never resolved
if (m_active)
{
cancelResource(this);
}
} // valueUnbound
public boolean isResource()
{
// TODO: this may need a different implementation in the handler
return true;
}
public boolean isCollection()
{
// TODO: this may need a different implementation in the handler
return false;
}
/**
* real content resources dont have handlers
*/
private ContentHostingHandler chh = null;
private ContentEntity chh_vce = null; // the wrapped virtual content entity
public ContentHostingHandler getContentHandler() {return chh;}
public void setContentHandler(ContentHostingHandler chh) {this.chh = chh;}
public ContentEntity getVirtualContentEntity() {return chh_vce;}
public void setVirtualContentEntity(ContentEntity ce) {this.chh_vce = ce;}
/**
* ContentResources cant have members, so this always returns null
*/
public ContentEntity getMember(String nextId)
{
return null;
}
/** Serializable Resource Access */
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getResourceTypeRegistry()
*/
public ResourceTypeRegistry getResourceTypeRegistry()
{
return m_resourceTypeRegistry;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableAccess()
*/
public AccessMode getSerializableAccess()
{
return m_access;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableBody()
*/
public byte[] getSerializableBody()
{
if ( m_body != null ) {
M_log.warn("Serializing Body to Entiry Blob, this is bad and will make Sakai crawl");
}
return m_body;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableContentLength()
*/
public long getSerializableContentLength()
{
return m_contentLength;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableContentType()
*/
public String getSerializableContentType()
{
return m_contentType;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableFilePath()
*/
public String getSerializableFilePath()
{
return m_filePath;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableGroup()
*/
public Collection<String> getSerializableGroup()
{
return m_groups;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableHidden()
*/
public boolean getSerializableHidden()
{
return m_hidden;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableId()
*/
public String getSerializableId()
{
return m_id;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableProperties()
*/
public SerializableEntity getSerializableProperties()
{
return (SerializableEntity)m_properties;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableReleaseDate()
*/
public Time getSerializableReleaseDate()
{
return m_releaseDate;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableResourceType()
*/
public String getSerializableResourceType()
{
return m_resourceType;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#getSerializableRetractDate()
*/
public Time getSerializableRetractDate()
{
return m_retractDate;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableAccess(org.sakaiproject.content.api.GroupAwareEntity.AccessMode)
*/
public void setSerializableAccess(AccessMode access)
{
m_access = access;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableBody(byte[])
*/
public void setSerializableBody(byte[] body)
{
if ( body != null ) {
M_log.warn("Body serialization from Entity, this is bad and will slow Sakai right down ");
}
m_body = body;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableContentLength(long)
*/
public void setSerializableContentLength(long contentLength)
{
if (m_bodyPath == null && contentLength > Integer.MAX_VALUE ) {
M_log.warn("File is longer than "+Integer.MAX_VALUE+", may be truncated if not stored in filesystem ");
}
m_contentLength = contentLength;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableContentType(java.lang.String)
*/
public void setSerializableContentType(String contentType)
{
m_contentType = contentType;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableFilePath(java.lang.String)
*/
public void setSerializableFilePath(String filePath)
{
m_filePath = filePath;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableGroups(java.util.Collection)
*/
public void setSerializableGroups(Collection<String> groups)
{
m_groups = groups;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableHidden(boolean)
*/
public void setSerializableHidden(boolean hidden)
{
m_hidden = hidden;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableId(java.lang.String)
*/
public void setSerializableId(String id)
{
m_id = id;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableReleaseDate(org.sakaiproject.time.api.Time)
*/
public void setSerializableReleaseDate(Time releaseDate)
{
m_releaseDate = releaseDate;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableResourceType(java.lang.String)
*/
public void setSerializableResourceType(String resourceType)
{
m_resourceType = resourceType;
}
/* (non-Javadoc)
* @see org.sakaiproject.content.impl.serialize.api.SerializableResourceAccess#setSerializableRetractDate(org.sakaiproject.time.api.Time)
*/
public void setSerializableRetractDate(Time retractDate)
{
m_retractDate = retractDate;
}
public void unbind() {
if ( !m_sessionBound && m_active ) {
//M_log.warn("Edit Object not closed correctly, Cancelling "+this.getId());
cancelResource(this);
}
}
/**
* @return the oldDisplayName
*/
public String getOldDisplayName() {
return m_oldDisplayName;
}
/**
* @param oldDisplayName the oldDisplayName to set
*/
public void setOldDisplayName(String oldDisplayName) {
this.m_oldDisplayName = oldDisplayName;
}
} // BaseResourceEdit
/**********************************************************************************************************************************************************************************************************************************************************
* Storage implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected interface Storage
{
/**
* Open and be ready to read / write.
*/
public void open();
/**
* Get a count of all members of a collection, where 'member' means the collection
* is the immediate parent of the item. The count is not recursive and it will
* include all resources and collections whose immediate parent is the collection
* identified by the parameter.
*/
public int getMemberCount(String collectionId);
/**
* Access a collection of string identifiers for all ContentResource entities
* that are members of the ContentCollection identified by the parameter.
* @param collectionId
* @return
*/
public Collection<String> getMemberResourceIds(String collectionId);
/**
* Access a collection of string identifiers for all ContentCollection entities
* that are members of the ContentCollection identified by the parameter.
* @param collectionId
* @return
*/
public Collection<String> getMemberCollectionIds(String collectionId);
/**
* Close.
*/
public void close();
/**
* Return the identified collection, or null if not found.
*/
public ContentCollection getCollection(String id);
/**
* Return true if the identified collection exists.
*/
public boolean checkCollection(String id);
/**
* Get a list of all getCollections within a collection.
*/
public List<ContentCollectionEdit> getCollections(ContentCollection collection);
/**
* Keep a new collection.
*/
public ContentCollectionEdit putCollection(String collectionId);
/**
* Get a collection locked for update
*/
public ContentCollectionEdit editCollection(String collectionId);
/**
* Commit a collection edit.
*/
public void commitCollection(ContentCollectionEdit edit);
/**
* Cancel a collection edit.
*/
public void cancelCollection(ContentCollectionEdit edit);
/**
* Forget about a collection.
*/
public void removeCollection(ContentCollectionEdit collection);
/**
* Return the identified resource, or null if not found.
* @throws TypeException
*/
public ContentResource getResource(String id) throws TypeException;
/**
* Return true if the identified resource exists.
*/
public boolean checkResource(String id);
/**
* Get a list of all resources within a collection.
*/
public List<ContentResourceEdit> getResources(ContentCollection collection);
/**
*
* @param collectionId
* @return
*/
public List getFlatResources(String collectionId);
/**
* Keep a new resource.
*/
public ContentResourceEdit putResource(String resourceId);
/**
* Get a resource locked for update
*/
public ContentResourceEdit editResource(String resourceId);
/**
* Commit a resource edit.
*/
public void commitResource(ContentResourceEdit edit) throws ServerOverloadException;
/**
* Cancel a resource edit.
*/
public void cancelResource(ContentResourceEdit edit);
/**
* Forget about a resource (and associated content).
*
* @param resource the resource to remove
*/
public void removeResource(ContentResourceEdit resource);
/**
* Forget about a resource with the option to leave the content in place
*
* @param resource the resource to remove
* @param removeContent if true, then also remove the content
*/
public void removeResource(ContentResourceEdit resource, boolean removeContent);
/**
* Read the resource's body.
*
* @exception ServerOverloadException
* if server is configured to save resource body in filesystem and an error occurs while trying to access the filesystem.
*/
public byte[] getResourceBody(ContentResource resource) throws ServerOverloadException;
/*
* Stream the resource's body for deleted resource.
*
* @exception ServerOverloadException
* if server is configured to save resource body in filesystem and an error occurs while trying to access the filesystem.
*/
public InputStream streamDeletedResourceBody(ContentResource resource) throws ServerOverloadException;
/**
* Stream the resource's body.
*
* @exception ServerOverloadException
* if server is configured to save resource body in filesystem and an error occurs while trying to access the filesystem.
*/
public InputStream streamResourceBody(ContentResource resource) throws ServerOverloadException;
/**
* Return a single character representing the access mode of the resource or collection identified by the parameter, or null if not found.
* @param id
* @return A character identifying the access mode for the content entity, one of 's' for site, 'p' for public or 'g' for group.
* @throws ServerOverloadException
*/
//public char getAccessMode(String id);
// htripath-storing into shadow table before deleting the resource
public void commitDeletedResource(ContentResourceEdit edit, String uuid) throws ServerOverloadException;
public ContentResourceEdit putDeleteResource(String resourceId, String uuid, String userId);
public List getDeletedResources(ContentCollection collection);
public ContentResourceEdit editDeletedResource(String resourceId);
public void removeDeletedResource(ContentResourceEdit edit);
public void cancelDeletedResource(ContentResourceEdit edit);
/**
* Retrieve a collection of ContentResource objects pf a particular resource-type. The collection will
* contain no more than the number of items specified as the pageSize, where pageSize is a non-negative
* number less than or equal to 1028. The resources will be selected in ascending order by resource-id.
* If the resources of the specified resource-type in the ContentHostingService in ascending order by
* resource-id are indexed from 0 to M and this method is called with parameters of N for pageSize and
* I for page, the resources returned will be those with indexes (I*N) through ((I+1)*N - 1). For example,
* if pageSize is 1028 and page is 0, the resources would be those with indexes of 0 to 1027.
*
* @param resourceType select resources where CONTENT_RESOURCE.RESOURCE_TYPE_ID equals resourceType
* @param pageSize (page) size of results
* @param page (page) increment of results
* @return collection of ContentResource
*/
public Collection<ContentResource> getResourcesOfType(String resourceType, int pageSize, int page);
/**
* Retrieve a collection of ContentResource objects of a particular resource-type in a set of contexts.
*
* @param resourceType select resources where CONTENT_RESOURCE.RESOURCE_TYPE_ID equals resourceType
* @param contextIds select resources where CONTENT_RESOURCE.CONTEXT in [context,...]
* @return collection of ContentResource
*/
public Collection<ContentResource> getContextResourcesOfType(String resourceType, Set<String> contextIds);
} // Storage
/**********************************************************************************************************************************************************************************************************************************************************
* CacheRefresher implementation (no container)
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Get a new value for this key whose value has already expired in the cache.
*
* @param key
* The key whose value has expired and needs to be refreshed.
* @param oldValue
* The old exipred value of the key.
* @param event
* The event which triggered this refresh.
* @return a new value for use in the cache for this key; if null, the entry will be removed.
*/
public Object refresh(Object key, Object oldValue, Event event)
{
Object rv = null;
// key is a reference
Reference ref = m_entityManager.newReference((String) key);
String id = ref.getId();
if (M_log.isDebugEnabled()) M_log.debug("refresh(): key " + key + " id : " + ref.getId());
// get from storage only (not cache!)
boolean collectionHint = id.endsWith(Entity.SEPARATOR);
if (collectionHint)
{
rv = m_storage.getCollection(id);
}
else
{
try
{
rv = m_storage.getResource(id);
}
catch (TypeException e)
{
M_log.error("Type Exception",e);
}
}
return rv;
} // refresh
/* Content Hosting Handlers are not implemented in the Base Content Service */
public boolean isContentHostingHandlersEnabled()
{
return false;
} // isContentHostingHandlersEnabled
/* (non-Javadoc)
* @see org.sakaiproject.content.api.SiteContentAdvisorProvider#getContentAdvisor(org.sakaiproject.site.api.Site)
*/
public SiteContentAdvisor getContentAdvisor(Site site)
{
if ( site == null ) {
return null;
}
SiteContentAdvisorProvider scap = siteContentAdvisorsProviders.get(site.getType());
if ( scap == null ) {
return null;
}
return scap.getContentAdvisor(site);
}
/* (non-Javadoc)
* @see org.sakaiproject.content.api.SiteContentAdvisorTypeRegistry#registerSiteContentAdvisorProvidor(org.sakaiproject.content.api.SiteContentAdvisorProvider, java.lang.String)
*/
public void registerSiteContentAdvisorProvidor(SiteContentAdvisorProvider advisor, String type)
{
siteContentAdvisorsProviders.put(type, advisor);
}
/**
* @return the collectionSerializer
*/
public EntitySerializer getCollectionSerializer()
{
return collectionSerializer;
}
/**
* @param collectionSerializer the collectionSerializer to set
*/
public void setCollectionSerializer(EntitySerializer collectionSerializer)
{
this.collectionSerializer = collectionSerializer;
}
/**
* @return the resourceSerializer
*/
public EntitySerializer getResourceSerializer()
{
return resourceSerializer;
}
/**
* @param resourceSerializer the resourceSerializer to set
*/
public void setResourceSerializer(EntitySerializer resourceSerializer)
{
this.resourceSerializer = resourceSerializer;
}
protected long getSizeForContext(String context)
{
return 0;
}
public void transferCopyEntities(String fromContext, String toContext, List ids, boolean cleanup)
{
transferCopyEntitiesRefMigrator(fromContext, toContext, ids, cleanup);
}
public Map<String,String> transferCopyEntitiesRefMigrator(String fromContext, String toContext, List ids, boolean cleanup)
{
Map transversalMap = new HashMap();
try
{
if(cleanup == true)
{
// Get the root collection
ContentCollection oCollection = getCollection(toContext);
if(oCollection != null)
{
// Get the collection members from the old collection
List oResources = oCollection.getMemberResources();
for (int i = 0; i < oResources.size(); i++)
{
// Get the original resource
Entity oResource = (Entity) oResources.get(i);
String oId = oResource.getId();
ResourceProperties oProperties = oResource.getProperties();
boolean isCollection = false;
try
{
isCollection = oProperties.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
}
catch (Exception e)
{
M_log.debug("Get Folder Collection" + e);
}
if (isCollection)
{
try
{
this.removeCollection(oId);
}
catch (Exception ee)
{
M_log.debug("remove folders resources" + ee);
}
}
else
{
try
{
BaseResourceEdit edit = (BaseResourceEdit) editResourceForDelete(oId);
m_storage.removeResource(edit);
}
catch (Exception ee)
{
M_log.debug("remove others resources" + ee);
}
}
}
}
}
}
catch (Exception e)
{
M_log.debug("BaseContentService Resources transferCopyEntities Error" + e);
}
transversalMap.putAll(transferCopyEntitiesRefMigrator(fromContext, toContext, ids));
return transversalMap;
}
// Code lightly adapted from Apache Tomcat 5.5.27 catalina default servlet
/**
* Range inner class. From Apache Tomcat DefaultServlet.java
*
*/
protected class Range {
public long start;
public long end;
public long length;
/**
* Validate range.
*/
public boolean validate() {
if (end >= length)
end = length - 1;
return ( (start >= 0) && (end >= 0) && (start <= end)
&& (length > 0) );
}
public void recycle() {
start = 0;
end = 0;
length = 0;
}
}
/**
* Parse the range header.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @return Vector of ranges
*/
protected ArrayList<Range> parseRange(HttpServletRequest request,
HttpServletResponse response,
long fileLength)
throws IOException {
/* Commented out pending implementation of last-modified / if-modified.
* See http://jira.sakaiproject.org/jira/browse/SAK-3916
// Checking If-Range
String headerValue = request.getHeader("If-Range");
if (headerValue != null) {
long headerValueTime = (-1L);
try {
headerValueTime = request.getDateHeader("If-Range");
} catch (Exception e) {
;
}
String eTag = getETag(resourceAttributes);
long lastModified = resourceAttributes.getLastModified();
if (headerValueTime == (-1L)) {
// If the ETag the client gave does not match the entity
// etag, then the entire entity is returned.
if (!eTag.equals(headerValue.trim()))
return FULL;
} else {
// If the timestamp of the entity the client got is older than
// the last modification date of the entity, the entire entity
// is returned.
if (lastModified > (headerValueTime + 1000))
return FULL;
}
}
*/
if (fileLength == 0)
return null;
// Retrieving the range header (if any is specified
String rangeHeader = request.getHeader("Range");
if (rangeHeader == null)
return null;
// bytes is the only range unit supported (and I don't see the point
// of adding new ones).
if (!rangeHeader.startsWith("bytes")) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
rangeHeader = rangeHeader.substring(6);
// Vector which will contain all the ranges which are successfully
// parsed.
ArrayList result = new ArrayList();
StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ",");
// Parsing the range list
while (commaTokenizer.hasMoreTokens()) {
String rangeDefinition = commaTokenizer.nextToken().trim();
Range currentRange = new Range();
currentRange.length = fileLength;
int dashPos = rangeDefinition.indexOf('-');
if (dashPos == -1) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
if (dashPos == 0) {
try {
long offset = Long.parseLong(rangeDefinition);
currentRange.start = fileLength + offset;
currentRange.end = fileLength - 1;
} catch (NumberFormatException e) {
response.addHeader("Content-Range",
"bytes */" + fileLength);
response.sendError
(HttpServletResponse
.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
} else {
try {
currentRange.start = Long.parseLong
(rangeDefinition.substring(0, dashPos));
if (dashPos < rangeDefinition.length() - 1)
currentRange.end = Long.parseLong
(rangeDefinition.substring
(dashPos + 1, rangeDefinition.length()));
else
currentRange.end = fileLength - 1;
} catch (NumberFormatException e) {
response.addHeader("Content-Range",
"bytes */" + fileLength);
response.sendError
(HttpServletResponse
.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
}
if (!currentRange.validate()) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
result.add(currentRange);
}
return result;
}
/**
* Copy the partial contents of the specified input stream to the specified
* output stream.
*
* @param istream The input stream to read from
* @param ostream The output stream to write to
* @param start Start of the range which will be copied
* @param end End of the range which will be copied
* @return Exception which occurred during processing
*/
protected IOException copyRange(InputStream istream,
OutputStream ostream,
long start, long end) {
try {
istream.skip(start);
} catch (IOException e) {
return e;
}
IOException exception = null;
long bytesToRead = end - start + 1;
byte buffer[] = new byte[STREAM_BUFFER_SIZE];
int len = buffer.length;
while ( (bytesToRead > 0) && (len >= buffer.length)) {
try {
len = istream.read(buffer);
if (bytesToRead >= len) {
ostream.write(buffer, 0, len);
bytesToRead -= len;
} else {
ostream.write(buffer, 0, (int) bytesToRead);
bytesToRead = 0;
}
} catch (IOException e) {
exception = e;
len = -1;
}
if (len < buffer.length)
break;
}
return exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream in a set of chunks as per the specified ranges.
*
* @param InputStream The input stream to read from
* @param out The output stream to write to
* @param ranges Enumeration of the ranges the client wanted to retrieve
* @param contentType Content type of the resource
* @exception IOException if an input/output error occurs
*/
protected void copyRanges(ContentResource content, OutputStream out,
Iterator ranges, String contentType)
throws IOException {
IOException exception = null;
while ( (exception == null) && (ranges.hasNext()) ) {
Range currentRange = (Range) ranges.next();
// Writing MIME header.
IOUtils.write("\r\n--" + MIME_SEPARATOR + "\r\n", out);
if (contentType != null)
IOUtils.write("Content-Type: " + contentType + "\r\n", out);
IOUtils.write("Content-Range: bytes " + currentRange.start
+ "-" + currentRange.end + "/"
+ currentRange.length + "\r\n", out);
IOUtils.write("\r\n", out);
// Printing content
InputStream in = null;
try {
in = content.streamContent();
} catch (ServerOverloadException se) {
exception = new IOException("ServerOverloadException reported getting inputstream");
throw exception;
}
InputStream istream =
new BufferedInputStream(in, STREAM_BUFFER_SIZE);
exception = copyRange(istream, out, currentRange.start, currentRange.end);
try {
istream.close();
} catch (IOException e) {
// ignore
}
}
IOUtils.write("\r\n--" + MIME_SEPARATOR + "--\r\n", out);
// Rethrow any exception that has occurred
if (exception != null) {
throw exception;
}
}
/**
* Establish a security advisor to allow the "embedded" azg work to occur with no need for additional security permissions.
*/
protected void enableAzgSecurityAdvisor()
{
// put in a security advisor so we can do our azg work without need of further permissions
// TODO: could make this more specific to the AuthzGroupService.SECURE_UPDATE_AUTHZ_GROUP permission -ggolden
m_securityService.pushAdvisor(ALLOW_ADVISOR);
}
/**
* Disabled the security advisor.
*/
protected void disableAzgSecurityAdvisor()
{
SecurityAdvisor popped = m_securityService.popAdvisor(ALLOW_ADVISOR);
if (!ALLOW_ADVISOR.equals(popped)) {
if (popped == null)
{
M_log.warn("Someone has removed our advisor.");
}
else
{
M_log.warn("Removed someone elses advisor, adding it back.");
m_securityService.pushAdvisor(popped);
}
}
}
/**
* Expand the supplied resource under its parent collection.
* If the zip is bigger than the max zip size specified in properties extraction will
* NOT occur. See KNL-273 and KNL-900.
*
* @param resourceId The zip file resource that we want to expand
* @exception Exception Anything thrown by ZipContentUtil gets passed upwards.
*/
public void expandZippedResource(String resourceId) throws Exception {
int maxZipExtractSize = ZipContentUtil.getMaxZipExtractFiles();
ZipContentUtil extractZipArchive = new ZipContentUtil();
// KNL-900 Total size of files should be checked before unzipping (KNL-273)
Map<String, Long> zipManifest = extractZipArchive.getZipManifest(resourceId);
if (zipManifest == null) {
M_log.error("Zip file for resource ("+resourceId+") has no zip manifest, cannot extract");
} else if (zipManifest.size() >= maxZipExtractSize) {
M_log.warn("Zip file for resource ("+resourceId+") is too large to be expanded, size("+zipManifest.size()+") exceeds the max=("+maxZipExtractSize+") as specified in setting content.zip.expand.maxfiles");
} else {
// zip is not too large to extract so check if files are too large
long totalSize = 0;
for (Long entrySize : zipManifest.values()) {
totalSize += entrySize;
}
// Get a context
ContentResourceEdit resource = editResource(resourceId);
// Set the updated length for quota checking
resource.setContentLength(totalSize);
if (M_log.isDebugEnabled()) M_log.debug(String.format("Resource is: [%s] Size is [%d]",resourceId, totalSize));
// check for over quota.
if (overQuota(resource)) {
M_log.error("Zip file for resource ("+resourceId+") would be too large after unzip so it cannot be expanded, totalSize("+totalSize+") exceeds the resource quota");
throw new OverQuotaException(resource.getReference());
}
// zip files are not too large to extract so do the extract
extractZipArchive.extractArchive(resourceId);
cancelResource(resource); //commitResource(resource); // KNL-1220
}
}
private static final String MACRO_USER_ID = "${USER_ID}";
private static final String MACRO_USER_EID = "${USER_EID}";
private static final String MACRO_USER_FIRST_NAME = "${USER_FIRST_NAME}";
private static final String MACRO_USER_LAST_NAME = "${USER_LAST_NAME}";
private static final String MACRO_SESSION_ID = "${SESSION_ID}";
private static final String MACRO_DEFAULT_ALLOWED = "${USER_ID},${USER_EID},${USER_FIRST_NAME},${USER_LAST_NAME}";
/**
* Expands a URL that may contain a set of predefined macros, into the full URL.
* This should only ever happen when its about to be redirected to, ie never stored and never displayed
* so that people dont accidentally send an expanded URL containing personally identifying information to someone else, for example.
* @param url original url that may contain macros
* @return url with macros expanded
*
* Note that much of this is from the web content tool though site related properties have been removed. This is actually called from /access/ which has no site context so
* any lookups of site_id or user role (which infers a site) will not work. The site_id may be able to be passed in, as the original resource does have context,
* however that needs to be more fully explored for security reasons and as such, has not been included.
*
* See SAK-23587
*/
private String expandMacros(String url) {
if(M_log.isDebugEnabled()){
M_log.debug("Original url: " + url);
}
if (!StringUtils.contains(url, "${")) {
return url;
}
//handled explicitly like this for backwards compatibility since comma separated strings from SCS are not supported in all versions of Sakai yet.
String allowedMacros = m_serverConfigurationService.getString("content.allowed.macros", MACRO_DEFAULT_ALLOWED);
List<String> macros = new ArrayList<String>();
if(StringUtils.isNotBlank(allowedMacros)) {
macros = Arrays.asList(StringUtils.split(allowedMacros, ','));
}
for(String macro: macros) {
url = StringUtils.replace(url, macro, getMacroValue(macro));
}
if(M_log.isDebugEnabled()){
M_log.debug("Expanded url: " + url);
}
return url;
}
/**
* Helper to get the value for a given macro.
* @param macroName
* @return
*/
private String getMacroValue(String macroName) {
try {
if (macroName.equals(MACRO_USER_ID)) {
return userDirectoryService.getCurrentUser().getId();
}
if (macroName.equals(MACRO_USER_EID)) {
return userDirectoryService.getCurrentUser().getEid();
}
if (macroName.equals(MACRO_USER_FIRST_NAME)) {
return userDirectoryService.getCurrentUser().getFirstName();
}
if (macroName.equals(MACRO_USER_LAST_NAME)) {
return userDirectoryService.getCurrentUser().getLastName();
}
if (macroName.equals(MACRO_SESSION_ID)) {
return sessionManager.getCurrentSession().getId();
}
}
catch (Exception e) {
M_log.error("Error resolving macro:" + macroName + ": " + e.getClass() + ": " + e.getCause());
return "";
}
//unsupported, use macro name as is.
return macroName;
}
/**
* Implementation of HardDeleteAware to allow content to be fully purged
*/
public void hardDelete(String siteId) {
/* Needs to cater for both db and filesystem storage, and there are a couple of situations to be handled
* 1. FS storage. File content is actually deleted so we can just issue a delete on the files and we are done.
* 2. FS storage + restore function enabled. File is deleted as per 1 however a copy of file is retained in bodyPathDeleted location
* 3. DB storage. Binary is (meant to be) deleted. Backup binary is created.
*
* Therefore we need to delete the files (1 handled), then get any backed up files and delete them also (2 and 3 handled). Then delete the collection to finalise things.
*/
//get collection for the site
String collectionId = getSiteCollection(siteId);
M_log.debug("collectionId: " + collectionId);
//handle 1
try {
List<ContentResource> resources = getAllResources(collectionId);
for(ContentResource resource: resources) {
M_log.debug("Removing resource: " + resource.getId());
removeResource(resource.getId());
}
} catch (Exception e) {
e.printStackTrace();
//ignore and try to proceed
}
//handle2
//only for 2.10 - comment this out for 2.9 and below
try {
List<ContentResource> deletedResources = getAllDeletedResources(collectionId);
for(ContentResource deletedResource: deletedResources) {
M_log.debug("Removing deleted resource: " + deletedResource.getId());
removeDeletedResource(deletedResource.getId());
}
} catch (Exception e) {
e.printStackTrace();
//ignore and try to proceed
}
//cleanup
try {
M_log.debug("Removing collection: " + collectionId);
removeCollection(collectionId);
} catch (Exception e) {
e.printStackTrace();
//ignore and try to proceed
}
}
} // BaseContentService
| udayg/sakai | kernel/kernel-impl/src/main/java/org/sakaiproject/content/impl/BaseContentService.java | Java | apache-2.0 | 429,329 |
package batchapi
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/azure-sdk-for-go/services/batch/2019-08-01.10.0/batch"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
"github.com/satori/go.uuid"
)
// ApplicationClientAPI contains the set of methods on the ApplicationClient type.
type ApplicationClientAPI interface {
Get(ctx context.Context, applicationID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.ApplicationSummary, err error)
List(ctx context.Context, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.ApplicationListResultPage, err error)
}
var _ ApplicationClientAPI = (*batch.ApplicationClient)(nil)
// PoolClientAPI contains the set of methods on the PoolClient type.
type PoolClientAPI interface {
Add(ctx context.Context, pool batch.PoolAddParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Delete(ctx context.Context, poolID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
DisableAutoScale(ctx context.Context, poolID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
EnableAutoScale(ctx context.Context, poolID string, poolEnableAutoScaleParameter batch.PoolEnableAutoScaleParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
EvaluateAutoScale(ctx context.Context, poolID string, poolEvaluateAutoScaleParameter batch.PoolEvaluateAutoScaleParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.AutoScaleRun, err error)
Exists(ctx context.Context, poolID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Get(ctx context.Context, poolID string, selectParameter string, expand string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result batch.CloudPool, err error)
GetAllLifetimeStatistics(ctx context.Context, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.PoolStatistics, err error)
List(ctx context.Context, filter string, selectParameter string, expand string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudPoolListResultPage, err error)
ListUsageMetrics(ctx context.Context, startTime *date.Time, endTime *date.Time, filter string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.PoolListUsageMetricsResultPage, err error)
Patch(ctx context.Context, poolID string, poolPatchParameter batch.PoolPatchParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
RemoveNodes(ctx context.Context, poolID string, nodeRemoveParameter batch.NodeRemoveParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Resize(ctx context.Context, poolID string, poolResizeParameter batch.PoolResizeParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
StopResize(ctx context.Context, poolID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
UpdateProperties(ctx context.Context, poolID string, poolUpdatePropertiesParameter batch.PoolUpdatePropertiesParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
}
var _ PoolClientAPI = (*batch.PoolClient)(nil)
// AccountClientAPI contains the set of methods on the AccountClient type.
type AccountClientAPI interface {
ListPoolNodeCounts(ctx context.Context, filter string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.PoolNodeCountsListResultPage, err error)
ListSupportedImages(ctx context.Context, filter string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.AccountListSupportedImagesResultPage, err error)
}
var _ AccountClientAPI = (*batch.AccountClient)(nil)
// JobClientAPI contains the set of methods on the JobClient type.
type JobClientAPI interface {
Add(ctx context.Context, job batch.JobAddParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Delete(ctx context.Context, jobID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Disable(ctx context.Context, jobID string, jobDisableParameter batch.JobDisableParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Enable(ctx context.Context, jobID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Get(ctx context.Context, jobID string, selectParameter string, expand string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result batch.CloudJob, err error)
GetAllLifetimeStatistics(ctx context.Context, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.JobStatistics, err error)
GetTaskCounts(ctx context.Context, jobID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.TaskCounts, err error)
List(ctx context.Context, filter string, selectParameter string, expand string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudJobListResultPage, err error)
ListFromJobSchedule(ctx context.Context, jobScheduleID string, filter string, selectParameter string, expand string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudJobListResultPage, err error)
ListPreparationAndReleaseTaskStatus(ctx context.Context, jobID string, filter string, selectParameter string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudJobListPreparationAndReleaseTaskStatusResultPage, err error)
Patch(ctx context.Context, jobID string, jobPatchParameter batch.JobPatchParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Terminate(ctx context.Context, jobID string, jobTerminateParameter *batch.JobTerminateParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Update(ctx context.Context, jobID string, jobUpdateParameter batch.JobUpdateParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
}
var _ JobClientAPI = (*batch.JobClient)(nil)
// CertificateClientAPI contains the set of methods on the CertificateClient type.
type CertificateClientAPI interface {
Add(ctx context.Context, certificate batch.CertificateAddParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
CancelDeletion(ctx context.Context, thumbprintAlgorithm string, thumbprint string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Delete(ctx context.Context, thumbprintAlgorithm string, thumbprint string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Get(ctx context.Context, thumbprintAlgorithm string, thumbprint string, selectParameter string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.Certificate, err error)
List(ctx context.Context, filter string, selectParameter string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CertificateListResultPage, err error)
}
var _ CertificateClientAPI = (*batch.CertificateClient)(nil)
// FileClientAPI contains the set of methods on the FileClient type.
type FileClientAPI interface {
DeleteFromComputeNode(ctx context.Context, poolID string, nodeID string, filePath string, recursive *bool, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
DeleteFromTask(ctx context.Context, jobID string, taskID string, filePath string, recursive *bool, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
GetFromComputeNode(ctx context.Context, poolID string, nodeID string, filePath string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ocpRange string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result batch.ReadCloser, err error)
GetFromTask(ctx context.Context, jobID string, taskID string, filePath string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ocpRange string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result batch.ReadCloser, err error)
GetPropertiesFromComputeNode(ctx context.Context, poolID string, nodeID string, filePath string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
GetPropertiesFromTask(ctx context.Context, jobID string, taskID string, filePath string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
ListFromComputeNode(ctx context.Context, poolID string, nodeID string, filter string, recursive *bool, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.NodeFileListResultPage, err error)
ListFromTask(ctx context.Context, jobID string, taskID string, filter string, recursive *bool, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.NodeFileListResultPage, err error)
}
var _ FileClientAPI = (*batch.FileClient)(nil)
// JobScheduleClientAPI contains the set of methods on the JobScheduleClient type.
type JobScheduleClientAPI interface {
Add(ctx context.Context, cloudJobSchedule batch.JobScheduleAddParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Delete(ctx context.Context, jobScheduleID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Disable(ctx context.Context, jobScheduleID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Enable(ctx context.Context, jobScheduleID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Exists(ctx context.Context, jobScheduleID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Get(ctx context.Context, jobScheduleID string, selectParameter string, expand string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result batch.CloudJobSchedule, err error)
List(ctx context.Context, filter string, selectParameter string, expand string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudJobScheduleListResultPage, err error)
Patch(ctx context.Context, jobScheduleID string, jobSchedulePatchParameter batch.JobSchedulePatchParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Terminate(ctx context.Context, jobScheduleID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Update(ctx context.Context, jobScheduleID string, jobScheduleUpdateParameter batch.JobScheduleUpdateParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
}
var _ JobScheduleClientAPI = (*batch.JobScheduleClient)(nil)
// TaskClientAPI contains the set of methods on the TaskClient type.
type TaskClientAPI interface {
Add(ctx context.Context, jobID string, task batch.TaskAddParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
AddCollection(ctx context.Context, jobID string, taskCollection batch.TaskAddCollectionParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.TaskAddCollectionResult, err error)
Delete(ctx context.Context, jobID string, taskID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Get(ctx context.Context, jobID string, taskID string, selectParameter string, expand string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result batch.CloudTask, err error)
List(ctx context.Context, jobID string, filter string, selectParameter string, expand string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudTaskListResultPage, err error)
ListSubtasks(ctx context.Context, jobID string, taskID string, selectParameter string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.CloudTaskListSubtasksResult, err error)
Reactivate(ctx context.Context, jobID string, taskID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Terminate(ctx context.Context, jobID string, taskID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
Update(ctx context.Context, jobID string, taskID string, taskUpdateParameter batch.TaskUpdateParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123, ifMatch string, ifNoneMatch string, ifModifiedSince *date.TimeRFC1123, ifUnmodifiedSince *date.TimeRFC1123) (result autorest.Response, err error)
}
var _ TaskClientAPI = (*batch.TaskClient)(nil)
// ComputeNodeClientAPI contains the set of methods on the ComputeNodeClient type.
type ComputeNodeClientAPI interface {
AddUser(ctx context.Context, poolID string, nodeID string, userParameter batch.ComputeNodeUser, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
DeleteUser(ctx context.Context, poolID string, nodeID string, userName string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
DisableScheduling(ctx context.Context, poolID string, nodeID string, nodeDisableSchedulingParameter *batch.NodeDisableSchedulingParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
EnableScheduling(ctx context.Context, poolID string, nodeID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Get(ctx context.Context, poolID string, nodeID string, selectParameter string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.ComputeNode, err error)
GetRemoteDesktop(ctx context.Context, poolID string, nodeID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.ReadCloser, err error)
GetRemoteLoginSettings(ctx context.Context, poolID string, nodeID string, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.ComputeNodeGetRemoteLoginSettingsResult, err error)
List(ctx context.Context, poolID string, filter string, selectParameter string, maxResults *int32, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.ComputeNodeListResultPage, err error)
Reboot(ctx context.Context, poolID string, nodeID string, nodeRebootParameter *batch.NodeRebootParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
Reimage(ctx context.Context, poolID string, nodeID string, nodeReimageParameter *batch.NodeReimageParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
UpdateUser(ctx context.Context, poolID string, nodeID string, userName string, nodeUpdateUserParameter batch.NodeUpdateUserParameter, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result autorest.Response, err error)
UploadBatchServiceLogs(ctx context.Context, poolID string, nodeID string, uploadBatchServiceLogsConfiguration batch.UploadBatchServiceLogsConfiguration, timeout *int32, clientRequestID *uuid.UUID, returnClientRequestID *bool, ocpDate *date.TimeRFC1123) (result batch.UploadBatchServiceLogsResult, err error)
}
var _ ComputeNodeClientAPI = (*batch.ComputeNodeClient)(nil)
| pweil-/origin | vendor/github.com/Azure/azure-sdk-for-go/services/batch/2019-08-01.10.0/batch/batchapi/interfaces.go | GO | apache-2.0 | 23,089 |
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.worker;
import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxInputs;
import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxOutputs;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.IOException;
import java.util.Set;
/** A {@link Worker} that runs inside a sandboxed execution root. */
final class SandboxedWorker extends Worker {
private final Path workDir;
private WorkerExecRoot workerExecRoot;
SandboxedWorker(WorkerKey workerKey, int workerId, Path workDir, Path logFile) {
super(workerKey, workerId, workDir, logFile);
this.workDir = workDir;
}
@Override
void destroy() throws IOException {
super.destroy();
workDir.deleteTree();
}
@Override
public void prepareExecution(
SandboxInputs inputFiles, SandboxOutputs outputs, Set<PathFragment> workerFiles)
throws IOException {
// Note that workerExecRoot isn't necessarily null at this point, so we can't do a Preconditions
// check for it: If a WorkerSpawnStrategy gets interrupted, finishExecution is not guaranteed to
// be called.
workerExecRoot = new WorkerExecRoot(workDir, inputFiles, outputs, workerFiles);
workerExecRoot.createFileSystem();
super.prepareExecution(inputFiles, outputs, workerFiles);
}
@Override
public void finishExecution(Path execRoot) throws IOException {
super.finishExecution(execRoot);
workerExecRoot.copyOutputs(execRoot);
workerExecRoot = null;
}
}
| davidzchen/bazel | src/main/java/com/google/devtools/build/lib/worker/SandboxedWorker.java | Java | apache-2.0 | 2,178 |
#include "cbase.h"
#include "nb_select_mission_panel.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/ImagePanel.h"
#include "vgui_controls/Button.h"
#include "nb_select_mission_entry.h"
#include "nb_horiz_list.h"
#include "nb_header_footer.h"
#include "missionchooser/iasw_mission_chooser.h"
#include "missionchooser/iasw_mission_chooser_source.h"
#include "nb_button.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
CNB_Select_Mission_Panel::CNB_Select_Mission_Panel( vgui::Panel *parent, const char *name ) : BaseClass( parent, name )
{
// == MANAGED_MEMBER_CREATION_START: Do not edit by hand ==
m_pHeaderFooter = new CNB_Header_Footer( this, "HeaderFooter" );
m_pTitle = new vgui::Label( this, "Title", "" );
m_pHorizList = new CNB_Horiz_List( this, "HorizList" );
// == MANAGED_MEMBER_CREATION_END ==
m_pBackButton = new CNB_Button( this, "BackButton", "", this, "BackButton" );
m_pHeaderFooter->SetTitle( "" );
m_pHeaderFooter->SetHeaderEnabled( false );
m_pHeaderFooter->SetFooterEnabled( false );
m_szCampaignFilter[0] = 0;
m_nLastCount = -1;
}
CNB_Select_Mission_Panel::~CNB_Select_Mission_Panel()
{
}
void CNB_Select_Mission_Panel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "resource/ui/nb_select_mission_panel.res" );
m_pHorizList->m_pBackgroundImage->SetImage( "briefing/select_marine_list_bg" );
m_pHorizList->m_pForegroundImage->SetImage( "briefing/horiz_list_fg" );
}
void CNB_Select_Mission_Panel::PerformLayout()
{
BaseClass::PerformLayout();
}
bool CampaignContainsMission( KeyValues *pCampaignKeys, const char *szMissionName )
{
char szMissionStripped[256];
Q_StripExtension( szMissionName, szMissionStripped, sizeof( szMissionStripped ) );
for ( KeyValues *pMissionKey = pCampaignKeys->GetFirstSubKey(); pMissionKey; pMissionKey = pMissionKey->GetNextKey() )
{
if ( !Q_stricmp( pMissionKey->GetName(), "MISSION" ) )
{
const char *szMapName = pMissionKey->GetString( "MapName", "none" );
if ( !Q_stricmp( szMapName, szMissionStripped ) )
return true;
}
}
return false;
}
int GetMissionIndex( IASW_Mission_Chooser_Source *pSource, const char *szMapName )
{
int nMissions = pSource->GetNumMissions( true );
for ( int i = 0; i < nMissions; i++ )
{
ASW_Mission_Chooser_Mission* pMission = pSource->GetMission( i, true );
char pTemp[64];
Q_StripExtension( pMission->m_szMissionName, pTemp, sizeof(pTemp) );
if ( !Q_stricmp( pTemp, szMapName ) )
{
return i;
}
}
return -1;
}
void CNB_Select_Mission_Panel::OnThink()
{
BaseClass::OnThink();
IASW_Mission_Chooser_Source *pSource = missionchooser ? missionchooser->LocalMissionSource() : NULL;
// TODO: If voting, then use:
//IASW_Mission_Chooser_Source *pSource = GetVotingMissionSource();
if ( !pSource )
{
//Warning( "Unable to select a mission as couldn't find an IASW_Mission_Chooser_Source\n" );
return;
}
pSource->Think();
KeyValues *pCampaignDetails = NULL;
if ( m_szCampaignFilter[0] )
{
pCampaignDetails = pSource->GetCampaignDetails( m_szCampaignFilter );
}
int nCount = 0;
if ( pCampaignDetails )
{
bool bSkippedFirst = false;
for ( KeyValues *pMission = pCampaignDetails->GetFirstSubKey(); pMission; pMission = pMission->GetNextKey() )
{
if ( !Q_stricmp( pMission->GetName(), "MISSION" ) )
{
if ( !bSkippedFirst )
{
bSkippedFirst = true;
}
else
{
const char *szMapName = pMission->GetString( "MapName", "asi-jac1-landingbay01" );
int nMissionIndex = GetMissionIndex( pSource, szMapName );
if ( nMissionIndex == -1 )
continue;
if ( m_pHorizList->m_Entries.Count() < nCount + 1 )
{
CNB_Select_Mission_Entry *pEntry = new CNB_Select_Mission_Entry( NULL, "Select_Mission_Entry" );
m_pHorizList->AddEntry( pEntry );
}
CNB_Select_Mission_Entry *pEntry = dynamic_cast<CNB_Select_Mission_Entry*>( m_pHorizList->m_Entries[nCount].Get() );
if ( pEntry )
{
pEntry->m_nMissionIndex = nMissionIndex;
}
nCount++;
}
}
}
}
else
{
int nMissions = pSource->GetNumMissions( true );
for ( int i = 0; i < nMissions; i++ )
{
//ASW_Mission_Chooser_Mission* pMission = pSource->GetMission( i, true );
//if ( pMission && pCampaignKeys && !CampaignContainsMission( pCampaignKeys, pMission->m_szMissionName ) )
//continue;
if ( m_pHorizList->m_Entries.Count() < nCount + 1 )
{
CNB_Select_Mission_Entry *pEntry = new CNB_Select_Mission_Entry( NULL, "Select_Mission_Entry" );
m_pHorizList->AddEntry( pEntry );
}
CNB_Select_Mission_Entry *pEntry = dynamic_cast<CNB_Select_Mission_Entry*>( m_pHorizList->m_Entries[nCount].Get() );
if ( pEntry )
{
pEntry->m_nMissionIndex = i;
}
nCount++;
}
}
// empty out remaining slots
for ( int i = nCount; i < m_pHorizList->m_Entries.Count(); i++ )
{
CNB_Select_Mission_Entry *pEntry = dynamic_cast<CNB_Select_Mission_Entry*>( m_pHorizList->m_Entries[i].Get() );
if ( pEntry )
{
pEntry->m_nMissionIndex = -1;
}
}
if ( nCount != m_nLastCount )
{
m_nLastCount = nCount;
InvalidateLayout( true, true );
}
}
void CNB_Select_Mission_Panel::InitList()
{
if ( m_szCampaignFilter[0] )
{
m_pTitle->SetText( "#nb_select_starting_mission" );
}
else
{
m_pTitle->SetText( "#nb_select_mission" );
}
}
void CNB_Select_Mission_Panel::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "BackButton" ) )
{
MarkForDeletion();
return;
}
else if ( !Q_stricmp( command, "AcceptButton" ) )
{
GetParent()->OnCommand( command );
return;
}
BaseClass::OnCommand( command );
}
void CNB_Select_Mission_Panel::MissionSelected( ASW_Mission_Chooser_Mission *pMission )
{
if ( !pMission || !pMission->m_szMissionName || pMission->m_szMissionName[0] == 0 )
return;
// pass selected mission name up to vgamesettings
char buffer[ 256 ];
Q_snprintf( buffer, sizeof( buffer ), "cmd_mission_selected_%s", pMission->m_szMissionName );
GetParent()->OnCommand( buffer );
MarkForDeletion();
}
void CNB_Select_Mission_Panel::SelectMissionsFromCampaign( const char *szCampaignName )
{
if ( !szCampaignName )
return;
Q_snprintf( m_szCampaignFilter, sizeof( m_szCampaignFilter ), "%s", szCampaignName );
} | ppittle/AlienSwarmDirectorMod | trunk/src/game/client/swarm/vgui/nb_select_mission_panel.cpp | C++ | apache-2.0 | 6,331 |
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32: FIXME #13256
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:print 'c-style-enum::SINGLE_VARIANT'
// gdb-check:$1 = TheOnlyVariant
// gdb-command:print 'c-style-enum::AUTO_ONE'
// gdb-check:$2 = One
// gdb-command:print 'c-style-enum::AUTO_TWO'
// gdb-check:$3 = One
// gdb-command:print 'c-style-enum::AUTO_THREE'
// gdb-check:$4 = One
// gdb-command:print 'c-style-enum::MANUAL_ONE'
// gdb-check:$5 = OneHundred
// gdb-command:print 'c-style-enum::MANUAL_TWO'
// gdb-check:$6 = OneHundred
// gdb-command:print 'c-style-enum::MANUAL_THREE'
// gdb-check:$7 = OneHundred
// gdb-command:run
// gdb-command:finish
// gdb-command:print auto_one
// gdb-check:$8 = One
// gdb-command:print auto_two
// gdb-check:$9 = Two
// gdb-command:print auto_three
// gdb-check:$10 = Three
// gdb-command:print manual_one_hundred
// gdb-check:$11 = OneHundred
// gdb-command:print manual_one_thousand
// gdb-check:$12 = OneThousand
// gdb-command:print manual_one_million
// gdb-check:$13 = OneMillion
// gdb-command:print single_variant
// gdb-check:$14 = TheOnlyVariant
// gdb-command:print 'c-style-enum::AUTO_TWO'
// gdb-check:$15 = Two
// gdb-command:print 'c-style-enum::AUTO_THREE'
// gdb-check:$16 = Three
// gdb-command:print 'c-style-enum::MANUAL_TWO'
// gdb-check:$17 = OneThousand
// gdb-command:print 'c-style-enum::MANUAL_THREE'
// gdb-check:$18 = OneMillion
#![allow(unused_variable)]
#![allow(dead_code)]
enum AutoDiscriminant {
One,
Two,
Three
}
enum ManualDiscriminant {
OneHundred = 100,
OneThousand = 1000,
OneMillion = 1000000
}
enum SingleVariant {
TheOnlyVariant
}
static SINGLE_VARIANT: SingleVariant = TheOnlyVariant;
static mut AUTO_ONE: AutoDiscriminant = One;
static mut AUTO_TWO: AutoDiscriminant = One;
static mut AUTO_THREE: AutoDiscriminant = One;
static mut MANUAL_ONE: ManualDiscriminant = OneHundred;
static mut MANUAL_TWO: ManualDiscriminant = OneHundred;
static mut MANUAL_THREE: ManualDiscriminant = OneHundred;
fn main() {
let auto_one = One;
let auto_two = Two;
let auto_three = Three;
let manual_one_hundred = OneHundred;
let manual_one_thousand = OneThousand;
let manual_one_million = OneMillion;
let single_variant = TheOnlyVariant;
unsafe {
AUTO_TWO = Two;
AUTO_THREE = Three;
MANUAL_TWO = OneThousand;
MANUAL_THREE = OneMillion;
};
zzz();
let a = SINGLE_VARIANT;
let a = unsafe { AUTO_ONE };
let a = unsafe { MANUAL_ONE };
}
fn zzz() {()}
| stepancheg/rust-ide-rust | src/test/debuginfo/c-style-enum.rs | Rust | apache-2.0 | 3,049 |
package org.mifos.dto.screen;
import java.io.Serializable;
import java.util.Locale;
import org.joda.time.DateTime;
@SuppressWarnings("PMD")
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="SE_NO_SERIALVERSIONID", justification="should disable at filter level and also for pmd - not important for us")
public class PersonnelNoteDto implements Serializable {
private final DateTime commentDate;
private final String comment;
private final String personnelName;
public PersonnelNoteDto(DateTime commentDate, String comment, String personnelName) {
this.commentDate = commentDate;
this.comment = comment;
this.personnelName = personnelName;
}
public String getCommentDateFormatted() {
return org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy").withLocale(Locale.getDefault()).print(this.commentDate);
}
public DateTime getCommentDate() {
return this.commentDate;
}
public String getComment() {
return this.comment;
}
public String getPersonnelName() {
return this.personnelName;
}
} | maduhu/mifos-head | serviceInterfaces/src/main/java/org/mifos/dto/screen/PersonnelNoteDto.java | Java | apache-2.0 | 1,112 |
/*
* Copyright 2011 Sonian Inc.
*
* 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 com.sonian.elasticsearch.zookeeper.discovery.embedded;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.env.Environment;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
/**
* @author imotov
*/
public class EmbeddedZooKeeperService extends AbstractLifecycleComponent<EmbeddedZooKeeper> implements EmbeddedZooKeeper {
private ZooKeeperServer zooKeeperServer;
private ServerCnxnFactory cnxnFactory;
public EmbeddedZooKeeperService(Settings settings, Environment environment) {
super(settings);
try {
zooKeeperServer = new ZooKeeperServer();
File zooKeeperDir = new File(environment.dataFiles()[0], "zookeeper");
FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(zooKeeperDir, zooKeeperDir);
zooKeeperServer.setTxnLogFactory(fileTxnSnapLog);
zooKeeperServer.setTickTime(ZooKeeperServer.DEFAULT_TICK_TIME);
// Large session timeout so it doesn't time out during debugging
zooKeeperServer.setMinSessionTimeout(100000);
zooKeeperServer.setMaxSessionTimeout(100000);
String zooKeeperPort = settings.get("zookeeper.port", "2800-2900");
PortsRange portsRange = new PortsRange(zooKeeperPort);
for (int port : portsRange.ports()) {
InetSocketAddress address = new InetSocketAddress(port);
try {
cnxnFactory = NIOServerCnxnFactory.createFactory(address, -1);
zooKeeperServer.setServerCnxnFactory(cnxnFactory);
break;
} catch (BindException bindException) {
// Ignore
}
}
} catch (Exception ex) {
logger.error("ZooKeeper initialization failed ", ex);
}
}
@Override protected void doStart() throws ElasticsearchException {
try {
cnxnFactory.startup(zooKeeperServer);
} catch (IOException e) {
throw new ElasticsearchException("Cannot start ZooKeeper", e);
} catch (InterruptedException e) {
throw new ElasticsearchException("ZooKeeper startup interrupted", e);
}
}
@Override protected void doStop() throws ElasticsearchException {
cnxnFactory.shutdown();
}
@Override protected void doClose() throws ElasticsearchException {
}
@Override public int port() {
return zooKeeperServer.getClientPort();
}
@Override public void expireSession(long sessionId) {
logger.info("Expiring session {}", sessionId);
zooKeeperServer.closeSession(sessionId);
}
}
| fabric8io/elasticsearch-zookeeper | src/test/java/com/sonian/elasticsearch/zookeeper/discovery/embedded/EmbeddedZooKeeperService.java | Java | apache-2.0 | 3,724 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.arrow.dataset.source;
import org.apache.arrow.vector.types.pojo.Schema;
/**
* DatasetFactory provides a way to inspect a Dataset potential
* schema before materializing it. Thus, the user can peek the schema for
* data sources and decide on a unified schema.
*/
public interface DatasetFactory extends AutoCloseable {
/**
* Get unified schema for the resulting Dataset.
*
* @return the schema object inspected
*/
Schema inspect();
/**
* Create a Dataset with auto-inferred schema. Which means, the schema of the resulting Dataset will be
* the same with calling {@link #inspect()} manually.
*
* @return the Dataset instance
*/
Dataset finish();
/**
* Create a Dataset with predefined schema. Schema inference will not be performed.
*
* @param schema a predefined schema
* @return the Dataset instance
*/
Dataset finish(Schema schema);
}
| cpcloud/arrow | java/dataset/src/main/java/org/apache/arrow/dataset/source/DatasetFactory.java | Java | apache-2.0 | 1,721 |
/*
* Copyright 2016 JBoss Inc
*
* 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 io.apiman.manager.api.jdbc.handlers;
import io.apiman.manager.api.beans.metrics.ResponseStatsDataPoint;
import io.apiman.manager.api.beans.metrics.ResponseStatsPerPlanBean;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.dbutils.ResultSetHandler;
/**
* @author [email protected]
*/
public class ResponseStatsPerPlanHandler implements ResultSetHandler<ResponseStatsPerPlanBean> {
/**
* Constructor.
*/
public ResponseStatsPerPlanHandler() {
}
/**
* @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
*/
@Override
public ResponseStatsPerPlanBean handle(ResultSet rs) throws SQLException {
ResponseStatsPerPlanBean rval = new ResponseStatsPerPlanBean();
while (rs.next()) {
String plan = rs.getString(1);
if (plan == null) {
continue;
}
String rtype = rs.getString(2);
long count = rs.getLong(3);
ResponseStatsDataPoint dataPoint = rval.getData().get(plan);
if (dataPoint == null) {
dataPoint = new ResponseStatsDataPoint();
rval.getData().put(plan, dataPoint);
}
if (rtype == null) {
dataPoint.setTotal(dataPoint.getErrors() + dataPoint.getFailures() + count);
} else if (rtype.equals("failure")) { //$NON-NLS-1$
dataPoint.setTotal(dataPoint.getTotal() + count);
dataPoint.setFailures(count);
} else if (rtype.equals("error")) { //$NON-NLS-1$
dataPoint.setTotal(dataPoint.getTotal() + count);
dataPoint.setErrors(count);
}
}
return rval;
}
}
| kahboom/apiman | manager/api/jdbc/src/main/java/io/apiman/manager/api/jdbc/handlers/ResponseStatsPerPlanHandler.java | Java | apache-2.0 | 2,400 |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* Security Support Provider Interface (SSPI)
*
* Copyright 2012-2014 Marc-Andre Moreau <[email protected]>
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <winpr/windows.h>
#include <winpr/crt.h>
#include <winpr/sspi.h>
#include <winpr/ssl.h>
#include <winpr/print.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "sspi.h"
#include "sspi_winpr.h"
#include "../log.h"
#define TAG WINPR_TAG("sspi")
/* Authentication Functions: http://msdn.microsoft.com/en-us/library/windows/desktop/aa374731/ */
extern const SecPkgInfoA NTLM_SecPkgInfoA;
extern const SecPkgInfoW NTLM_SecPkgInfoW;
extern const SecurityFunctionTableA NTLM_SecurityFunctionTableA;
extern const SecurityFunctionTableW NTLM_SecurityFunctionTableW;
extern const SecPkgInfoA NEGOTIATE_SecPkgInfoA;
extern const SecPkgInfoW NEGOTIATE_SecPkgInfoW;
extern const SecurityFunctionTableA NEGOTIATE_SecurityFunctionTableA;
extern const SecurityFunctionTableW NEGOTIATE_SecurityFunctionTableW;
extern const SecPkgInfoA CREDSSP_SecPkgInfoA;
extern const SecPkgInfoW CREDSSP_SecPkgInfoW;
extern const SecurityFunctionTableA CREDSSP_SecurityFunctionTableA;
extern const SecurityFunctionTableW CREDSSP_SecurityFunctionTableW;
extern const SecPkgInfoA SCHANNEL_SecPkgInfoA;
extern const SecPkgInfoW SCHANNEL_SecPkgInfoW;
extern const SecurityFunctionTableA SCHANNEL_SecurityFunctionTableA;
extern const SecurityFunctionTableW SCHANNEL_SecurityFunctionTableW;
const SecPkgInfoA* SecPkgInfoA_LIST[] =
{
&NTLM_SecPkgInfoA,
&NEGOTIATE_SecPkgInfoA,
&CREDSSP_SecPkgInfoA,
&SCHANNEL_SecPkgInfoA
};
const SecPkgInfoW* SecPkgInfoW_LIST[] =
{
&NTLM_SecPkgInfoW,
&NEGOTIATE_SecPkgInfoW,
&CREDSSP_SecPkgInfoW,
&SCHANNEL_SecPkgInfoW
};
SecurityFunctionTableA winpr_SecurityFunctionTableA;
SecurityFunctionTableW winpr_SecurityFunctionTableW;
struct _SecurityFunctionTableA_NAME
{
SEC_CHAR* Name;
const SecurityFunctionTableA* SecurityFunctionTable;
};
typedef struct _SecurityFunctionTableA_NAME SecurityFunctionTableA_NAME;
struct _SecurityFunctionTableW_NAME
{
SEC_WCHAR* Name;
const SecurityFunctionTableW* SecurityFunctionTable;
};
typedef struct _SecurityFunctionTableW_NAME SecurityFunctionTableW_NAME;
const SecurityFunctionTableA_NAME SecurityFunctionTableA_NAME_LIST[] =
{
{ "NTLM", &NTLM_SecurityFunctionTableA },
{ "Negotiate", &NEGOTIATE_SecurityFunctionTableA },
{ "CREDSSP", &CREDSSP_SecurityFunctionTableA },
{ "Schannel", &SCHANNEL_SecurityFunctionTableA }
};
WCHAR NTLM_NAME_W[] = { 'N','T','L','M','\0' };
WCHAR NEGOTIATE_NAME_W[] = { 'N','e','g','o','t','i','a','t','e','\0' };
WCHAR CREDSSP_NAME_W[] = { 'C','r','e','d','S','S','P','\0' };
WCHAR SCHANNEL_NAME_W[] = { 'S','c','h','a','n','n','e','l','\0' };
const SecurityFunctionTableW_NAME SecurityFunctionTableW_NAME_LIST[] =
{
{ NTLM_NAME_W, &NTLM_SecurityFunctionTableW },
{ NEGOTIATE_NAME_W, &NEGOTIATE_SecurityFunctionTableW },
{ CREDSSP_NAME_W, &CREDSSP_SecurityFunctionTableW },
{ SCHANNEL_NAME_W, &SCHANNEL_SecurityFunctionTableW }
};
#define SecHandle_LOWER_MAX 0xFFFFFFFF
#define SecHandle_UPPER_MAX 0xFFFFFFFE
struct _CONTEXT_BUFFER_ALLOC_ENTRY
{
void* contextBuffer;
UINT32 allocatorIndex;
};
typedef struct _CONTEXT_BUFFER_ALLOC_ENTRY CONTEXT_BUFFER_ALLOC_ENTRY;
struct _CONTEXT_BUFFER_ALLOC_TABLE
{
UINT32 cEntries;
UINT32 cMaxEntries;
CONTEXT_BUFFER_ALLOC_ENTRY* entries;
};
typedef struct _CONTEXT_BUFFER_ALLOC_TABLE CONTEXT_BUFFER_ALLOC_TABLE;
CONTEXT_BUFFER_ALLOC_TABLE ContextBufferAllocTable;
int sspi_ContextBufferAllocTableNew()
{
size_t size;
ContextBufferAllocTable.entries = NULL;
ContextBufferAllocTable.cEntries = 0;
ContextBufferAllocTable.cMaxEntries = 4;
size = sizeof(CONTEXT_BUFFER_ALLOC_ENTRY) * ContextBufferAllocTable.cMaxEntries;
ContextBufferAllocTable.entries = (CONTEXT_BUFFER_ALLOC_ENTRY*) calloc(1, size);
if (!ContextBufferAllocTable.entries)
return -1;
return 1;
}
int sspi_ContextBufferAllocTableGrow()
{
size_t size;
CONTEXT_BUFFER_ALLOC_ENTRY* entries;
ContextBufferAllocTable.cEntries = 0;
ContextBufferAllocTable.cMaxEntries *= 2;
size = sizeof(CONTEXT_BUFFER_ALLOC_ENTRY) * ContextBufferAllocTable.cMaxEntries;
if (!size)
return -1;
entries = (CONTEXT_BUFFER_ALLOC_ENTRY*) realloc(ContextBufferAllocTable.entries, size);
if (!entries)
{
free(ContextBufferAllocTable.entries);
return -1;
}
ContextBufferAllocTable.entries = entries;
ZeroMemory((void*) &ContextBufferAllocTable.entries[ContextBufferAllocTable.cMaxEntries / 2], size / 2);
return 1;
}
void sspi_ContextBufferAllocTableFree()
{
ContextBufferAllocTable.cEntries = ContextBufferAllocTable.cMaxEntries = 0;
free(ContextBufferAllocTable.entries);
}
void* sspi_ContextBufferAlloc(UINT32 allocatorIndex, size_t size)
{
int index;
void* contextBuffer;
for (index = 0; index < (int) ContextBufferAllocTable.cMaxEntries; index++)
{
if (!ContextBufferAllocTable.entries[index].contextBuffer)
{
contextBuffer = calloc(1, size);
if (!contextBuffer)
return NULL;
ContextBufferAllocTable.cEntries++;
ContextBufferAllocTable.entries[index].contextBuffer = contextBuffer;
ContextBufferAllocTable.entries[index].allocatorIndex = allocatorIndex;
return ContextBufferAllocTable.entries[index].contextBuffer;
}
}
/* no available entry was found, the table needs to be grown */
if (sspi_ContextBufferAllocTableGrow() < 0)
return NULL;
/* the next call to sspi_ContextBufferAlloc() should now succeed */
return sspi_ContextBufferAlloc(allocatorIndex, size);
}
SSPI_CREDENTIALS* sspi_CredentialsNew()
{
SSPI_CREDENTIALS* credentials;
credentials = (SSPI_CREDENTIALS*) calloc(1, sizeof(SSPI_CREDENTIALS));
return credentials;
}
void sspi_CredentialsFree(SSPI_CREDENTIALS* credentials)
{
size_t userLength;
size_t domainLength;
size_t passwordLength;
if (!credentials)
return;
userLength = credentials->identity.UserLength;
domainLength = credentials->identity.DomainLength;
passwordLength = credentials->identity.PasswordLength;
if (credentials->identity.Flags & SEC_WINNT_AUTH_IDENTITY_UNICODE)
{
userLength *= 2;
domainLength *= 2;
passwordLength *= 2;
}
memset(credentials->identity.User, 0, userLength);
memset(credentials->identity.Domain, 0, domainLength);
memset(credentials->identity.Password, 0, passwordLength);
free(credentials->identity.User);
free(credentials->identity.Domain);
free(credentials->identity.Password);
free(credentials);
}
void* sspi_SecBufferAlloc(PSecBuffer SecBuffer, ULONG size)
{
if (!SecBuffer)
return NULL;
SecBuffer->pvBuffer = calloc(1, size);
if (!SecBuffer->pvBuffer)
return NULL;
SecBuffer->cbBuffer = size;
return SecBuffer->pvBuffer;
}
void sspi_SecBufferFree(PSecBuffer SecBuffer)
{
if (!SecBuffer)
return;
memset(SecBuffer->pvBuffer, 0, SecBuffer->cbBuffer);
free(SecBuffer->pvBuffer);
SecBuffer->pvBuffer = NULL;
SecBuffer->cbBuffer = 0;
}
SecHandle* sspi_SecureHandleAlloc()
{
SecHandle* handle = (SecHandle*) calloc(1, sizeof(SecHandle));
if (!handle)
return NULL;
SecInvalidateHandle(handle);
return handle;
}
void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle) || !handle->dwLower)
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
void sspi_SecureHandleSetLowerPointer(SecHandle* handle, void* pointer)
{
if (!handle)
return;
handle->dwLower = (ULONG_PTR) (~((size_t) pointer));
}
void* sspi_SecureHandleGetUpperPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle) || !handle->dwUpper)
return NULL;
pointer = (void*) ~((size_t) handle->dwUpper);
return pointer;
}
void sspi_SecureHandleSetUpperPointer(SecHandle* handle, void* pointer)
{
if (!handle)
return;
handle->dwUpper = (ULONG_PTR) (~((size_t) pointer));
}
void sspi_SecureHandleFree(SecHandle* handle)
{
free(handle);
}
int sspi_SetAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity, const char* user, const char* domain, const char* password)
{
int status;
identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
free(identity->User);
identity->User = (UINT16*) NULL;
identity->UserLength = 0;
if (user)
{
status = ConvertToUnicode(CP_UTF8, 0, user, -1, (LPWSTR*) &(identity->User), 0);
if (status <= 0)
return -1;
identity->UserLength = (ULONG) (status - 1);
}
free(identity->Domain);
identity->Domain = (UINT16*) NULL;
identity->DomainLength = 0;
if (domain)
{
status = ConvertToUnicode(CP_UTF8, 0, domain, -1, (LPWSTR*) &(identity->Domain), 0);
if (status <= 0)
return -1;
identity->DomainLength = (ULONG) (status - 1);
}
free(identity->Password);
identity->Password = NULL;
identity->PasswordLength = 0;
if (password)
{
status = ConvertToUnicode(CP_UTF8, 0, password, -1, (LPWSTR*) &(identity->Password), 0);
if (status <= 0)
return -1;
identity->PasswordLength = (ULONG) (status - 1);
}
return 1;
}
int sspi_CopyAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity, SEC_WINNT_AUTH_IDENTITY* srcIdentity)
{
int status;
if (srcIdentity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
{
status = sspi_SetAuthIdentity(identity, (char*) srcIdentity->User,
(char*) srcIdentity->Domain, (char*) srcIdentity->Password);
if (status <= 0)
return -1;
identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
return 1;
}
identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
identity->User = identity->Domain = identity->Password = NULL;
identity->UserLength = srcIdentity->UserLength;
if (identity->UserLength > 0)
{
identity->User = (UINT16*) malloc((identity->UserLength + 1) * sizeof(WCHAR));
if (!identity->User)
return -1;
CopyMemory(identity->User, srcIdentity->User, identity->UserLength * sizeof(WCHAR));
identity->User[identity->UserLength] = 0;
}
identity->DomainLength = srcIdentity->DomainLength;
if (identity->DomainLength > 0)
{
identity->Domain = (UINT16*) malloc((identity->DomainLength + 1) * sizeof(WCHAR));
if (!identity->Domain)
return -1;
CopyMemory(identity->Domain, srcIdentity->Domain, identity->DomainLength * sizeof(WCHAR));
identity->Domain[identity->DomainLength] = 0;
}
identity->PasswordLength = srcIdentity->PasswordLength;
if (identity->PasswordLength > 256)
identity->PasswordLength /= SSPI_CREDENTIALS_HASH_LENGTH_FACTOR;
if (identity->PasswordLength > 0)
{
identity->Password = (UINT16*) malloc((identity->PasswordLength + 1) * sizeof(WCHAR));
if (!identity->Password)
return -1;
CopyMemory(identity->Password, srcIdentity->Password, identity->PasswordLength * sizeof(WCHAR));
identity->Password[identity->PasswordLength] = 0;
}
identity->PasswordLength = srcIdentity->PasswordLength;
return 1;
}
PSecBuffer sspi_FindSecBuffer(PSecBufferDesc pMessage, ULONG BufferType)
{
ULONG index;
PSecBuffer pSecBuffer = NULL;
for (index = 0; index < pMessage->cBuffers; index++)
{
if (pMessage->pBuffers[index].BufferType == BufferType)
{
pSecBuffer = &pMessage->pBuffers[index];
break;
}
}
return pSecBuffer;
}
static BOOL sspi_initialized = FALSE;
void sspi_GlobalInit()
{
if (!sspi_initialized)
{
winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT);
sspi_ContextBufferAllocTableNew();
sspi_initialized = TRUE;
}
}
void sspi_GlobalFinish()
{
if (sspi_initialized)
{
sspi_ContextBufferAllocTableFree();
}
sspi_initialized = FALSE;
}
SecurityFunctionTableA* sspi_GetSecurityFunctionTableAByNameA(const SEC_CHAR* Name)
{
int index;
UINT32 cPackages;
cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST));
for (index = 0; index < (int) cPackages; index++)
{
if (strcmp(Name, SecurityFunctionTableA_NAME_LIST[index].Name) == 0)
{
return (SecurityFunctionTableA*) SecurityFunctionTableA_NAME_LIST[index].SecurityFunctionTable;
}
}
return NULL;
}
SecurityFunctionTableA* sspi_GetSecurityFunctionTableAByNameW(const SEC_WCHAR* Name)
{
return NULL;
}
SecurityFunctionTableW* sspi_GetSecurityFunctionTableWByNameW(const SEC_WCHAR* Name)
{
int index;
UINT32 cPackages;
cPackages = sizeof(SecPkgInfoW_LIST) / sizeof(*(SecPkgInfoW_LIST));
for (index = 0; index < (int) cPackages; index++)
{
if (lstrcmpW(Name, SecurityFunctionTableW_NAME_LIST[index].Name) == 0)
{
return (SecurityFunctionTableW*) SecurityFunctionTableW_NAME_LIST[index].SecurityFunctionTable;
}
}
return NULL;
}
SecurityFunctionTableW* sspi_GetSecurityFunctionTableWByNameA(const SEC_CHAR* Name)
{
int status;
SEC_WCHAR* NameW = NULL;
SecurityFunctionTableW* table;
status = ConvertToUnicode(CP_UTF8, 0, Name, -1, &NameW, 0);
if (status <= 0)
return NULL;
table = sspi_GetSecurityFunctionTableWByNameW(NameW);
free(NameW);
return table;
}
void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer);
void FreeContextBuffer_QuerySecurityPackageInfo(void* contextBuffer);
void sspi_ContextBufferFree(void* contextBuffer)
{
int index;
UINT32 allocatorIndex;
for (index = 0; index < (int) ContextBufferAllocTable.cMaxEntries; index++)
{
if (contextBuffer == ContextBufferAllocTable.entries[index].contextBuffer)
{
contextBuffer = ContextBufferAllocTable.entries[index].contextBuffer;
allocatorIndex = ContextBufferAllocTable.entries[index].allocatorIndex;
ContextBufferAllocTable.cEntries--;
ContextBufferAllocTable.entries[index].allocatorIndex = 0;
ContextBufferAllocTable.entries[index].contextBuffer = NULL;
switch (allocatorIndex)
{
case EnumerateSecurityPackagesIndex:
FreeContextBuffer_EnumerateSecurityPackages(contextBuffer);
break;
case QuerySecurityPackageInfoIndex:
FreeContextBuffer_QuerySecurityPackageInfo(contextBuffer);
break;
}
}
}
}
/**
* Standard SSPI API
*/
/* Package Management */
SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesW(ULONG* pcPackages, PSecPkgInfoW* ppPackageInfo)
{
int index;
size_t size;
UINT32 cPackages;
SecPkgInfoW* pPackageInfo;
cPackages = sizeof(SecPkgInfoW_LIST) / sizeof(*(SecPkgInfoW_LIST));
size = sizeof(SecPkgInfoW) * cPackages;
pPackageInfo = (SecPkgInfoW*) sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size);
if (!pPackageInfo)
return SEC_E_INSUFFICIENT_MEMORY;
for (index = 0; index < (int) cPackages; index++)
{
pPackageInfo[index].fCapabilities = SecPkgInfoW_LIST[index]->fCapabilities;
pPackageInfo[index].wVersion = SecPkgInfoW_LIST[index]->wVersion;
pPackageInfo[index].wRPCID = SecPkgInfoW_LIST[index]->wRPCID;
pPackageInfo[index].cbMaxToken = SecPkgInfoW_LIST[index]->cbMaxToken;
pPackageInfo[index].Name = _wcsdup(SecPkgInfoW_LIST[index]->Name);
pPackageInfo[index].Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment);
}
*(pcPackages) = cPackages;
*(ppPackageInfo) = pPackageInfo;
return SEC_E_OK;
}
SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesA(ULONG* pcPackages, PSecPkgInfoA* ppPackageInfo)
{
int index;
size_t size;
UINT32 cPackages;
SecPkgInfoA* pPackageInfo;
cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST));
size = sizeof(SecPkgInfoA) * cPackages;
pPackageInfo = (SecPkgInfoA*) sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size);
if (!pPackageInfo)
return SEC_E_INSUFFICIENT_MEMORY;
for (index = 0; index < (int) cPackages; index++)
{
pPackageInfo[index].fCapabilities = SecPkgInfoA_LIST[index]->fCapabilities;
pPackageInfo[index].wVersion = SecPkgInfoA_LIST[index]->wVersion;
pPackageInfo[index].wRPCID = SecPkgInfoA_LIST[index]->wRPCID;
pPackageInfo[index].cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken;
pPackageInfo[index].Name = _strdup(SecPkgInfoA_LIST[index]->Name);
pPackageInfo[index].Comment = _strdup(SecPkgInfoA_LIST[index]->Comment);
if (!pPackageInfo[index].Name || !pPackageInfo[index].Comment)
{
sspi_ContextBufferFree(pPackageInfo);
return SEC_E_INSUFFICIENT_MEMORY;
}
}
*(pcPackages) = cPackages;
*(ppPackageInfo) = pPackageInfo;
return SEC_E_OK;
}
void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer)
{
int index;
UINT32 cPackages;
SecPkgInfoA* pPackageInfo = (SecPkgInfoA*) contextBuffer;
cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST));
for (index = 0; index < (int) cPackages; index++)
{
free(pPackageInfo[index].Name);
free(pPackageInfo[index].Comment);
}
free(pPackageInfo);
}
SecurityFunctionTableW* SEC_ENTRY winpr_InitSecurityInterfaceW(void)
{
return &winpr_SecurityFunctionTableW;
}
SecurityFunctionTableA* SEC_ENTRY winpr_InitSecurityInterfaceA(void)
{
return &winpr_SecurityFunctionTableA;
}
SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoW(SEC_WCHAR* pszPackageName, PSecPkgInfoW* ppPackageInfo)
{
int index;
size_t size;
UINT32 cPackages;
SecPkgInfoW* pPackageInfo;
cPackages = sizeof(SecPkgInfoW_LIST) / sizeof(*(SecPkgInfoW_LIST));
for (index = 0; index < (int) cPackages; index++)
{
if (lstrcmpW(pszPackageName, SecPkgInfoW_LIST[index]->Name) == 0)
{
size = sizeof(SecPkgInfoW);
pPackageInfo = (SecPkgInfoW*) sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size);
if (!pPackageInfo)
return SEC_E_INSUFFICIENT_MEMORY;
pPackageInfo->fCapabilities = SecPkgInfoW_LIST[index]->fCapabilities;
pPackageInfo->wVersion = SecPkgInfoW_LIST[index]->wVersion;
pPackageInfo->wRPCID = SecPkgInfoW_LIST[index]->wRPCID;
pPackageInfo->cbMaxToken = SecPkgInfoW_LIST[index]->cbMaxToken;
pPackageInfo->Name = _wcsdup(SecPkgInfoW_LIST[index]->Name);
pPackageInfo->Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment);
*(ppPackageInfo) = pPackageInfo;
return SEC_E_OK;
}
}
*(ppPackageInfo) = NULL;
return SEC_E_SECPKG_NOT_FOUND;
}
SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoA(SEC_CHAR* pszPackageName, PSecPkgInfoA* ppPackageInfo)
{
int index;
size_t size;
UINT32 cPackages;
SecPkgInfoA* pPackageInfo;
cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST));
for (index = 0; index < (int) cPackages; index++)
{
if (strcmp(pszPackageName, SecPkgInfoA_LIST[index]->Name) == 0)
{
size = sizeof(SecPkgInfoA);
pPackageInfo = (SecPkgInfoA*) sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size);
if (!pPackageInfo)
return SEC_E_INSUFFICIENT_MEMORY;
pPackageInfo->fCapabilities = SecPkgInfoA_LIST[index]->fCapabilities;
pPackageInfo->wVersion = SecPkgInfoA_LIST[index]->wVersion;
pPackageInfo->wRPCID = SecPkgInfoA_LIST[index]->wRPCID;
pPackageInfo->cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken;
pPackageInfo->Name = _strdup(SecPkgInfoA_LIST[index]->Name);
pPackageInfo->Comment = _strdup(SecPkgInfoA_LIST[index]->Comment);
if (!pPackageInfo->Name || !pPackageInfo->Comment)
{
sspi_ContextBufferFree(pPackageInfo);
return SEC_E_INSUFFICIENT_MEMORY;
}
*(ppPackageInfo) = pPackageInfo;
return SEC_E_OK;
}
}
*(ppPackageInfo) = NULL;
return SEC_E_SECPKG_NOT_FOUND;
}
void FreeContextBuffer_QuerySecurityPackageInfo(void* contextBuffer)
{
SecPkgInfo* pPackageInfo = (SecPkgInfo*) contextBuffer;
if (!pPackageInfo)
return;
free(pPackageInfo->Name);
free(pPackageInfo->Comment);
free(pPackageInfo);
}
/* Credential Management */
SECURITY_STATUS SEC_ENTRY winpr_AcquireCredentialsHandleW(SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage,
ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn,
void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
{
SECURITY_STATUS status;
SecurityFunctionTableW* table = sspi_GetSecurityFunctionTableWByNameW(pszPackage);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->AcquireCredentialsHandleW)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->AcquireCredentialsHandleW(pszPrincipal, pszPackage, fCredentialUse,
pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "AcquireCredentialsHandleW status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_AcquireCredentialsHandleA(SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage,
ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn,
void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
{
SECURITY_STATUS status;
SecurityFunctionTableA* table = sspi_GetSecurityFunctionTableAByNameA(pszPackage);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->AcquireCredentialsHandleA)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse,
pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "AcquireCredentialsHandleA status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_ExportSecurityContext(PCtxtHandle phContext, ULONG fFlags, PSecBuffer pPackedContext, HANDLE* pToken)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->ExportSecurityContext)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->ExportSecurityContext(phContext, fFlags, pPackedContext, pToken);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "ExportSecurityContext status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_FreeCredentialsHandle(PCredHandle phCredential)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phCredential);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->FreeCredentialsHandle)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->FreeCredentialsHandle(phCredential);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "FreeCredentialsHandle status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_ImportSecurityContextW(SEC_WCHAR* pszPackage, PSecBuffer pPackedContext, HANDLE pToken, PCtxtHandle phContext)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->ImportSecurityContextW)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->ImportSecurityContextW(pszPackage, pPackedContext, pToken, phContext);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "ImportSecurityContextW status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_ImportSecurityContextA(SEC_CHAR* pszPackage, PSecBuffer pPackedContext, HANDLE pToken, PCtxtHandle phContext)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->ImportSecurityContextA)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->ImportSecurityContextA(pszPackage, pPackedContext, pToken, phContext);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "ImportSecurityContextA status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_QueryCredentialsAttributesW(PCredHandle phCredential, ULONG ulAttribute, void* pBuffer)
{
SEC_WCHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_WCHAR*) sspi_SecureHandleGetUpperPointer(phCredential);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameW(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->QueryCredentialsAttributesW)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "QueryCredentialsAttributesW status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_QueryCredentialsAttributesA(PCredHandle phCredential, ULONG ulAttribute, void* pBuffer)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phCredential);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->QueryCredentialsAttributesA)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->QueryCredentialsAttributesA(phCredential, ulAttribute, pBuffer);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "QueryCredentialsAttributesA status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
/* Context Management */
SECURITY_STATUS SEC_ENTRY winpr_AcceptSecurityContext(PCredHandle phCredential, PCtxtHandle phContext,
PSecBufferDesc pInput, ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext,
PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phCredential);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->AcceptSecurityContext)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->AcceptSecurityContext(phCredential, phContext, pInput, fContextReq,
TargetDataRep, phNewContext, pOutput, pfContextAttr, ptsTimeStamp);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "AcceptSecurityContext status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_ApplyControlToken(PCtxtHandle phContext, PSecBufferDesc pInput)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->ApplyControlToken)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->ApplyControlToken(phContext, pInput);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "ApplyControlToken status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_CompleteAuthToken(PCtxtHandle phContext, PSecBufferDesc pToken)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->CompleteAuthToken)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->CompleteAuthToken(phContext, pToken);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "CompleteAuthToken status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->DeleteSecurityContext)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "DeleteSecurityContext status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_FreeContextBuffer(void* pvContextBuffer)
{
if (!pvContextBuffer)
return SEC_E_INVALID_HANDLE;
sspi_ContextBufferFree(pvContextBuffer);
return SEC_E_OK;
}
SECURITY_STATUS SEC_ENTRY winpr_ImpersonateSecurityContext(PCtxtHandle phContext)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->ImpersonateSecurityContext)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->ImpersonateSecurityContext(phContext);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "ImpersonateSecurityContext status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_InitializeSecurityContextW(PCredHandle phCredential, PCtxtHandle phContext,
SEC_WCHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phCredential);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->InitializeSecurityContextW)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->InitializeSecurityContextW(phCredential, phContext,
pszTargetName, fContextReq, Reserved1, TargetDataRep,
pInput, Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "InitializeSecurityContextW status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_InitializeSecurityContextA(PCredHandle phCredential, PCtxtHandle phContext,
SEC_CHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phCredential);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->InitializeSecurityContextA)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->InitializeSecurityContextA(phCredential, phContext,
pszTargetName, fContextReq, Reserved1, TargetDataRep,
pInput, Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "InitializeSecurityContextA status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_QueryContextAttributesW(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->QueryContextAttributesW)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->QueryContextAttributesW(phContext, ulAttribute, pBuffer);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "QueryContextAttributesW status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_QueryContextAttributesA(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->QueryContextAttributesA)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->QueryContextAttributesA(phContext, ulAttribute, pBuffer);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "QueryContextAttributesA status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityContextToken(PCtxtHandle phContext, HANDLE* phToken)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->QuerySecurityContextToken)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->QuerySecurityContextToken(phContext, phToken);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "QuerySecurityContextToken status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_SetContextAttributesW(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer, ULONG cbBuffer)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->SetContextAttributesW)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "SetContextAttributesW status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_SetContextAttributesA(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer, ULONG cbBuffer)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->SetContextAttributesA)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->SetContextAttributesA(phContext, ulAttribute, pBuffer, cbBuffer);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "SetContextAttributesA status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_RevertSecurityContext(PCtxtHandle phContext)
{
SEC_CHAR* Name;
SECURITY_STATUS status;
SecurityFunctionTableW* table;
Name = (SEC_CHAR*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableWByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->RevertSecurityContext)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->RevertSecurityContext(phContext);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "RevertSecurityContext status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
/* Message Support */
SECURITY_STATUS SEC_ENTRY winpr_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->DecryptMessage)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DecryptMessage(phContext, pMessage, MessageSeqNo, pfQOP);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "DecryptMessage status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->EncryptMessage)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->EncryptMessage(phContext, fQOP, pMessage, MessageSeqNo);
if (status != SEC_E_OK)
{
WLog_ERR(TAG, "EncryptMessage status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_MakeSignature(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->MakeSignature)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->MakeSignature(phContext, fQOP, pMessage, MessageSeqNo);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "MakeSignature status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SECURITY_STATUS SEC_ENTRY winpr_VerifySignature(PCtxtHandle phContext, PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (!table->VerifySignature)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
if (IsSecurityStatusError(status))
{
WLog_WARN(TAG, "VerifySignature status %s [%08X]",
GetSecurityStatusString(status), status);
}
return status;
}
SecurityFunctionTableA winpr_SecurityFunctionTableA =
{
1, /* dwVersion */
winpr_EnumerateSecurityPackagesA, /* EnumerateSecurityPackages */
winpr_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */
winpr_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */
winpr_FreeCredentialsHandle, /* FreeCredentialsHandle */
NULL, /* Reserved2 */
winpr_InitializeSecurityContextA, /* InitializeSecurityContext */
winpr_AcceptSecurityContext, /* AcceptSecurityContext */
winpr_CompleteAuthToken, /* CompleteAuthToken */
winpr_DeleteSecurityContext, /* DeleteSecurityContext */
winpr_ApplyControlToken, /* ApplyControlToken */
winpr_QueryContextAttributesA, /* QueryContextAttributes */
winpr_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
winpr_RevertSecurityContext, /* RevertSecurityContext */
winpr_MakeSignature, /* MakeSignature */
winpr_VerifySignature, /* VerifySignature */
winpr_FreeContextBuffer, /* FreeContextBuffer */
winpr_QuerySecurityPackageInfoA, /* QuerySecurityPackageInfo */
NULL, /* Reserved3 */
NULL, /* Reserved4 */
winpr_ExportSecurityContext, /* ExportSecurityContext */
winpr_ImportSecurityContextA, /* ImportSecurityContext */
NULL, /* AddCredentials */
NULL, /* Reserved8 */
winpr_QuerySecurityContextToken, /* QuerySecurityContextToken */
winpr_EncryptMessage, /* EncryptMessage */
winpr_DecryptMessage, /* DecryptMessage */
winpr_SetContextAttributesA, /* SetContextAttributes */
};
SecurityFunctionTableW winpr_SecurityFunctionTableW =
{
1, /* dwVersion */
winpr_EnumerateSecurityPackagesW, /* EnumerateSecurityPackages */
winpr_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */
winpr_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */
winpr_FreeCredentialsHandle, /* FreeCredentialsHandle */
NULL, /* Reserved2 */
winpr_InitializeSecurityContextW, /* InitializeSecurityContext */
winpr_AcceptSecurityContext, /* AcceptSecurityContext */
winpr_CompleteAuthToken, /* CompleteAuthToken */
winpr_DeleteSecurityContext, /* DeleteSecurityContext */
winpr_ApplyControlToken, /* ApplyControlToken */
winpr_QueryContextAttributesW, /* QueryContextAttributes */
winpr_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
winpr_RevertSecurityContext, /* RevertSecurityContext */
winpr_MakeSignature, /* MakeSignature */
winpr_VerifySignature, /* VerifySignature */
winpr_FreeContextBuffer, /* FreeContextBuffer */
winpr_QuerySecurityPackageInfoW, /* QuerySecurityPackageInfo */
NULL, /* Reserved3 */
NULL, /* Reserved4 */
winpr_ExportSecurityContext, /* ExportSecurityContext */
winpr_ImportSecurityContextW, /* ImportSecurityContext */
NULL, /* AddCredentials */
NULL, /* Reserved8 */
winpr_QuerySecurityContextToken, /* QuerySecurityContextToken */
winpr_EncryptMessage, /* EncryptMessage */
winpr_DecryptMessage, /* DecryptMessage */
winpr_SetContextAttributesW, /* SetContextAttributes */
};
| ssieb/FreeRDP | winpr/libwinpr/sspi/sspi_winpr.c | C | apache-2.0 | 42,196 |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Canopy Interpreter Provider")]
[assembly: AssemblyDescription("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("48C77E5C-EC45-4506-B32F-CBF772BB7066")]
| ChinaQuants/PTVS | Python/Product/CanopyInterpreter/AssemblyInfo.Internal.cs | C# | apache-2.0 | 1,512 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for Grappler LayoutOptimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import device_properties_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.core.protobuf import saver_pb2
from tensorflow.python.client import session
from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
from tensorflow.python.grappler import cluster as gcluster
from tensorflow.python.grappler import tf_optimizer
from tensorflow.python.layers import convolutional as conv_layers
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import map_fn
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import saver as saver_lib
def _weight(shape):
"""Generates a weight of a given shape."""
return random_ops.truncated_normal(shape, seed=0, stddev=0.1)
def _bias(shape):
"""Generates a bias of a given shape."""
return constant_op.constant(0.1, shape=shape)
def _conv2d(x, w):
"""Returns a 2d convolution layer with full stride."""
return nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
def _max_pool_2x2(x):
"""Downsamples a feature map by 2X."""
return nn.max_pool(
x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# Taken from tensorflow/examples/tutorials/mnist/mnist_deep.py
def _two_layer_model(x):
x_image = array_ops.reshape(x, [-1, 28, 28, 1])
w_conv1 = _weight([5, 5, 1, 32])
b_conv1 = _bias([32])
h_conv1 = nn.relu(_conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = _max_pool_2x2(h_conv1)
w_conv2 = _weight([5, 5, 32, 64])
b_conv2 = _bias([64])
h_conv2 = nn.relu(_conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = _max_pool_2x2(h_conv2)
return h_pool2
def _model_with_second_port():
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([2, 5, 5, 4], seed=0)
scale = constant_op.constant(0.1, shape=[4])
offset = constant_op.constant(0.3, shape=[4])
y, mean, _ = nn.fused_batch_norm(x, scale, offset)
mul = math_ops.add(y, mean)
output = array_ops.identity(mul)
return output
def _model_with_branch(x):
x_image = array_ops.reshape(x, [-1, 28, 28, 1])
w_conv1 = _weight([5, 5, 1, 32])
w_conv2 = _weight([5, 5, 1, 32])
c_conv1 = _conv2d(x_image, w_conv1)
c_conv2 = _conv2d(x_image, w_conv2)
add = math_ops.add(c_conv1, c_conv2)
return add
def _model_with_vec_and_4d(x):
x_image = array_ops.reshape(x, [-1, 28, 28, 1])
w_conv1 = _weight([5, 5, 1, 32])
c_conv1 = _conv2d(x_image, w_conv1)
vector = constant_op.constant(6.4, shape=[32])
add = math_ops.add(c_conv1, vector)
return add
def _loop():
random_seed.set_random_seed(0)
x1 = random_ops.truncated_normal([1, 784], seed=0)
x2 = random_ops.truncated_normal([1, 784], seed=0)
x3 = random_ops.truncated_normal([1, 784], seed=0)
x4 = random_ops.truncated_normal([1, 784], seed=0)
elems = (x1, x2, x3, x4)
outputs = map_fn.map_fn(_two_layer_model, elems, dtype=dtypes.float32)
return outputs
def _loop_with_branch():
random_seed.set_random_seed(0)
x1 = random_ops.truncated_normal([1, 784], seed=0)
x2 = random_ops.truncated_normal([1, 784], seed=0)
x3 = random_ops.truncated_normal([1, 784], seed=0)
x4 = random_ops.truncated_normal([1, 784], seed=0)
elems = (x1, x2, x3, x4)
outputs = map_fn.map_fn(_model_with_branch, elems, dtype=dtypes.float32)
return outputs
def _loop_with_vec_and_4d():
random_seed.set_random_seed(0)
x1 = random_ops.truncated_normal([1, 784], seed=0)
x2 = random_ops.truncated_normal([1, 784], seed=0)
x3 = random_ops.truncated_normal([1, 784], seed=0)
x4 = random_ops.truncated_normal([1, 784], seed=0)
elems = (x1, x2, x3, x4)
outputs = map_fn.map_fn(_model_with_vec_and_4d, elems, dtype=dtypes.float32)
return outputs
def _get_config(layout_optimizer=True):
if layout_optimizer:
rewrite_options = rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.ON,
# do not remove duplicated nodes
arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF)
else:
rewrite_options = rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.OFF,
# do not remove duplicated nodes
arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF)
rewrite_options.min_graph_nodes = -1
graph_options = config_pb2.GraphOptions(
rewrite_options=rewrite_options, build_cost_model=1)
config = config_pb2.ConfigProto(graph_options=graph_options)
config.graph_options.optimizer_options.opt_level = -1
return config
def _simple_metagraph(depthwise=False):
random_seed.set_random_seed(0)
x = variables.Variable(random_ops.truncated_normal([1, 200, 200, 3], seed=0))
conv = conv_layers.separable_conv2d if depthwise else conv_layers.conv2d
y = conv(x, 32, [3, 3])
z = conv(y, 32, [3, 3])
optimizer = gradient_descent.GradientDescentOptimizer(1e-4)
loss = math_ops.reduce_mean(z)
train_op = optimizer.minimize(loss)
graph = ops.get_default_graph()
graph.add_to_collection('train_op', train_op)
meta_graph = saver_lib.export_meta_graph(graph_def=graph.as_graph_def())
return meta_graph
def _get_cluster():
named_device = device_properties_pb2.NamedDevice()
named_device.name = '/GPU:0'
named_device.properties.type = 'GPU'
named_device.properties.num_cores = 24
named_device.properties.frequency = 1000
named_device.properties.environment['architecture'] = '4'
cluster = gcluster.Cluster(devices=[named_device])
return cluster
def _is_transpose(node):
return node.endswith('TransposeNHWCToNCHW-LayoutOptimizer') or node.endswith(
'TransposeNCHWToNHWC-LayoutOptimizer')
def _is_permute(node):
return node.endswith('VecPermuteNHWCToNCHW-LayoutOptimizer') or node.endswith(
'VecPermuteNCHWToNHWC-LayoutOptimizer')
@test_util.for_all_test_methods(test_util.no_xla_auto_jit,
'Test does not apply in XLA setting')
class LayoutOptimizerTest(test.TestCase):
"""Tests the Grappler layout optimizer."""
def _assert_trans_nchw_to_nhwc(self, name, nodes):
self.assertIn(name + '-TransposeNCHWToNHWC-LayoutOptimizer', nodes)
def _assert_trans_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-TransposeNHWCToNCHW-LayoutOptimizer', nodes)
def _assert_map_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-DimMapNHWCToNCHW-LayoutOptimizer', nodes)
def _assert_vec_nchw_to_nhwc(self, name, nodes):
self.assertIn(name + '-VecPermuteNCHWToNHWC-LayoutOptimizer', nodes)
def _assert_vec_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-VecPermuteNHWCToNCHW-LayoutOptimizer', nodes)
def _train(self, checkpoint_path, layout_optimizer=False, restore=False):
ops.reset_default_graph()
graph = ops.get_default_graph()
with session.Session(
config=_get_config(layout_optimizer), graph=graph) as sess:
batch = 2
height = 6
width = 7
input_channels = 3
shape = [batch, height, width, input_channels]
image = array_ops.placeholder(dtype='float32', shape=shape)
conv1 = conv_layers.conv2d(image, 32, [3, 3])
conv2 = conv_layers.conv2d(conv1, 32, [3, 3])
optimizer = gradient_descent.GradientDescentOptimizer(0.01)
loss = math_ops.reduce_mean(conv2)
train_op = optimizer.minimize(loss)
saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2)
if restore:
saver.restore(sess, checkpoint_path)
else:
self.evaluate(variables.global_variables_initializer())
np.random.seed(0)
for _ in range(2):
image_val = np.random.rand(*shape).astype(np.float32)
sess.run([loss, train_op], feed_dict={image: image_val})
if restore:
all_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
all_vars_values = [var.eval(session=sess) for var in all_vars]
return all_vars_values
else:
saver.save(sess, checkpoint_path)
@test_util.deprecated_graph_mode_only
def testTwoConvLayers(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
output = _two_layer_model(x)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Relu_1-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSplitWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dim = array_ops.placeholder(dtype='int32')
split = array_ops.split(conv, 2, axis=dim)
scale = constant_op.constant(0.1, shape=[32])
offset = constant_op.constant(0.3, shape=[32])
bn0 = nn.fused_batch_norm(split[0], scale, offset)
bn1 = nn.fused_batch_norm(split[1], scale, offset)
add = bn0[0] + bn1[0]
output = array_ops.identity(add)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={dim: 3})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata, feed_dict={dim: 3})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('add_2-0-0', nodes)
self._assert_map_nhwc_to_nchw('split-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSplitVWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dim = array_ops.placeholder(dtype='int32')
sizes = constant_op.constant([50, 10, 4], shape=[3])
split = gen_array_ops.split_v(
value=conv, size_splits=sizes, axis=dim, num_split=3)
output = math_ops.reduce_sum(split[0])
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={dim: 3})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata, feed_dict={dim: 3})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('SplitV-0-0', nodes)
self._assert_map_nhwc_to_nchw('SplitV-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testPadWithConstPaddings(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
paddings_val = [[1, 2], [3, 4], [5, 6], [7, 8]]
paddings = constant_op.constant(
paddings_val, dtype='int32', name='PaddingsConst')
pad = array_ops.pad(conv, paddings)
output = array_ops.identity(pad)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Pad-0-0', nodes)
self.assertIn('Pad-1-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSum(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testCast(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
cast = math_ops.cast(conv, dtype='bool')
output = array_ops.identity(cast)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Cast-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSqueeze(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[1, 2])
squeeze = array_ops.squeeze(reduce_sum)
output = array_ops.identity(squeeze)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSqueezeAlongHW(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[1, 2], keepdims=True)
squeeze = array_ops.squeeze(reduce_sum, axis=[1, 2])
output = array_ops.identity(squeeze)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSqueezeAlongNHW(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[0, 1, 2], keepdims=True)
squeeze = array_ops.squeeze(reduce_sum, axis=[0, 1, 2])
output = array_ops.identity(squeeze)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongHWC(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[1, 2, 3])
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongNHW(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[0, 1, 2])
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongC(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[3])
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongCKeepDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[3], keepdims=True)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Sum-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongHKeepDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[2], keepdims=True)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongWCKeepDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[2, 3], keepdims=True)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testConcatWithControlDependency(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
axis = constant_op.constant(3)
var = variables.Variable(3)
assign = state_ops.assign(var, 6)
with ops.control_dependencies([assign]):
concat = array_ops.concat([conv, conv], axis)
output = array_ops.identity(concat)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('concat-0-0', nodes)
self.assertIn('concat-2-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testFill(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = array_ops.placeholder(dtype='float32')
conv = _two_layer_model(x)
shape = array_ops.shape(conv)
scalar = array_ops.constant(5.7)
fill = array_ops.fill(shape, scalar)
output = array_ops.identity(fill)
x_val = [3.4] * 784
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={x: x_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
x: x_val
})
nodes = []
num_transposes = 0
num_vec_permute = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
if _is_permute(node.name):
num_vec_permute += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
# Two vector permute nodes were initially added in the Expand phase of
# LayoutOptimizer; they cancelled out each other in the Collapse phase.
expected_vec_permute = 0
self.assertEqual(expected_vec_permute, num_vec_permute)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Fill-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testTile(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
multiple = array_ops.placeholder(dtype='int32')
tile = array_ops.tile(conv, multiple)
output = array_ops.identity(tile)
multiple_val = [2, 3, 4, 1]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={multiple: multiple_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
multiple: multiple_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Tile-0-0', nodes)
self._assert_vec_nhwc_to_nchw('Tile-1', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReverseWithConstDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dims = constant_op.constant([3, 1], name='DimsConst')
reverse = array_ops.reverse(conv, dims)
output = array_ops.identity(reverse)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('ReverseV2-0-0', nodes)
self.assertIn('ReverseV2-1-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReverseWithNonConstDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dims = array_ops.placeholder(dtype='int32')
reverse = array_ops.reverse(conv, dims)
output = array_ops.identity(reverse)
dims_val = [2, 3]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={dims: dims_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
dims: dims_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('ReverseV2-0-0', nodes)
self._assert_map_nhwc_to_nchw('ReverseV2-1', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSelectOp(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
add = math_ops.add(conv, conv)
mean = math_ops.reduce_mean(conv)
condition = math_ops.less(conv, mean)
select = gen_math_ops.select(condition, conv, add)
output = array_ops.identity(select)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Select-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSelectOpConditionUnknownShape(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
add = math_ops.add(conv, conv)
condition = array_ops.placeholder(dtype='bool')
select = gen_math_ops.select(condition, conv, add)
output = array_ops.identity(select)
condition_val = np.zeros((1, 7, 7, 64))
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={condition: condition_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={condition: condition_val})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 3
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSelectOpScalarCondition(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
add = math_ops.add(conv, conv)
condition = constant_op.constant(True)
select = gen_math_ops.select(condition, conv, add)
output = array_ops.identity(select)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Select-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testPadWithNonConstPaddings(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
paddings = array_ops.placeholder(dtype='int32')
pad = array_ops.pad(conv, paddings)
output = array_ops.identity(pad)
paddings_val = [[1, 2], [3, 4], [5, 6], [7, 8]]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={paddings: paddings_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
paddings: paddings_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Pad-0-0', nodes)
self._assert_vec_nhwc_to_nchw('Pad-1', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testMaxPoolV2(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
ksize = constant_op.constant([1, 2, 3, 1], shape=[4])
strides = array_ops.placeholder(dtype='int32', shape=[4])
max_pool = gen_nn_ops.max_pool_v2(conv, ksize, strides, 'VALID')
output = array_ops.identity(max_pool)
strides_val = [1, 3, 2, 1]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={strides: strides_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
strides: strides_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('MaxPoolV2-0-0', nodes)
self._assert_vec_nhwc_to_nchw('MaxPoolV2-2', nodes)
self.assertIn('MaxPoolV2-1-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testMaxPoolGradV2(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
ksize = constant_op.constant([1, 2, 3, 1], shape=[4])
strides = array_ops.placeholder(dtype='int32', shape=[4])
max_pool_grad = gen_nn_ops.max_pool_grad_v2(conv, conv, conv, ksize,
strides, 'VALID')
output = array_ops.identity(max_pool_grad)
strides_val = [1, 3, 2, 1]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={strides: strides_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
strides: strides_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('MaxPoolGradV2-0-0', nodes)
self._assert_vec_nhwc_to_nchw('MaxPoolGradV2-4', nodes)
self.assertIn('MaxPoolGradV2-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSliceWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
size = array_ops.placeholder(dtype='int32')
s = array_ops.slice(conv, [0, 0, 0, 0], size)
output = array_ops.identity(s)
size_val = [1, 2, 3, 4]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={size: size_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
size: size_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Slice-0-0', nodes)
self._assert_vec_nhwc_to_nchw('Slice-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
end = array_ops.placeholder(dtype='int32')
s = array_ops.strided_slice(conv, [0, 0, 0, 0], end, strides=[1, 2, 3, 1])
output = array_ops.identity(s)
end_val = [1, 2, 3, 4]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={end: end_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
end: end_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('StridedSlice-0-0', nodes)
self._assert_vec_nhwc_to_nchw('StridedSlice-2', nodes)
self.assertIn('StridedSlice-1-LayoutOptimizer', nodes)
self.assertIn('StridedSlice-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceWithMask1011(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
# This will generate a StridedSlice op with begin mask and
# end mask 11(1011).
s = conv[:, :, 1:-1, :]
output = array_ops.identity(s)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('strided_slice-0-0', nodes)
self.assertIn('strided_slice-1-LayoutOptimizer', nodes)
self.assertIn('strided_slice-2-LayoutOptimizer', nodes)
self.assertIn('strided_slice-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceWithMask0111(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
# This will generate a StridedSlice op with begin mask and
# end mask 7(0111).
s = conv[:, :, :, 1:-1]
output = array_ops.identity(s)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('strided_slice-0-0', nodes)
self.assertIn('strided_slice-1-LayoutOptimizer', nodes)
self.assertIn('strided_slice-2-LayoutOptimizer', nodes)
self.assertIn('strided_slice-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceGradWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
end = array_ops.placeholder(dtype='int32')
shape = array_ops.shape(conv)
end_val = [1, 2, 3, 4]
s = array_ops.strided_slice(
conv, [0, 0, 0, 0], end_val, strides=[1, 2, 3, 1])
s_grad = array_ops.strided_slice_grad(shape, [0, 0, 0, 0], end,
[1, 2, 3, 1], s)
output = array_ops.identity(s_grad)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={end: end_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
end: end_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('StridedSliceGrad-0-0', nodes)
self._assert_vec_nhwc_to_nchw('StridedSliceGrad-2', nodes)
self.assertIn('StridedSlice-1-LayoutOptimizer', nodes)
self.assertIn('StridedSlice-2-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testShapeN(self):
if test.is_gpu_available(cuda_only=True):
x = array_ops.placeholder(dtype='float32')
conv = _two_layer_model(x)
shapen = array_ops.shape_n([conv, conv])
output = math_ops.add(shapen[0], shapen[1])
x_val = [1.7] * 784
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={x: x_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
x: x_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_vec_nchw_to_nhwc('ShapeN-0-0', nodes)
self.assertAllEqual(output_val_ref, output_val)
@test_util.deprecated_graph_mode_only
def testShapeNFollowedByNotConvertibleNodeReshape(self):
if test.is_gpu_available(cuda_only=True):
x = array_ops.placeholder(dtype='float32')
conv = _two_layer_model(x)
conv_reshape = array_ops.reshape(conv, [1, 1, 1, -1])
shapen = array_ops.shape_n([conv, conv_reshape])
shape = array_ops.identity(shapen[1])
ones = array_ops.ones(shape)
output = math_ops.add_n([conv_reshape, ones])
x_val = [1.7] * 784
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={x: x_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={x: x_val})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testLoop(self):
if test.is_gpu_available(cuda_only=True):
output = _loop()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('map/while/Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('map/while/MaxPool_1-0-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testLoopWithBranch(self):
if test.is_gpu_available(cuda_only=True):
output = _loop_with_branch()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 3
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('map/while/Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('map/while/Add_1-0-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testLoopWithVecAnd4D(self):
if test.is_gpu_available(cuda_only=True):
output = _loop_with_vec_and_4d()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('map/while/Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('map/while/Add_1-0-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testBinaryOpSecondPort(self):
with compat.forward_compatibility_horizon(2019, 6, 7):
if test.is_gpu_available(cuda_only=True):
output = _model_with_second_port()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('FusedBatchNormV3-0', nodes)
self._assert_trans_nchw_to_nhwc('Add-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testGradient(self):
meta_graph = _simple_metagraph()
config = config_pb2.ConfigProto()
config.graph_options.rewrite_options.CopyFrom(
rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.ON,
min_graph_nodes=-1))
optimized_graph = tf_optimizer.OptimizeGraph(
config, meta_graph, cluster=_get_cluster())
found = 0
for node in optimized_graph.node:
if node.op in ['Conv2D', 'Conv2DBackpropFilter', 'Conv2DBackpropInput']:
found += 1
self.assertEqual(node.attr['data_format'].s, b'NCHW')
self.assertEqual(found, 5)
@test_util.deprecated_graph_mode_only
def testDepthwise(self):
meta_graph = _simple_metagraph(depthwise=True)
config = config_pb2.ConfigProto()
config.graph_options.rewrite_options.CopyFrom(
rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.ON,
min_graph_nodes=-1))
optimized_graph = tf_optimizer.OptimizeGraph(
config, meta_graph, cluster=_get_cluster())
found = 0
for node in optimized_graph.node:
if node.op in [
'DepthwiseConv2dNative', 'DepthwiseConv2dNativeBackpropFilter',
'DepthwiseConv2dNativeBackpropInput'
]:
found += 1
self.assertEqual(node.attr['data_format'].s, b'NCHW')
self.assertEqual(found, 6)
def testCheckpointCompatibility(self):
if not test.is_gpu_available(cuda_only=True):
self.skipTest('GPU required')
checkpoint_path = self.get_temp_dir()
self._train(checkpoint_path)
vars_expected = self._train(checkpoint_path, restore=True)
vars_layout_optimized = self._train(
checkpoint_path, restore=True, layout_optimizer=True)
for var_expected, var_layout_optimized in zip(vars_expected,
vars_layout_optimized):
self.assertAllClose(var_expected, var_layout_optimized, atol=1e-6)
if __name__ == '__main__':
test.main()
| ghchinoy/tensorflow | tensorflow/python/grappler/layout_optimizer_test.py | Python | apache-2.0 | 60,128 |
//
// CppParserTestSuite.h
//
// $Id: //poco/1.3/CppParser/testsuite/src/CppParserTestSuite.h#1 $
//
// Definition of the CppParserTestSuite class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef CppParserTestSuite_INCLUDED
#define CppParserTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class CppParserTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // CppParserTestSuite_INCLUDED
| nextsmsversion/macchina.io | platform/CppParser/testsuite/src/CppParserTestSuite.h | C | apache-2.0 | 503 |
/*
Copyright 2007, 2008 Daniel Zerbino ([email protected])
This file is part of Velvet.
Velvet is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Velvet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Velvet; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _SHORTREADPAIRS_H_
#define _SHORTREADPAIRS_H_
// Original
boolean pushNeighboursInterRepeat(Node * node, Node * nodeInterRepeat,
Node * oppositeNode, Graph * argGraph);
// Original
void exploitShortReadPairs(Graph * graph, ReadSet * reads,
boolean * dubious, boolean force_jumps);
void detachImprobablePairs(ReadSet * sequences, Graph * graph);
void handicapNode(Node * node);
NodeList *getMarkedNodeList();
#endif
| reiverjohn/biobench2 | velvet/contrib/MetaVelvet-v0.3.1/src/shortReadPairs.h | C | apache-2.0 | 1,238 |
/*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#import <Foundation/Foundation.h>
#import "EC2DescribeImagesResponse.h"
#import "EC2ResponseUnmarshaller.h"
#import "../AmazonValueUnmarshaller.h"
#import "../AmazonBoolValueUnmarshaller.h"
#import "../AmazonListUnmarshaller.h"
#import "EC2ImageUnmarshaller.h"
/**
* Describe Images Response Unmarshaller
*/
@interface EC2DescribeImagesResponseUnmarshaller:EC2ResponseUnmarshaller {
EC2DescribeImagesResponse *response;
}
@property (nonatomic, readonly) EC2DescribeImagesResponse *response;
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
@end
| abovelabs/aws-ios-sdk | src/include/EC2/EC2DescribeImagesResponseUnmarshaller.h | C | apache-2.0 | 1,429 |
'use strict';
/**
* @ngdoc function
* @name openshiftConsole.controller:ImageController
* @description
* Controller of the openshiftConsole
*/
angular.module('openshiftConsole')
.controller('ImageController', function ($scope, $routeParams, DataService, ProjectsService, $filter, ImageStreamsService) {
$scope.projectName = $routeParams.project;
$scope.imageStream = null;
$scope.tagsByName = {};
$scope.tagShowOlder = {};
$scope.alerts = {};
$scope.renderOptions = $scope.renderOptions || {};
$scope.renderOptions.hideFilterWidget = true;
$scope.breadcrumbs = [
{
title: "Image Streams",
link: "project/" + $routeParams.project + "/browse/images"
},
{
title: $routeParams.image
}
];
$scope.emptyMessage = "Loading...";
var watches = [];
ProjectsService
.get($routeParams.project)
.then(_.spread(function(project, context) {
$scope.project = project;
DataService.get("imagestreams", $routeParams.image, context).then(
// success
function(imageStream) {
$scope.loaded = true;
$scope.imageStream = imageStream;
$scope.emptyMessage = "No tags to show";
// If we found the item successfully, watch for changes on it
watches.push(DataService.watchObject("imagestreams", $routeParams.image, context, function(imageStream, action) {
if (action === "DELETED") {
$scope.alerts["deleted"] = {
type: "warning",
message: "This image stream has been deleted."
};
}
$scope.imageStream = imageStream;
$scope.tagsByName = ImageStreamsService.tagsByName($scope.imageStream);
}));
},
// failure
function(e) {
$scope.loaded = true;
$scope.alerts["load"] = {
type: "error",
message: "The image stream details could not be loaded.",
details: "Reason: " + $filter('getErrorDetails')(e)
};
});
$scope.$on('$destroy', function(){
DataService.unwatchAll(watches);
});
}));
});
| tmckayus/oshinko-rest | vendor/github.com/openshift/origin/assets/app/scripts/controllers/image.js | JavaScript | apache-2.0 | 2,257 |
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* 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 com.dtolabs.rundeck.core.storage;
import java.util.Date;
import java.util.Map;
/**
* Abstract base implementation of {@link ResourceMeta}
*/
abstract class BaseResource implements ResourceMeta {
Map<String,String> meta;
protected BaseResource(Map<String, String> meta) {
this.meta = meta;
}
@Override
public Map<String, String> getMeta() {
return meta;
}
@Override
public String getContentType() {
return meta.get(StorageUtil.RES_META_RUNDECK_CONTENT_TYPE);
}
@Override
public long getContentLength() {
return StorageUtil.parseLong(meta.get(StorageUtil.RES_META_RUNDECK_CONTENT_LENGTH), -1);
}
@Override
public Date getModificationTime() {
return StorageUtil.parseDate(meta.get(StorageUtil.RES_META_RUNDECK_CONTENT_MODIFY_TIME), null);
}
@Override
public Date getCreationTime() {
return StorageUtil.parseDate(meta.get(StorageUtil.RES_META_RUNDECK_CONTENT_CREATION_TIME), null);
}
}
| rophy/rundeck | core/src/main/java/com/dtolabs/rundeck/core/storage/BaseResource.java | Java | apache-2.0 | 1,647 |
"""Support for switches through the SmartThings cloud API."""
from __future__ import annotations
from collections.abc import Sequence
from pysmartthings import Capability
from homeassistant.components.switch import SwitchEntity
from . import SmartThingsEntity
from .const import DATA_BROKERS, DOMAIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Add switches for a config entry."""
broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id]
async_add_entities(
[
SmartThingsSwitch(device)
for device in broker.devices.values()
if broker.any_assigned(device.device_id, "switch")
]
)
def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None:
"""Return all capabilities supported if minimum required are present."""
# Must be able to be turned on/off.
if Capability.switch in capabilities:
return [Capability.switch, Capability.energy_meter, Capability.power_meter]
return None
class SmartThingsSwitch(SmartThingsEntity, SwitchEntity):
"""Define a SmartThings switch."""
async def async_turn_off(self, **kwargs) -> None:
"""Turn the switch off."""
await self._device.switch_off(set_status=True)
# State is set optimistically in the command above, therefore update
# the entity state ahead of receiving the confirming push updates
self.async_write_ha_state()
async def async_turn_on(self, **kwargs) -> None:
"""Turn the switch on."""
await self._device.switch_on(set_status=True)
# State is set optimistically in the command above, therefore update
# the entity state ahead of receiving the confirming push updates
self.async_write_ha_state()
@property
def is_on(self) -> bool:
"""Return true if light is on."""
return self._device.status.switch
| jawilson/home-assistant | homeassistant/components/smartthings/switch.py | Python | apache-2.0 | 1,911 |
//===- include/Core/Instrumentation.h - Instrumentation API ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Provide an Instrumentation API that optionally uses VTune interfaces.
///
//===----------------------------------------------------------------------===//
#ifndef LLD_CORE_INSTRUMENTATION_H
#define LLD_CORE_INSTRUMENTATION_H
#include "llvm/Support/Compiler.h"
#include <utility>
#ifdef LLD_HAS_VTUNE
# include <ittnotify.h>
#endif
namespace lld {
#ifdef LLD_HAS_VTUNE
/// A unique global scope for instrumentation data.
///
/// Domains last for the lifetime of the application and cannot be destroyed.
/// Multiple Domains created with the same name represent the same domain.
class Domain {
__itt_domain *_domain;
public:
explicit Domain(const char *name) : _domain(__itt_domain_createA(name)) {}
operator __itt_domain *() const { return _domain; }
__itt_domain *operator->() const { return _domain; }
};
/// A global reference to a string constant.
///
/// These are uniqued by the ITT runtime and cannot be deleted. They are not
/// specific to a domain.
///
/// Prefer reusing a single StringHandle over passing a ntbs when the same
/// string will be used often.
class StringHandle {
__itt_string_handle *_handle;
public:
StringHandle(const char *name) : _handle(__itt_string_handle_createA(name)) {}
operator __itt_string_handle *() const { return _handle; }
};
/// A task on a single thread. Nests within other tasks.
///
/// Each thread has its own task stack and tasks nest recursively on that stack.
/// A task cannot transfer threads.
///
/// SBRM is used to ensure task starts and ends are ballanced. The lifetime of
/// a task is either the lifetime of this object, or until end is called.
class ScopedTask {
__itt_domain *_domain;
ScopedTask(const ScopedTask &) = delete;
ScopedTask &operator=(const ScopedTask &) = delete;
public:
/// Create a task in Domain \p d named \p s.
ScopedTask(const Domain &d, const StringHandle &s) : _domain(d) {
__itt_task_begin(d, __itt_null, __itt_null, s);
}
ScopedTask(ScopedTask &&other) {
*this = std::move(other);
}
ScopedTask &operator=(ScopedTask &&other) {
_domain = other._domain;
other._domain = nullptr;
return *this;
}
/// Prematurely end this task.
void end() {
if (_domain)
__itt_task_end(_domain);
_domain = nullptr;
}
~ScopedTask() { end(); }
};
/// A specific point in time. Allows metadata to be associated.
class Marker {
public:
Marker(const Domain &d, const StringHandle &s) {
__itt_marker(d, __itt_null, s, __itt_scope_global);
}
};
#else
class Domain {
public:
Domain(const char *name) {}
};
class StringHandle {
public:
StringHandle(const char *name) {}
};
class ScopedTask {
public:
ScopedTask(const Domain &d, const StringHandle &s) {}
void end() {}
};
class Marker {
public:
Marker(const Domain &d, const StringHandle &s) {}
};
#endif
inline const Domain &getDefaultDomain() {
static Domain domain("org.llvm.lld");
return domain;
}
} // end namespace lld.
#endif
| llvm-mirror/lld | include/lld/Core/Instrumentation.h | C | apache-2.0 | 3,344 |
#ifndef AXIS2_CREATEACCOUNTRESPONSE_H
#define AXIS2_CREATEACCOUNTRESPONSE_H
/**
* axis2_createAccountResponse.h
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: #axisVersion# #today#
*/
#include <stdio.h>
#include <axiom.h>
#include <axutil_utils.h>
#include <axiom_soap.h>
#include <axis2_client.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define AXIS2_DEFAULT_DIGIT_LIMIT 64
/**
* axis2_createAccountResponse class class
*/
typedef struct axis2_createAccountResponse axis2_createAccountResponse_t;
AXIS2_EXTERN axis2_createAccountResponse_t* AXIS2_CALL
axis2_createAccountResponse_create(
const axutil_env_t *env );
axis2_status_t AXIS2_CALL
axis2_createAccountResponse_free (
axis2_createAccountResponse_t* createAccountResponse,
const axutil_env_t *env);
axutil_qname_t* AXIS2_CALL
axis2_createAccountResponse_get_qname (
axis2_createAccountResponse_t* createAccountResponse,
const axutil_env_t *env);
axiom_node_t* AXIS2_CALL
axis2_createAccountResponse_serialize(
axis2_createAccountResponse_t* createAccountResponse,
const axutil_env_t *env,
axiom_node_t* createAccountResponse_om_node, int has_parent);
axis2_status_t AXIS2_CALL
axis2_createAccountResponse_deserialize(
axis2_createAccountResponse_t* createAccountResponse,
const axutil_env_t *env, axiom_node_t* parent);
/**
* getter for userid.
*/
axis2_char_t* AXIS2_CALL
axis2_createAccountResponse_get_userid(
axis2_createAccountResponse_t* createAccountResponse,
const axutil_env_t *env);
/**
* setter for userid
*/
axis2_status_t AXIS2_CALL
axis2_createAccountResponse_set_userid(
axis2_createAccountResponse_t* createAccountResponse,
const axutil_env_t *env,
axis2_char_t* param_userid);
#ifdef __cplusplus
}
#endif
#endif /* AXIS2_CREATEACCOUNTRESPONSE_H */
| techhead/wsf_php_dist | wsf_c/examples/trader/include/axis2_createAccountResponse.h | C | apache-2.0 | 2,360 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.watcher.actions.jira;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.xpack.core.watcher.actions.Action;
import org.elasticsearch.xpack.core.watcher.actions.ExecutableAction;
import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.core.watcher.watch.Payload;
import org.elasticsearch.xpack.watcher.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.common.text.TextTemplateEngine;
import org.elasticsearch.xpack.watcher.notification.jira.JiraAccount;
import org.elasticsearch.xpack.watcher.notification.jira.JiraIssue;
import org.elasticsearch.xpack.watcher.notification.jira.JiraService;
import org.elasticsearch.xpack.watcher.support.Variables;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class ExecutableJiraAction extends ExecutableAction<JiraAction> {
private final TextTemplateEngine engine;
private final JiraService jiraService;
public ExecutableJiraAction(JiraAction action, Logger logger, JiraService jiraService, TextTemplateEngine templateEngine) {
super(action, logger);
this.jiraService = jiraService;
this.engine = templateEngine;
}
@Override
public Action.Result execute(final String actionId, WatchExecutionContext ctx, Payload payload) throws Exception {
JiraAccount account = jiraService.getAccount(action.account);
if (account == null) {
// the account associated with this action was deleted
throw new IllegalStateException("account [" + action.account + "] was not found. perhaps it was deleted");
}
final Function<String, String> render = s -> engine.render(new TextTemplate(s), Variables.createCtxParamsMap(ctx, payload));
Map<String, Object> fields = new HashMap<>();
// Apply action fields
fields = merge(fields, action.fields, render);
// Apply default fields
fields = merge(fields, account.getDefaults(), render);
if (ctx.simulateAction(actionId)) {
return new JiraAction.Simulated(fields);
}
JiraIssue result = account.createIssue(fields, action.proxy);
return new JiraAction.Executed(result);
}
/**
* Merges the defaults provided as the second parameter into the content of the first
* while applying a {@link Function} on both map key and map value.
*/
static Map<String, Object> merge(final Map<String, Object> fields, final Map<String, ?> defaults, final Function<String, String> fn) {
if (defaults != null) {
for (Map.Entry<String, ?> defaultEntry : defaults.entrySet()) {
Object value = defaultEntry.getValue();
if (value instanceof String) {
// Apply the transformation to a simple string
value = fn.apply((String) value);
} else if (value instanceof Map) {
// Apply the transformation to a map
value = merge(new HashMap<>(), (Map<String, ?>) value, fn);
} else if (value instanceof String[]) {
// Apply the transformation to an array of strings
String[] newValues = new String[((String[]) value).length];
for (int i = 0; i < newValues.length; i++) {
newValues[i] = fn.apply(((String[]) value)[i]);
}
value = newValues;
} else if (value instanceof List) {
// Apply the transformation to a list of strings
List<Object> newValues = new ArrayList<>(((List) value).size());
for (Object v : (List) value) {
if (v instanceof String) {
newValues.add(fn.apply((String) v));
} else if (v instanceof Map) {
newValues.add(merge(new HashMap<>(), (Map<String, ?>) v, fn));
} else {
newValues.add(v);
}
}
value = newValues;
}
// Apply the transformation to the key
String key = fn.apply(defaultEntry.getKey());
// Copy the value directly in the map if it does not exist yet.
// We don't try to merge maps or list.
if (fields.containsKey(key) == false) {
fields.put(key, value);
}
}
}
return fields;
}
}
| robin13/elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/jira/ExecutableJiraAction.java | Java | apache-2.0 | 4,970 |
(function() {
window.WallTime || (window.WallTime = {});
window.WallTime.data = {
rules: {"PRC":[{"name":"PRC","_from":"1986","_to":"only","type":"-","in":"May","on":"4","at":"0:00","_save":"1:00","letter":"D"},{"name":"PRC","_from":"1986","_to":"1991","type":"-","in":"Sep","on":"Sun>=11","at":"0:00","_save":"0","letter":"S"},{"name":"PRC","_from":"1987","_to":"1991","type":"-","in":"Apr","on":"Sun>=10","at":"0:00","_save":"1:00","letter":"D"}]},
zones: {"Asia/Chongqing":[{"name":"Asia/Chongqing","_offset":"7:06:20","_rule":"-","format":"LMT","_until":"1928"},{"name":"Asia/Chongqing","_offset":"7:00","_rule":"-","format":"LONT","_until":"1980 May"},{"name":"Asia/Chongqing","_offset":"8:00","_rule":"PRC","format":"C%sT","_until":""}]}
};
window.WallTime.autoinit = true;
}).call(this); | SalesforceSFDC/aura | aura-resources/src/main/resources/aura/resources/walltime-js/olson/walltime-data_Asia-Chongqing.js | JavaScript | apache-2.0 | 826 |
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement as listed in [the MAINTAINERS file](https://github.com/docker-library/official-images/blob/master/MAINTAINERS). All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
| docker-solr/official-images | CODE-OF-CONDUCT.md | Markdown | apache-2.0 | 3,421 |
package mil.nga.giat.geowave.adapter.raster.adapter.merge.nodata;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Set;
public class NoDataBySampleIndex implements
NoDataMetadata
{
private Set<SampleIndex> noDataIndexSet;
protected NoDataBySampleIndex() {
super();
}
public NoDataBySampleIndex(
final Set<SampleIndex> noDataIndexSet ) {
this.noDataIndexSet = noDataIndexSet;
}
@Override
public byte[] toBinary() {
final ByteBuffer buf = ByteBuffer.allocate(noDataIndexSet.size() * 12);
for (final SampleIndex i : noDataIndexSet) {
buf.putInt(i.getX());
buf.putInt(i.getY());
buf.putInt(i.getBand());
}
return buf.array();
}
@Override
public void fromBinary(
final byte[] bytes ) {
final ByteBuffer buf = ByteBuffer.wrap(bytes);
final int size = bytes.length / 12;
noDataIndexSet = new HashSet<SampleIndex>(
size);
for (int i = 0; i < size; i++) {
final int x = buf.getInt();
final int y = buf.getInt();
final int b = buf.getInt();
noDataIndexSet.add(new SampleIndex(
x,
y,
b));
}
}
@Override
public boolean isNoData(
final SampleIndex index,
final double sampleValue ) {
return noDataIndexSet.contains(index);
}
@Override
public Set<SampleIndex> getNoDataIndices() {
return noDataIndexSet;
}
}
| ruks/geowave | extensions/adapters/raster/src/main/java/mil/nga/giat/geowave/adapter/raster/adapter/merge/nodata/NoDataBySampleIndex.java | Java | apache-2.0 | 1,322 |
// (C) Copyright Edward Diener 2011
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include "test_has_static_mem_fun.hpp"
#include <boost/mpl/assert.hpp>
int main()
{
// You can always instantiate without compiler errors
TheTIntFunction<AType,void (long,double)> aVar;
Pickedname<AnotherType,AType (long,long)> aVar3;
// Compile time asserts
BOOST_MPL_ASSERT((HaveTheSIntFunction<AType,int (long,double)>));
BOOST_MPL_ASSERT((TheTIntFunction<AnotherType,AType (long,double)>));
BOOST_MPL_ASSERT((BOOST_TTI_HAS_STATIC_MEMBER_FUNCTION_GEN(TSFunction)<AnotherType,AType::AStructType (AType::AnIntType,double)>));
return 0;
}
| flingone/frameworks_base_cmds_remoted | libs/boost/libs/tti/test/test_has_static_member_compile.cpp | C++ | apache-2.0 | 833 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/*
* $Id$
*/
#include "DOMImplementationListImpl.hpp"
#include <xercesc/dom/DOMImplementation.hpp>
XERCES_CPP_NAMESPACE_BEGIN
DOMImplementationListImpl::DOMImplementationListImpl()
{
fList=new RefVectorOf<DOMImplementation>(3, false);
}
DOMImplementationListImpl:: ~DOMImplementationListImpl()
{
delete fList;
}
void DOMImplementationListImpl::add(DOMImplementation* impl) {
fList->addElement(impl);
}
XMLSize_t DOMImplementationListImpl::getLength() const{
return fList->size();
}
DOMImplementation *DOMImplementationListImpl::item(XMLSize_t index) const
{
if(index<fList->size())
return fList->elementAt(index);
return 0;
}
void DOMImplementationListImpl::release() {
delete this;
}
XERCES_CPP_NAMESPACE_END
| Distrotech/xerces-c | src/xercesc/dom/impl/DOMImplementationListImpl.cpp | C++ | apache-2.0 | 1,564 |
=pod
=for comment openssl_manual_section:7
=head1 NAME
evp - high-level cryptographic functions
=head1 SYNOPSIS
#include <openssl/evp.h>
=head1 DESCRIPTION
The EVP library provides a high-level interface to cryptographic
functions.
L<B<EVP_Seal>I<...>|EVP_SealInit(3)> and L<B<EVP_Open>I<...>|EVP_OpenInit(3)>
provide public key encryption and decryption to implement digital "envelopes".
The L<B<EVP_DigestSign>I<...>|EVP_DigestSignInit(3)> and
L<B<EVP_DigestVerify>I<...>|EVP_DigestVerifyInit(3)> functions implement
digital signatures and Message Authentication Codes (MACs). Also see the older
L<B<EVP_Sign>I<...>|EVP_SignInit(3)> and L<B<EVP_Verify>I<...>|EVP_VerifyInit(3)>
functions.
Symmetric encryption is available with the L<B<EVP_Encrypt>I<...>|EVP_EncryptInit(3)>
functions. The L<B<EVP_Digest>I<...>|EVP_DigestInit(3)> functions provide message digests.
The B<EVP_PKEY>I<...> functions provide a high level interface to
asymmetric algorithms. To create a new EVP_PKEY see
L<EVP_PKEY_new(3)>. EVP_PKEYs can be associated
with a private key of a particular algorithm by using the functions
described on the L<EVP_PKEY_set1_RSA(3)> page, or
new keys can be generated using L<EVP_PKEY_keygen(3)>.
EVP_PKEYs can be compared using L<EVP_PKEY_cmp(3)>, or printed using
L<EVP_PKEY_print_private(3)>.
The EVP_PKEY functions support the full range of asymmetric algorithm operations:
=over
=item For key agreement see L<EVP_PKEY_derive(3)>
=item For signing and verifying see L<EVP_PKEY_sign(3)>,
L<EVP_PKEY_verify(3)> and L<EVP_PKEY_verify_recover(3)>.
However, note that
these functions do not perform a digest of the data to be signed. Therefore
normally you would use the L<EVP_DigestSignInit(3)>
functions for this purpose.
=item For encryption and decryption see L<EVP_PKEY_encrypt(3)>
and L<EVP_PKEY_decrypt(3)> respectively. However, note that
these functions perform encryption and decryption only. As public key
encryption is an expensive operation, normally you would wrap
an encrypted message in a "digital envelope" using the L<EVP_SealInit(3)> and
L<EVP_OpenInit(3)> functions.
=back
The L<EVP_BytesToKey(3)> function provides some limited support for password
based encryption. Careful selection of the parameters will provide a PKCS#5 PBKDF1 compatible
implementation. However, new applications should not typically use this (preferring, for example,
PBKDF2 from PCKS#5).
The L<B<EVP_Encode>I<...>|EVP_EncodeInit(3)> and
L<B<EVP_Decode>I<...>|EVP_EncodeInit(3)> functions implement base 64 encoding
and decoding.
All the symmetric algorithms (ciphers), digests and asymmetric algorithms
(public key algorithms) can be replaced by L<engine(3)> modules providing alternative
implementations. If ENGINE implementations of ciphers or digests are registered
as defaults, then the various EVP functions will automatically use those
implementations automatically in preference to built in software
implementations. For more information, consult the engine(3) man page.
Although low level algorithm specific functions exist for many algorithms
their use is discouraged. They cannot be used with an ENGINE and ENGINE
versions of new algorithms cannot be accessed using the low level functions.
Also makes code harder to adapt to new algorithms and some options are not
cleanly supported at the low level and some operations are more efficient
using the high level interface.
=head1 SEE ALSO
L<EVP_DigestInit(3)>,
L<EVP_EncryptInit(3)>,
L<EVP_OpenInit(3)>,
L<EVP_SealInit(3)>,
L<EVP_DigestSignInit(3)>,
L<EVP_SignInit(3)>,
L<EVP_VerifyInit(3)>,
L<EVP_EncodeInit(3)>,
L<EVP_PKEY_new(3)>,
L<EVP_PKEY_set1_RSA(3)>,
L<EVP_PKEY_keygen(3)>,
L<EVP_PKEY_print_private(3)>,
L<EVP_PKEY_decrypt(3)>,
L<EVP_PKEY_encrypt(3)>,
L<EVP_PKEY_sign(3)>,
L<EVP_PKEY_verify(3)>,
L<EVP_PKEY_verify_recover(3)>,
L<EVP_PKEY_derive(3)>,
L<EVP_BytesToKey(3)>,
L<engine(3)>
=head1 COPYRIGHT
Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| openweave/openweave-core | third_party/openssl/openssl/doc/crypto/evp.pod | Perl | apache-2.0 | 4,219 |
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.big.data.kettle.plugins.hdfs.job;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.pentaho.big.data.api.cluster.NamedClusterService;
import org.pentaho.big.data.api.cluster.service.locator.NamedClusterServiceLocator;
import org.pentaho.big.data.api.initializer.ClusterInitializationException;
import org.pentaho.big.data.impl.cluster.NamedClusterImpl;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.entry.loadSave.LoadSaveTester;
import org.pentaho.runtime.test.RuntimeTester;
import org.pentaho.runtime.test.action.RuntimeTestActionService;
public class JobEntryHadoopCopyFilesLoadSaveTest {
private NamedClusterService namedClusterService;
private RuntimeTestActionService runtimeTestActionService;
private RuntimeTester runtimeTester;
@Before
public void setup() throws ClusterInitializationException {
namedClusterService = mock( NamedClusterService.class );
when( namedClusterService.getClusterTemplate() ).thenReturn( new NamedClusterImpl() );
mock( NamedClusterServiceLocator.class );
runtimeTester = mock( RuntimeTester.class );
runtimeTestActionService = mock( RuntimeTestActionService.class );
new JobEntryHadoopCopyFiles( namedClusterService, runtimeTestActionService, runtimeTester );
}
@Test
public void testLoadSave() throws KettleException {
List<String> commonAttributes = Arrays.asList( "copy_empty_folders", "arg_from_previous", "overwrite_files",
"include_subfolders", "remove_source_files", "add_result_filesname", "destination_is_a_file",
"create_destination_folder" );
Map<String, String> getterMap = new HashMap<String, String>();
getterMap.put( "copy_empty_folders", "isCopyEmptyFolders" );
getterMap.put( "arg_from_previous", "isArgFromPrevious" );
getterMap.put( "overwrite_files", "isoverwrite_files" );
getterMap.put( "include_subfolders", "isIncludeSubfolders" );
getterMap.put( "remove_source_files", "isRemoveSourceFiles" );
getterMap.put( "add_result_filesname", "isAddresultfilesname" );
getterMap.put( "destination_is_a_file", "isDestinationIsAFile" );
getterMap.put( "create_destination_folder", "isCreateDestinationFolder" );
Map<String, String> setterMap = new HashMap<String, String>();
setterMap.put( "copy_empty_folders", "setCopyEmptyFolders" );
setterMap.put( "arg_from_previous", "setArgFromPrevious" );
setterMap.put( "overwrite_files", "setoverwrite_files" );
setterMap.put( "include_subfolders", "setIncludeSubfolders" );
setterMap.put( "remove_source_files", "setRemoveSourceFiles" );
setterMap.put( "add_result_filesname", "setAddresultfilesname" );
setterMap.put( "destination_is_a_file", "setDestinationIsAFile" );
setterMap.put( "create_destination_folder", "setCreateDestinationFolder" );
LoadSaveTester<JobEntryHadoopCopyFiles> tester =
new LoadSaveTester<JobEntryHadoopCopyFiles>( JobEntryHadoopCopyFiles.class, commonAttributes,
getterMap, setterMap ) {
@Override public JobEntryHadoopCopyFiles createMeta() {
return new JobEntryHadoopCopyFiles( namedClusterService, runtimeTestActionService, runtimeTester );
}
};
tester.testSerialization();
}
}
| pedrofvteixeira/big-data-plugin | kettle-plugins/hdfs/src/test/java/org/pentaho/big/data/kettle/plugins/hdfs/job/JobEntryHadoopCopyFilesLoadSaveTest.java | Java | apache-2.0 | 4,340 |