answer stringlengths 17 10.2M |
|---|
/*
*
* Adafruit16CServoDriver
*
* TODO - test with Steppers & Motors - switches on board - interface accepts motor control
*
*/
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.DeviceControl;
import org.myrobotlab.service.interfaces.DeviceController;
import org.myrobotlab.service.interfaces.I2CControl;
import org.myrobotlab.service.interfaces.I2CController;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
public class Adafruit16CServoDriver extends Service implements I2CControl, ServoController {
/** version of the library */
static public final String VERSION = "0.9";
private static final long serialVersionUID = 1L;
// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos
// you have!
public final static int SERVOMIN = 150; // this is the 'minimum' pulse
// length count (out of 4096)
public final static int SERVOMAX = 600; // this is the 'maximum' pulse
// length count (out of 4096)
transient public I2CController controller;
// Variable to ensure that a PWM freqency has been set before starting PWM
private int pwmFreq = 60;
private boolean pwmFreqSet = false;
// List of possible addresses. Used by the GUI.
public List<String> deviceAddressList = Arrays.asList("0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E",
"0x4F", "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F");
// Default address
public String deviceAddress = "0x40";
/**
* This address is to address all Adafruit16CServoDrivers on the i2c bus Don't
* use this address for any other device on the i2c bus since it will cause
* collisions.
*/
public String broadcastAddress = "0x70";
public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7");
public String deviceBus = "1";
public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName());
public static final int PCA9685_MODE1 = 0x00; // Mode 1 register
public static final byte PCA9685_SLEEP = 0x10; // Set sleep mode, before
// changing prescale value
public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set autoincrement to
// be able to write
// more than one byte
// in sequence
public static final byte PCA9685_PRESCALE = (byte) 0xFE; // PreScale
// register
// Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0
// The rest of the addresses are calculated based on pin numbers
public static final int PCA9685_LED0_ON_L = 0x06; // First LED address Low
public static final int PCA9685_LED0_ON_H = 0x07; // First LED address High
public static final int PCA9685_LED0_OFF_L = 0x08; // First LED address Low
public static final int PCA9685_LED0_OFF_H = 0x08; // First LED address High
// public static final int PWM_FREQ = 60; // default frequency for servos
public static final int osc_clock = 25000000; // clock frequency of the
// internal clock
public static final int precision = 4096; // pwm_precision
// i2c controller
public ArrayList<String> controllers;
public String controllerName;
public boolean isControllerSet = false;
/**
* @Mats - added by GroG - was wondering if this would help, probably you need
* a reverse index too ?
* @GroG - I only need servoNameToPin yet. To be able to sweep some more
* values may be needed
*/
HashMap<String, Integer> servoNameToPin = new HashMap<String, Integer>();
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver");
log.info("Driver {}", driver);
}
public Adafruit16CServoDriver(String n) {
super(n);
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
}
public void onRegistered(ServiceInterface s) {
refreshControllers();
broadcastState();
}
/*
* Refresh the list of running services that can be selected in the GUI
*/
public ArrayList<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(I2CController.class);
return controllers;
}
// TODO
// Implement MotorController
/**
* This set of methods is used to set i2c parameters
*
* @param controllerName
* = The name of the i2c controller
* @param deviceBus
* = i2c bus Should be "1" for Arduino and RasPi
* "0"-"7" for I2CMux
* @param deviceAddress
* = The i2c address of the PCA9685 ( "0x40" - "0x5F")
* @return
*/
// @Override
public boolean setController(String controllerName, String deviceBus, String deviceAddress) {
return setController((I2CController) Runtime.getService(controllerName), deviceBus, deviceAddress);
}
public boolean setController(String controllerName) {
return setController((I2CController) Runtime.getService(controllerName), this.deviceBus, this.deviceAddress);
}
@Override
public boolean setController(I2CController controller) {
return setController(controller, this.deviceBus, this.deviceAddress);
}
@Override
public void setController(DeviceController controller) {
setController(controller);
}
public boolean setController(I2CController controller, String deviceBus, String deviceAddress) {
if (controller == null) {
error("setting null as controller");
return false;
}
controllerName = controller.getName();
log.info(String.format("%s setController %s", getName(), controllerName));
controllerName = controller.getName();
this.controller = controller;
this.deviceBus = deviceBus;
this.deviceAddress = deviceAddress;
isControllerSet = true;
broadcastState();
return true;
}
@Override
public void unsetController() {
controller = null;
this.deviceBus = null;
this.deviceAddress = null;
isControllerSet = false;
broadcastState();
}
@Override
public void setDeviceBus(String deviceBus) {
this.deviceBus = deviceBus;
broadcastState();
}
@Override
public void setDeviceAddress(String deviceAddress) {
if (controller != null) {
if (this.deviceAddress != deviceAddress) {
controller.releaseI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
controller.createI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
}
}
log.info(String.format("Setting device address to %s", deviceAddress));
this.deviceAddress = deviceAddress;
}
public void begin() {
byte[] buffer = { PCA9685_MODE1, 0x0 };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
// @Override
public boolean isAttached() {
return controller != null;
}
/**
* Set the PWM pulsewidth
*
* @param pin
* @param pulseWidthOn
* @param pulseWidthOff
*/
public void setPWM(Integer pin, Integer pulseWidthOn, Integer pulseWidthOff) {
byte[] buffer = { (byte) (PCA9685_LED0_ON_L + (pin * 4)), (byte) (pulseWidthOn & 0xff), (byte) (pulseWidthOn >> 8), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
/**
* Set the PWM frequency i.e. the frequency between positive pulses.
*
* @param hz
*/
public void setPWMFreq(Integer hz) { // Analog servos run at ~60 Hz updates
log.info(String.format("servoPWMFreq %s hz", hz));
int prescale_value = Math.round(osc_clock / precision / hz) - 1;
// Set sleep mode before changing PWM freqency
byte[] buffer1 = { PCA9685_MODE1, PCA9685_SLEEP };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer1, buffer1.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
// Write the PWM frequency value
byte[] buffer2 = { PCA9685_PRESCALE, (byte) prescale_value };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer2, buffer2.length);
// Leave sleep mode, set autoincrement to be able to write several
// bytes
// in sequence
byte[] buffer3 = { PCA9685_MODE1, PCA9685_AUTOINCREMENT };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer3, buffer3.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
}
public void setServo(Integer pin, Integer pulseWidthOff) {
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("setServo %s deviceAddress %S pin %s pulse %s", pin, deviceAddress, pin, pulseWidthOff));
byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
/**
* this would have been nice to have Java 8 and a default implmentation in
* this interface which does Servo sweeping in the Servo (already implmented)
* and only if the controller can does it do sweeping on the "controller"
*
* For example MrlComm can sweep internally (or it used to be implemented)
*/
@Override
public void servoSweepStart(ServoControl servo) {
log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl");
}
@Override
public void servoSweepStop(ServoControl servo) {
log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl");
}
@Override
public void servoWrite(ServoControl servo) {
if (!pwmFreqSet) {
setPWMFreq(pwmFreq);
}
log.info(String.format("servoWrite %s deviceAddress %s targetOutput %d", servo.getName(), deviceAddress, servo.getTargetOutput()));
int pulseWidthOff = SERVOMIN + (int) (servo.getTargetOutput() * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180));
setServo(servo.getPin(), pulseWidthOff);
}
@Override
public void servoWriteMicroseconds(ServoControl servo, int uS) {
if (!pwmFreqSet) {
setPWMFreq(pwmFreq);
}
int pin = servo.getPin();
// 1000 ms => 150, 2000 ms => 600
int pulseWidthOff = (int) (uS * 0.45) - 300;
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(), deviceAddress, pin, pulseWidthOff));
byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
@Override
public boolean servoEventsEnabled(ServoControl servo, boolean enabled) {
// @GroG. What is this method supposed to do ?
// return arduino.servoEventsEnabled(servo, enabled);
// Grog says - if you want feedback from the microcontroller to say when a
// servo has stopped
// when its moving at sub speed ...
// perhaps cannot do this with Adafruit16CServoDriver
// Mats says - We don't have any feedback from the servos, but to send
// an event when the sweep stops should not be a problem
return enabled;
}
@Override
public void servoSetSpeed(ServoControl servo) {
// TODO Auto-generated method stub.
// perhaps cannot do this with Adafruit16CServoDriver
// Mats says. It can be done in this service. But not by the board.
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName());
meta.addDescription("Adafruit 16-Channel PWM/Servo Driver");
meta.addCategory("shield", "servo & pwm");
meta.setSponsor("Mats");
/*
* meta.addPeer("arduino", "Arduino", "our Arduino"); meta.addPeer("raspi",
* "RasPi", "our RasPi");
*/
return meta;
}
/**
* Stop sending pulses to the servo, relax
*/
@Override
public void servoDetach(ServoControl servo) {
int pin = servo.getPin();
setPWM(pin, 4096, 0);
}
@Override
public DeviceController getController() {
return controller;
}
/**
* Device attach - this should be creating the I2C device on MRLComm for the
* "first" servo if not already created - Since this does not use the Arduino
* <Servo.h> servos - it DOES NOT need to create "Servo" devices in MRLComm.
* It will need to keep track of the "pin" to I2C address, and whenever a
* ServoControl.moveTo(79) - the Servo will tell this controller its name &
* location to move.
* Mats says. The board has a single i2c address that doesn't change.
* The Arduino only needs to keep track of the i2c bs, not all devices that can
* communicate thru it. I.e. This service should keep track of servos,
* not the Arduino or the Raspi.
*
*
* This service will translate the name & location to an I2C address & value
* write request to the MRLComm device.
*
* Mats comments on the above MRLComm should not know anything about the
* servos in this case. This service keeps track of the servos. MRLComm should
* not know anything about what addresses are used on the i2c bus MRLComm
* should initiate the i2c bus when it receives the first i2c write or read
* This service knows nothing about other i2c devices that can be on the same
* bus. And most important. This service knows nothing about MRLComm at all.
* I.e except for this bunch of comments :-)
*
* It implements the methods defined in the ServoController and translates the
* servo requests to i2c writes defined in the I2CControl interface
*
*/
/**
* if your device controller can provided several {Type}Controller interfaces,
* there might be commonality between all of them. e.g. initialization of data
* structures, preparing communication, sending control and config messages,
* etc.. - if there is commonality, it could be handled here - where Type
* specific methods call this method
*
* This is a software representation of a board that uses the i2c protocol.
* It uses the methods defined in the I2CController interface to write
* servo-commands.
* The I2CControl interface defines the common methods for all devices that use the
* i2c protocol.
* In most services I wiil define addition <device>Control methods, but this
* service is a "middle man" so it implements the ServoController methods and
* should not have any "own" methods.
*
* After our explanation of the roles of <device>Control and <device>Controller
* it's clear to me that any device that uses the i2c protocol needs to implement
* to <device>Control methods:
* I2CControl that is the generic interface for any i2c device
* <device>Control, that defines the specific methods for that device.
* For example the MPU6050 should implement both I2CControl and MPU6050Control
* or perhaps a AccGyroControl interface that would define the common methods
* that a Gyro/Accelerometer/Magnetometer device should implement.
*/
// FIXME how many do we want to support ??
// this device attachment is overloaded on the Arduino side ...
// Currently its only Servo, but it's also possible to implement
// MotorController and any device that requires pwm, like a LED dimmer.
@Override
public void deviceAttach(DeviceControl device, Object... conf) throws Exception {
// only need to handle servos :)
// this is easy
ServoControl servo = (ServoControl) device;
// servo.setController(this); Do not set any "ServoControl" data like this
// Not necessary
// should initial pos be a requirement ?
// This will fail because the pin data has not yet been set in Servo
// servoNameToPin.put(servo.getName(), servo.getPin());
int pin = (int)conf[0];
servoNameToPin.put(servo.getName(), pin);
}
@Override
public void deviceDetach(DeviceControl servo) {
// de-energize pin
servoDetach((ServoControl) servo);
servoNameToPin.remove(servo.getName());
}
@Override
public void servoAttach(ServoControl servo, int pin) {
// TODO Auto-generated method stub
}
} |
/*
*
* Adafruit16CServoDriver
*
* TODO - test with Steppers & Motors - switches on board - interface accepts motor control
*
*/
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.motor.MotorConfig;
import org.myrobotlab.motor.MotorConfigDualPwm;
import org.myrobotlab.motor.MotorConfigSimpleH;
import org.myrobotlab.motor.MotorConfigPulse;
import org.myrobotlab.service.interfaces.DeviceControl;
import org.myrobotlab.service.interfaces.DeviceController;
import org.myrobotlab.service.interfaces.I2CControl;
import org.myrobotlab.service.interfaces.I2CController;
import org.myrobotlab.service.interfaces.PinDefinition;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.MotorController;
import org.slf4j.Logger;
public class Adafruit16CServoDriver extends Service implements I2CControl, ServoController, MotorController {
/** version of the library */
static public final String VERSION = "0.9";
private static final long serialVersionUID = 1L;
// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos
// you have!
public final static int SERVOMIN = 150; // this
// the
// 'minimum'
// pulse
// length count (out of 4096)
public final static int SERVOMAX = 600; // this
// the
// 'maximum'
// pulse
// length count (out of 4096)
transient public I2CController controller;
// Constant for default PWM freqency
private static int pwmFreq = 60;
final static int minPwmFreq = 24;
final static int maxPwmFreq = 1526;
// List of possible addresses. Used by the GUI.
public List<String> deviceAddressList = Arrays.asList("0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B",
"0x4C", "0x4D", "0x4E", "0x4F", "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59",
"0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F");
// Default address
public String deviceAddress = "0x40";
/**
* This address is to address all Adafruit16CServoDrivers on the i2c bus Don't
* use this address for any other device on the i2c bus since it will cause
* collisions.
*/
public String broadcastAddress = "0x70";
public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7");
public String deviceBus = "1";
public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName());
public static final int PCA9685_MODE1 = 0x00; // Mod
// register
public static final byte PCA9685_SLEEP = 0x10; // Set
// sleep
// mode,
// before
// changing
// prescale
// value
public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set
// autoincrement
// able
// write
// more
// than
// one
// byte
// sequence
public static final byte PCA9685_PRESCALE = (byte) 0xFE; // PreScale
// register
// Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0
// The rest of the addresses are calculated based on pin numbers
public static final int PCA9685_LED0_ON_L = 0x06; // First
// LED
// address
// Low
public static final int PCA9685_LED0_ON_H = 0x07; // First
// LED
// address
// High
public static final int PCA9685_LED0_OFF_L = 0x08; // First
// LED
// address
// Low
public static final int PCA9685_LED0_OFF_H = 0x08; // First
// LED
// addressHigh
// public static final int PWM_FREQ = 60; // default frequency for servos
public static final float osc_clock = 25000000; // clock
// frequency
// the
// internal
// clock
public static final float precision = 4096; // pwm_precision
// i2c controller
public List<String> controllers;
public String controllerName;
public boolean isControllerSet = false;
/**
* @Mats - added by GroG - was wondering if this would help, probably you need
* a reverse index too ?
* @GroG - I only need servoNameToPin yet. To be able to sweep some more
* values may be needed
*/
class ServoData {
int pin;
boolean pwmFreqSet = false;
int pwmFreq;
float sweepMin = 0;
float sweepMax = 180;
float sweepDelay = 1;
int sweepStep = 1;
boolean isSweeping = false;
boolean sweepOneWay = false;
}
transient HashMap<String, ServoData> servoMap = new HashMap<String, ServoData>();
// Motor related constants
public static final int MOTOR_FORWARD = 1;
public static final int MOTOR_BACKWARD = 0;
public static final int defaultMotorPwmFreq = 1000;
/**
* pin named map of all the pins on the board
*/
Map<String, PinDefinition> pinMap = null;
/**
* the definitive sequence of pins - "true address"
*/
Map<Integer, PinDefinition> pinIndex = null;
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver");
log.info("Driver {}", driver);
}
public Adafruit16CServoDriver(String n) {
super(n);
createPinList();
refreshControllers();
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
}
public void onRegistered(ServiceInterface s) {
refreshControllers();
broadcastState();
}
/*
* Refresh the list of running services that can be selected in the GUI
*/
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(I2CController.class);
return controllers;
}
// TODO
// Implement MotorController
/**
* This set of methods is used to set i2c parameters
*
* @param controllerName
* = The name of the i2c controller
* @param deviceBus
* = i2c bus Should be "1" for Arduino and RasPi "0"-"7" for I2CMux
* @param deviceAddress
* = The i2c address of the PCA9685 ( "0x40" - "0x5F")
* @return
*/
// @Override
public boolean setController(String controllerName, String deviceBus, String deviceAddress) {
return setController((I2CController) Runtime.getService(controllerName), deviceBus, deviceAddress);
}
public boolean setController(String controllerName) {
return setController((I2CController) Runtime.getService(controllerName), this.deviceBus, this.deviceAddress);
}
@Override
public boolean setController(I2CController controller) {
return setController(controller, this.deviceBus, this.deviceAddress);
}
@Override
public void setController(DeviceController controller) {
setController(controller);
}
public boolean setController(I2CController controller, String deviceBus, String deviceAddress) {
if (controller == null) {
error("setting null as controller");
return false;
}
controllerName = controller.getName();
log.info(String.format("%s setController %s", getName(), controllerName));
controllerName = controller.getName();
this.controller = controller;
this.deviceBus = deviceBus;
this.deviceAddress = deviceAddress;
createDevice();
isControllerSet = true;
broadcastState();
return true;
}
@Override
public void unsetController() {
controller = null;
this.deviceBus = null;
this.deviceAddress = null;
isControllerSet = false;
broadcastState();
}
@Override
public void setDeviceBus(String deviceBus) {
this.deviceBus = deviceBus;
broadcastState();
}
@Override
public void setDeviceAddress(String deviceAddress) {
if (controller != null) {
if (this.deviceAddress != deviceAddress) {
controller.releaseI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
controller.createI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
}
}
log.info(String.format("Setting device address to %s", deviceAddress));
this.deviceAddress = deviceAddress;
}
/**
* This method creates the i2c device
*/
boolean createDevice() {
if (controller != null) {
// controller.releaseI2cDevice(this, Integer.parseInt(deviceBus),
// Integer.decode(deviceAddress));
controller.createI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
}
else {
log.error("Can't create device until the controller has been set");
return false;
}
log.info(String.format("Creating device on bus: %s address %s", deviceBus, deviceAddress));
return true;
}
// @Override
// boolean DeviceControl.isAttached()
public boolean isAttached() {
return controller != null;
}
/**
* Set the PWM pulsewidth
*
* @param pin
* @param pulseWidthOn
* @param pulseWidthOff
*/
public void setPWM(Integer pin, Integer pulseWidthOn, Integer pulseWidthOff) {
byte[] buffer = { (byte) (PCA9685_LED0_ON_L + (pin * 4)), (byte) (pulseWidthOn & 0xff), (byte) (pulseWidthOn >> 8), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
/**
* Set the PWM frequency i.e. the frequency between positive pulses.
*
* @param hz
*/
public void setPWMFreq(int pin, Integer hz) { // Analog servos run at ~60 Hz
float prescale_value;
if (hz < minPwmFreq) {
log.error(String.format("Minimum PWMFreq is %s Hz, requested freqency is %s Hz, clamping to minimum", minPwmFreq, hz));
hz = minPwmFreq;
prescale_value = 255;
} else if (hz > maxPwmFreq) {
log.error(String.format("Maximum PWMFreq is %s Hz, requested frequency is %s Hz, clamping to maximum", maxPwmFreq, hz));
hz = maxPwmFreq;
prescale_value = 3;
} else {
prescale_value = Math.round(osc_clock / precision / hz) - 1;
}
log.info(String.format("PWMFreq %s hz, prescale_value calculated to %s", hz, prescale_value));
// Set sleep mode before changing PWM freqency
byte[] writeBuffer = { PCA9685_MODE1, PCA9685_SLEEP };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), writeBuffer, writeBuffer.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
if (Thread.interrupted()) { // Clears interrupted status!
}
}
// Write the PWM frequency value
byte[] buffer2 = { PCA9685_PRESCALE, (byte) prescale_value };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer2, buffer2.length);
// Leave sleep mode, set autoincrement to be able to write several
// bytes
// in sequence
byte[] buffer3 = { PCA9685_MODE1, PCA9685_AUTOINCREMENT };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer3, buffer3.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
}
public void setServo(Integer pin, Integer pulseWidthOff) {
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("setServo %s deviceAddress %s pin %s pulse %s", pin, deviceAddress, pin, pulseWidthOff));
byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
/**
* this would have been nice to have Java 8 and a default implementation in
* this interface which does Servo sweeping in the Servo (already implemented)
* and only if the controller can does it do sweeping on the "controller"
*
* For example MrlComm can sweep internally (or it used to be implemented)
*/
@Override
public void servoSweepStart(ServoControl servo) {
log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl");
}
@Override
public void servoSweepStop(ServoControl servo) {
log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl");
}
@Override
public void servoWrite(ServoControl servo) {
ServoData servoData = servoMap.get(servo.getName());
if (!servoData.pwmFreqSet) {
setPWMFreq(servoData.pin, servoData.pwmFreq);
servoData.pwmFreqSet = true;
}
log.debug(String.format("servoWrite %s deviceAddress %s targetOutput %d", servo.getName(), deviceAddress, servo.getTargetOutput()));
int pulseWidthOff = SERVOMIN + (int) (servo.getTargetOutput() * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180));
setServo(servo.getPin(), pulseWidthOff);
}
@Override
public void servoWriteMicroseconds(ServoControl servo, int uS) {
ServoData servoData = servoMap.get(servo.getName());
if (!servoData.pwmFreqSet) {
setPWMFreq(servoData.pin, servoData.pwmFreq);
servoData.pwmFreqSet = true;
}
int pin = servo.getPin();
// 1000 ms => 150, 2000 ms => 600
int pulseWidthOff = (int) (uS * 0.45) - 300;
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(), deviceAddress, pin, pulseWidthOff));
byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
@Override
public DeviceController getController() {
return controller;
}
/**
* Device attach - this should be creating the I2C bus on MRLComm for the
* "first" servo if not already created - Since this does not use the Arduino
* <Servo.h> servos - it DOES NOT need to create "Servo" devices in MRLComm.
* It will need to keep track of the "pin" to I2C address, and whenever a
* ServoControl.moveTo(pos) - the Servo will tell this controller its name &
* location to move. Mats says. The board has a single i2c address that
* doesn't change. The Arduino only needs to keep track of the i2c bus, not
* all devices that can communicate thru it. I.e. This service should keep
* track of servos, not the Arduino or the Raspi.
*
*
* This service will translate the name & location to an I2C address & value
* write request to the MRLComm device.
*
* Mats comments on the above. MRLComm should not know anything about the
* servos in this case. This service keeps track of the servos. MRLComm should
* not know anything about what addresses are used on the i2c bus MRLComm
* should initiate the i2c bus when it receives the first i2c write or read
* This service knows nothing about other i2c devices that can be on the same
* bus. And most important. This service knows nothing about MRLComm at all.
* I.e except for this bunch of comments :-)
*
* It implements the methods defined in the ServoController and translates the
* servo requests to i2c writes defined in the I2CControl interface
*
*/
/**
* if your device controller can provided several {Type}Controller interfaces,
* there might be commonality between all of them. e.g. initialization of data
* structures, preparing communication, sending control and config messages,
* etc.. - if there is commonality, it could be handled here - where Type
* specific methods call this method
*
* This is a software representation of a board that uses the i2c protocol. It
* uses the methods defined in the I2CController interface to write
* servo-commands. The I2CController interface defines the common methods for
* all devices that use the i2c protocol. In most services I will define
* addition <device>Control methods, but this service is a "middle man" so it
* implements the ServoController methods and should not have any "own"
* methods.
*
* After our explanation of the roles of <device>Control and
* <device>Controller it's clear to me that any device that uses the i2c
* protocol needs to implement to <device>Control methods: I2CControl that is
* the generic interface for any i2c device <device>Control, that defines the
* specific methods for that device. For example the MPU6050 should implement
* both I2CControl and MPU6050Control or perhaps a AccGyroControl interface
* that would define the common methods that a Gyro/Accelerometer/Magnetometer
* device should implement.
*/
// FIXME how many do we want to support ??
// this device attachment is overloaded on the Arduino side ...
// Currently its only Servo, but it's also possible to implement
// MotorController and any device that requires pwm, like a LED dimmer.
@Override
public void deviceAttach(DeviceControl device, Object... conf) throws Exception {
if (device instanceof ServoControl) {
servoAttach((ServoControl) device, conf);
}
if (device instanceof MotorControl) {
motorAttach((MotorControl) device, conf);
}
}
void servoAttach(ServoControl device, Object... conf) {
ServoControl servo = (ServoControl) device;
// should initial pos be a requirement ?
// This will fail because the pin data has not yet been set in Servo
// servoNameToPin.put(servo.getName(), servo.getPin());
String servoName = servo.getName();
ServoData servoData = new ServoData();
servoData.pin = (int) conf[0];
servoData.pwmFreqSet = false;
servoData.pwmFreq = pwmFreq;
servoMap.put(servoName, servoData);
invoke("publishAttachedDevice", servoName);
}
void motorAttach(MotorControl device, Object... conf) {
/*
* This is where motor data could be initialized. So far all motor data this
* service needs can be requested from the motors config
*/
MotorControl motor = (MotorControl) device;
invoke("publishAttachedDevice", motor.getName());
}
@Override
public void deviceDetach(DeviceControl servo) {
servoDetach((ServoControl) servo);
servoMap.remove(servo.getName());
}
public String publishAttachedDevice(String deviceName) {
return deviceName;
}
/**
* Start sending pulses to the servo
*
*/
@Override
public void servoAttach(ServoControl servo, int pin) {
servoWrite(servo);
}
/**
* Stop sending pulses to the servo, relax
*/
@Override
public void servoDetach(ServoControl servo) {
int pin = servo.getPin();
setPWM(pin, 4096, 0);
}
@Override
public void servoSetMaxVelocity(ServoControl servo) {
// TODO Auto-generated method stub.
// perhaps cannot do this with Adafruit16CServoDriver
// Mats says: It can be done in this service. But not by the board.
}
@Override
public void motorMove(MotorControl mc) {
MotorConfig c = mc.getConfig();
if (c == null) {
error("motor config not set");
return;
}
Class<?> type = mc.getConfig().getClass();
double powerOutput = mc.getPowerOutput();
if (MotorConfigSimpleH.class == type) {
MotorConfigSimpleH config = (MotorConfigSimpleH) c;
if (config.getPwmFreq() == null) {
config.setPwmFreq(defaultMotorPwmFreq);
setPWMFreq(config.getPwrPin(), config.getPwmFreq());
}
setPinValue(config.getDirPin(), (powerOutput < 0) ? MOTOR_BACKWARD : MOTOR_FORWARD);
setPinValue(config.getPwrPin(), powerOutput);
} else if (MotorConfigDualPwm.class == type) {
MotorConfigDualPwm config = (MotorConfigDualPwm) c;
log.info(String.format("Adafruti16C Motor DualPwm motorMove, powerOutput = %s", powerOutput));
if (config.getPwmFreq() == null) {
config.setPwmFreq(defaultMotorPwmFreq);
setPWMFreq(config.getLeftPin(), config.getPwmFreq());
setPWMFreq(config.getRightPin(), config.getPwmFreq());
}
if (powerOutput < 0) {
setPinValue(config.getLeftPin(), 0);
setPinValue(config.getRightPin(), Math.abs(powerOutput / 255));
} else if (powerOutput > 0) {
setPinValue(config.getRightPin(), 0);
setPinValue(config.getLeftPin(), Math.abs(powerOutput / 255));
} else {
setPinValue(config.getRightPin(), 0);
setPinValue(config.getLeftPin(), 0);
}
} else if (MotorPulse.class == type) {
MotorPulse motor = (MotorPulse) mc;
// sendMsg(ANALOG_WRITE, motor.getPin(Motor.PIN_TYPE_PWM_RIGHT),
// TODO implement with a -1 for "endless" pulses or a different
// command parameter :P
// TODO Change to setPwmFreq I guess
// setPwmFreq(motor.getPulsePin(), (int) Math.abs(powerOutput));
} else {
error("motorMove for motor type %s not supported", type);
}
}
@Override
public void motorMoveTo(MotorControl mc) {
// speed parameter?
// modulo - if < 1
// speed = 1 else
log.info("motorMoveTo targetPos {} powerLevel {}", mc.getTargetPos(), mc.getPowerLevel());
Class<?> type = mc.getClass();
// if pulser (with or without fake encoder
// send a series of pulses !
// with current direction
if (MotorPulse.class == type) {
MotorPulse motor = (MotorPulse) mc;
// check motor direction
// send motor direction
// TODO powerLevel = 100 * powerlevel
// FIXME !!! - this will have to send a Long for targetPos at some
// point !!!!
double target = Math.abs(motor.getTargetPos());
int b0 = (int) target & 0xff;
int b1 = ((int) target >> 8) & 0xff;
int b2 = ((int) target >> 16) & 0xff;
int b3 = ((int) target >> 24) & 0xff;
// TODO FIXME
// sendMsg(PULSE, deviceList.get(motor.getName()).id, b3, b2, b1,
// b0, (int) motor.getPowerLevel(), feedbackRate);
}
}
@Override
public void motorStop(MotorControl mc) {
MotorConfig c = mc.getConfig();
if (c == null) {
error("motor config not set");
return;
}
Class<?> type = mc.getConfig().getClass();
if (MotorConfigPulse.class == type) {
MotorConfigPulse config = (MotorConfigPulse) mc.getConfig();
setPinValue(config.getPulsePin(), 0);
} else if (MotorConfigSimpleH.class == type) {
MotorConfigSimpleH config = (MotorConfigSimpleH) mc.getConfig();
if (config.getPwmFreq() == null) {
config.setPwmFreq(500);
setPWMFreq(config.getPwrPin(), config.getPwmFreq());
}
setPinValue(config.getPwrPin(), 0);
} else if (MotorConfigDualPwm.class == type) {
MotorConfigDualPwm config = (MotorConfigDualPwm) mc.getConfig();
setPinValue(config.getLeftPin(), 0);
setPinValue(config.getRightPin(), 0);
}
}
@Override
public void motorReset(MotorControl motor) {
// perhaps this should be in the motor control
// motor.reset();
// opportunity to reset variables on the controller
// sendMsg(MOTOR_RESET, motor.getind);
}
public void setPinValue(int pin, double powerOutput) {
log.info(String.format("Adafruit16C setPinValue, pin = %s, powerOutput = %s", pin, powerOutput));
if (powerOutput < 0) {
log.error(String.format("Adafruit16CServoDriver setPinValue. Value below zero (%s). Defaulting to 0.", powerOutput));
powerOutput = 0;
} else if (powerOutput > 1) {
log.error(String.format("Adafruit16CServoDriver setPinValue. Value > 1 (%s). Defaulting to 1", powerOutput));
powerOutput = 1;
}
int powerOn;
int powerOff;
// No phase shift. Simple calculation
if (powerOutput == 0) {
powerOn = 4096;
powerOff = 0;
} else if (powerOutput == 1){
powerOn= 0;
powerOff = 1;
}
else {
powerOn = (int) (powerOutput * 4096);
powerOff = 4095;
}
log.info(String.format("powerOutput = %s, powerOn = %s, powerOff = %s", powerOutput, powerOn, powerOff));
setPWM(pin, powerOn, powerOff);
}
public List<PinDefinition> getPinList() {
List<PinDefinition> list = new ArrayList<PinDefinition>(pinIndex.values());
return list;
}
public Map<String, PinDefinition> createPinList() {
pinIndex = new HashMap<Integer, PinDefinition>();
for (int i = 0; i < 16; ++i) {
PinDefinition pindef = new PinDefinition();
String name = null;
name = String.format("D%d", i);
pindef.setDigital(true);
pindef.setName(name);
pindef.setAddress(i);
pinIndex.put(i, pindef);
}
return pinMap;
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName());
meta.addDescription("Adafruit 16-Channel PWM/Servo Driver");
meta.addCategory("shield", "servo & pwm");
meta.setSponsor("Mats");
/*
* meta.addPeer("arduino", "Arduino", "our Arduino"); meta.addPeer("raspi",
* "RasPi", "our RasPi");
*/
return meta;
}
@Override
public void servoSetVelocity(ServoControl servo) {
// TODO Auto-generated method stub
}
} |
package org.obd.ws.resources;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.bbop.dataadapter.DataAdapterException;
import org.json.JSONException;
import org.json.JSONObject;
import org.obd.query.Shard;
import org.obd.ws.exceptions.PhenoscapeTreeAssemblyException;
import org.obd.ws.util.Queries;
import org.obd.ws.util.TTOTaxonomy;
import org.obd.ws.util.TaxonTree;
import org.obd.ws.util.TaxonomyBuilder;
import org.obd.ws.util.dto.NodeDTO;
import org.obd.ws.util.dto.PhenotypeDTO;
import org.phenoscape.obd.OBDQuery;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
public class PhenotypeDetailsResource extends Resource {
Logger log = Logger.getLogger(this.getClass());
private String subject_id;
private String entity_id;
private String character_id;
private String publication_id;
private String type;
private String group;
private Map<String, String> parameters;
Map<String, String> queryResultsFilterSpecs;
private JSONObject jObjs;
private Shard obdsql;
private OBDQuery obdq;
private Queries queries;
private TTOTaxonomy ttoTaxonomy;
private TaxonomyBuilder taxonomyBuilder;
/**
* This constructor reads in objects from the application context, initializes
* instance variables and reads in the form data into the instance variables
* @param context
* @param request
* @param response
* @throws IOException
* @throws DataAdapterException
*/
public PhenotypeDetailsResource(Context context, Request request, Response response) throws IOException, DataAdapterException {
super(context, request, response);
this.obdsql = (Shard) this.getContext().getAttributes().get("shard");
this.ttoTaxonomy = (TTOTaxonomy)this.getContext().getAttributes().get("ttoTaxonomy");
this.getVariants().add(new Variant(MediaType.APPLICATION_JSON));
if(request.getResourceRef().getQueryAsForm().getFirstValue("subject") != null){
this.subject_id = Reference.decode((String) (request.getResourceRef().getQueryAsForm().getFirstValue("subject")));
}
if(request.getResourceRef().getQueryAsForm().getFirstValue("entity") != null){
this.entity_id = Reference.decode((String)(request.getResourceRef().getQueryAsForm().getFirstValue("entity")));
}
if(request.getResourceRef().getQueryAsForm().getFirstValue("quality") != null){
this.character_id = Reference.decode((String)(request.getResourceRef().getQueryAsForm().getFirstValue("quality")));
}
if(request.getResourceRef().getQueryAsForm().getFirstValue("publication") != null){
this.publication_id = Reference.decode((String)(request.getResourceRef().getQueryAsForm().getFirstValue("publication")));
}
if(request.getResourceRef().getQueryAsForm().getFirstValue("type") != null){
this.type = Reference.decode((String)(request.getResourceRef().getQueryAsForm().getFirstValue("type")));
}
if(request.getResourceRef().getQueryAsForm().getFirstValue("group") != null){
this.group = Reference.decode((String)(request.getResourceRef().getQueryAsForm().getFirstValue("group")));
}
queries = new Queries(obdsql);
obdq = new OBDQuery(obdsql);
jObjs = new JSONObject();
parameters = new HashMap<String, String>();
queryResultsFilterSpecs = new HashMap<String, String>();
}
/**
* This method is responsible for generating the object
* which is output at the endpoint interface. It calls methods
* which check the input form data, execute the query and
* process the results into a JSON object for delivery to
* the client
*
*/
public Representation represent(Variant variant)
throws ResourceException {
Representation rep;
Map<NodeDTO, List<List<String>>> annots;
if(!checkInputFormParameters()){
this.jObjs = null;
return null;
}
try{
annots = getAnnotations();
}
/* 'getAnnotations' method returns null in case of a server side exception*/
catch(SQLException sqle){
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,
"[SQL EXCEPTION] Something broke server side. Consult server logs");
return null;
} catch (IOException e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,
"[IO EXCEPTION] Something broke server side. Consult server logs");
return null;
} catch (DataAdapterException e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,
"[DATA ADAPTER EXCEPTION] Something broke server side. Consult server logs");
return null;
} catch (PhenoscapeTreeAssemblyException e){
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,
"[TREE ASSEMBLY EXCEPTION] Something broke server side. Consult server logs");
return null;
}
try{
this.jObjs = this.assembleJSONObjectFromDataStructure(annots);
}
catch(ResourceException e){
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST,
"[RESOURCE EXCEPTION] Something broke in the JSON Object. Consult server logs");
return null;
}
rep = new JsonRepresentation(this.jObjs);
return rep;
}
/**
* @PURPOSE: This method takes the nodes returned by OBDQuery class and packages them into a
* data structure, which will be processed by the caller {@link represent} method
* @return
* @throws SQLException
* @throws IOException
* @throws DataAdapterException
* @throws PhenoscapeTreeAssemblyException
*/
private Map<NodeDTO, List<List<String>>>
getAnnotations()
throws SQLException, IOException, DataAdapterException, PhenoscapeTreeAssemblyException{
Map<NodeDTO, List<List<String>>> taxonToAssertionsMap = new HashMap<NodeDTO, List<List<String>>>();
List<String> queryAndSearchTerm = assembleQueryAndSearchTerm();
String query = queryAndSearchTerm.get(0);
String searchTerm = queryAndSearchTerm.get(1);
log.trace("Search Term: " + searchTerm + " Query: " + query);
try{
Collection<PhenotypeDTO> phenotypeColl =
obdq.executeQueryAndAssembleResults(query, searchTerm, queryResultsFilterSpecs);
if(type != null)
phenotypeColl = filterCollectionByType(phenotypeColl, type);
if(type != null && type.equals("evo") && group != null){
taxonToAssertionsMap =
generateTreeBasedDataStructureFromAssertions(taxonToAssertionsMap, phenotypeColl);
}
else{
taxonToAssertionsMap =
generateSimpleDataStructureFromAssertions(taxonToAssertionsMap, phenotypeColl);
}
}
catch(SQLException e){
log.fatal(e);
throw e;
} catch (IOException e) {
log.fatal(e);
throw e;
} catch (DataAdapterException e) {
log.fatal(e);
throw e;
} catch(PhenoscapeTreeAssemblyException e){
log.fatal(e);
throw e;
}
return taxonToAssertionsMap;
}
/**
* A method to check if the input parameters are
* valid
* @return - a boolean to indicate validity of input
* form parameters
*/
private boolean checkInputFormParameters(){
if (subject_id != null && !subject_id.startsWith("TTO:") && !subject_id.contains("GENE")) {
getResponse().setStatus(
Status.CLIENT_ERROR_BAD_REQUEST,
"ERROR: The input parameter for subject "
+ "is not a recognized taxon or gene");
return false;
}
/* Commenting out this section to let post compositions work - Cartik 06/03/09
if(entity_id != null && !entity_id.startsWith("TAO:") && !entity_id.startsWith("ZFA:")){
this.jObjs = null;
getResponse().setStatus(
Status.CLIENT_ERROR_BAD_REQUEST,
"ERROR: The input parameter for entity "
+ "is not a recognized anatomical entity");
return null;
}
*/
if(character_id != null && !character_id.startsWith("PATO:")){
getResponse().setStatus(
Status.CLIENT_ERROR_BAD_REQUEST,
"ERROR: The input parameter for quality "
+ "is not a recognized PATO quality");
return false;
}
if(type != null && !type.equals("evo") && !type.equals("devo")){
getResponse().setStatus(
Status.CLIENT_ERROR_BAD_REQUEST,
"ERROR: [INVALID PARAMETER] The input parameter for taxon type can only be "
+ "'evo' or 'devo'");
return false;
}
if(group != null && !group.equals("root") && !group.matches("TTO:[0-9]+")){
getResponse().setStatus(
Status.CLIENT_ERROR_BAD_REQUEST,
"ERROR: [INVALID PARAMETER] The input parameter for group can only be "
+ "'root' or a valid TTO taxon");
return false;
}
//TODO Publication ID check
parameters.put("entity_id", entity_id);
parameters.put("quality_id", character_id);
parameters.put("subject_id", subject_id);
parameters.put("publication_id", publication_id);
for(String key : parameters.keySet()){
if(parameters.get(key) != null){
if(obdsql.getNode(parameters.get(key)) == null){
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND,
"No annotations were found with the specified search parameters");
return false;
}
}
}
return true;
}
/**
* This method takes an input data structure and translates it
* into a JSON Object
* @param annots - the input data structure
* @return
* @throws ResourceException
*/
private JSONObject assembleJSONObjectFromDataStructure
(Map<NodeDTO, List<List<String>>> annots)
throws ResourceException{
JSONObject subjectObj, qualityObj, entityObj, phenotypeObj;
List<JSONObject> phenotypeObjs;
List<JSONObject> subjectObjs = new ArrayList<JSONObject>();
JSONObject result = new JSONObject();
try{
for(NodeDTO taxonDTO : annots.keySet()){
subjectObj = new JSONObject();
subjectObj.put("id", taxonDTO.getId());
subjectObj.put("name", taxonDTO.getName());
phenotypeObjs = new ArrayList<JSONObject>();
for(List<String> phenotype : annots.get(taxonDTO)){
String count = phenotype.get(4);
if(count == null)
count = "";
entityObj = new JSONObject();
entityObj.put("id", phenotype.get(0));
entityObj.put("name", phenotype.get(1));
qualityObj = new JSONObject();
qualityObj.put("id", phenotype.get(2));
qualityObj.put("name", phenotype.get(3));
phenotypeObj = new JSONObject();
phenotypeObj.put("entity", entityObj);
phenotypeObj.put("quality", qualityObj);
phenotypeObj.put("count", count);
phenotypeObj.put("id", phenotype.get(5));
phenotypeObjs.add(phenotypeObj);
}
subjectObj.put("phenotypes", phenotypeObjs);
subjectObjs.add(subjectObj);
}
log.trace(annots.size() + " annotations returned");
result.put("subjects", subjectObjs);
}
catch(JSONException jsone){
log.error(jsone);
throw new ResourceException(jsone);
}
return result;
}
/**
* A helper method which crea6tes a query based upon the
* input parameters and sets up the filter options as well
* @return - a two member list comprising the final query and
* the search term for the query
*/
private List<String> assembleQueryAndSearchTerm(){
String query, searchTerm;
if(subject_id != null){
if(subject_id.contains("GENE"))
query = queries.getGeneQuery();
else
query = queries.getTaxonQuery();
searchTerm = subject_id;
if(entity_id != null){
query += " AND entity_uid = '" + entity_id + "'";
}
// queryResultsFilterSpecs.put("entity", entity_id);
}
else{
query = queries.getAnatomyQuery();
/* neither subject or entity are provided. so we use the root TAO term
* which returns every phenotype in the database
*/
searchTerm = (entity_id != null ? entity_id : "TAO:0100000");
}
if(character_id != null){
query += " AND character_uid = '" + character_id + "'";
}
//queryResultsFilterSpecs.put("character", character_id);
queryResultsFilterSpecs.put("publication", null); //TODO pub_id goes here;
return Arrays.asList(new String[]{query, searchTerm});
}
/**
* @PURPOSE This method uses an input collection of taxon to
* phenotype assertions to create a data structure, which is
* passed to the calling {@link getAnnotations} method
* @param taxonToAssertionsMap - the data structure to be updated
* @param phenotypeColl - the input set of taxon to phenotype assertions
* @return - the input data structure after updates from the input set of
* taxon to phenotype assertions
* @throws IOException
* @throws DataAdapterException
* @throws PhenoscapeTreeAssemblyException
*/
private Map<NodeDTO, List<List<String>>>
generateTreeBasedDataStructureFromAssertions(
Map<NodeDTO, List<List<String>>> taxonToAssertionsMap,
Collection<PhenotypeDTO> phenotypeColl)
throws IOException, DataAdapterException, PhenoscapeTreeAssemblyException{
taxonomyBuilder = new TaxonomyBuilder(ttoTaxonomy, phenotypeColl);
TaxonTree taxonTree = taxonomyBuilder.getTree();
NodeDTO mrca = taxonTree.getMrca();
if(group.equals("root")){
List<List<String>> listOfEQCRLists =
taxonTree.getNodeToListOfEQCRListsMap().get(mrca);
taxonToAssertionsMap.put(mrca, listOfEQCRLists);
}else{
taxonToAssertionsMap = processChildrenOfGroupNodeFromInput(taxonToAssertionsMap);
}
return taxonToAssertionsMap;
}
/**
* This is a helper method that processes the annotations from the tree and returns them to
* calling {@link generateTreeBasedDataStructureFromAssertions} method
* @param taxonToAssertionsMap - the node to assertions map to be processed
* @return the processed node to assertions map
* @throws PhenoscapeTreeAssemblyException
*/
private Map<NodeDTO, List<List<String>>> processChildrenOfGroupNodeFromInput(
Map<NodeDTO,List<List<String>>> taxonToAssertionsMap) throws PhenoscapeTreeAssemblyException{
NodeDTO groupNodeFromInput = ttoTaxonomy.getIdToNodeMap().get(group);
TaxonTree tree = taxonomyBuilder.getTree();
Set<NodeDTO> children = tree.getNodeToChildrenMap().get(groupNodeFromInput);
if(children != null){
for(NodeDTO child : children){
List<List<String>> listOfEQCRLists =
tree.getNodeToListOfEQCRListsMap().get(child);
taxonToAssertionsMap.put(child, listOfEQCRLists);
}
}
else if(tree.getLeaves().contains(groupNodeFromInput)){
taxonToAssertionsMap = new HashMap<NodeDTO, List<List<String>>>();
}
else if(tree.getNodeToChildrenMap().get(tree.getMrca()) == null){
NodeDTO mrcaNode = tree.getMrca();
taxonToAssertionsMap.put(mrcaNode, tree.getNodeToListOfEQCRListsMap().get(mrcaNode));
}
else{
throw new PhenoscapeTreeAssemblyException("");
}
return taxonToAssertionsMap;
}
/**
* This method generates a simple Taxon to List of Phenotypes
* map from the input taxon to phenotype assertions, which is
* passed to the calling {@link getAnnotations} method
* @param taxonToAssertionsMap - the map from taxa to phenotype assertions
* @param phenotypeColl - the input collection of taxon to phenotype assertions
* @return
*/
private Map<NodeDTO, List<List<String>>>
generateSimpleDataStructureFromAssertions(
Map<NodeDTO, List<List<String>>> taxonToAssertionsMap,
Collection<PhenotypeDTO> phenotypeColl){
for(PhenotypeDTO phenotypeDTO : phenotypeColl){
NodeDTO taxonDTO = new NodeDTO(phenotypeDTO.getTaxonId());
taxonDTO.setName(phenotypeDTO.getTaxon());
List<List<String>> annotations = taxonToAssertionsMap.get(taxonDTO);
if(annotations == null)
annotations = new ArrayList<List<String>>();
annotations.add(Arrays.asList(new String[]{
phenotypeDTO.getEntityId(),
phenotypeDTO.getEntity(),
phenotypeDTO.getQualityId(),
phenotypeDTO.getQuality(),
phenotypeDTO.getNumericalCount(),
phenotypeDTO.getReifId()
}));
taxonToAssertionsMap.put(taxonDTO, annotations);
}
return taxonToAssertionsMap;
}
/**
* A method to filter the collection based upon
* the value of the "type" parameter
* @param phenotypeColl
* @param type - can be "evo" or "devo". This is set in the calling method
* @return input collection minus TTOs or GENEs depending on the value of the
* "type" parameter
*/
private Collection<PhenotypeDTO> filterCollectionByType(Collection<PhenotypeDTO> phenotypeColl, String type){
if(type.equals("evo"))
return filterGenesFromCollection(phenotypeColl);
else
return filterTaxaFromCollection(phenotypeColl);
}
/**
* A simple method that weeds out DTOs with TTOs as their taxa
* from the collection
* @param phenotypeColl
* @return input collection minus TTOs
*/
private Collection<PhenotypeDTO> filterTaxaFromCollection(
Collection<PhenotypeDTO> phenotypeColl) {
Collection<PhenotypeDTO> collectionToReturn = new ArrayList<PhenotypeDTO>();
for(PhenotypeDTO phenotypeDTO : phenotypeColl){
if(phenotypeDTO.getTaxonId().contains("GENE")){
collectionToReturn.add(phenotypeDTO);
}
}
return collectionToReturn;
}
/**
* A simple method that weeds out DTOs with GENEs as their taxa
* from the collection
* @param phenotypeColl
* @return input collection minus GENEs
*/
private Collection<PhenotypeDTO> filterGenesFromCollection(
Collection<PhenotypeDTO> phenotypeColl) {
Collection<PhenotypeDTO> collectionToReturn = new ArrayList<PhenotypeDTO>();
for(PhenotypeDTO phenotypeDTO : phenotypeColl){
if(phenotypeDTO.getTaxonId().contains("TTO")){
collectionToReturn.add(phenotypeDTO);
}
}
return collectionToReturn;
}
} |
package org.royaldev.royalcommands.runners;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.AFKUtils;
import org.royaldev.royalcommands.RoyalCommands;
import java.util.Date;
public class AFKWatcher implements Runnable {
RoyalCommands plugin;
public AFKWatcher(RoyalCommands instance) {
plugin = instance;
}
@Override
public void run() {
long afkKickTime = plugin.afkKickTime;
long afkAutoTime = plugin.afkAutoTime;
for (Player p : plugin.getServer().getOnlinePlayers()) {
long currentTime = new Date().getTime();
if (!AFKUtils.isAfk(p)) {
if (plugin.isVanished(p)) continue;
if (!AFKUtils.moveTimesContains(p)) continue;
if (afkAutoTime <= 0) continue;
long lastMove = AFKUtils.getLastMove(p);
if ((lastMove + (afkAutoTime * 1000)) < currentTime) {
AFKUtils.setAfk(p, currentTime);
plugin.getServer().broadcastMessage(p.getName() + " is now AFK.");
continue;
}
}
if (!AFKUtils.isAfk(p)) continue;
if (afkKickTime <= 0) continue;
long afkAt = AFKUtils.getAfkTime(p);
if (plugin.isAuthorized(p, "rcmds.exempt.afkkick")) return;
if (afkAt + (afkKickTime * 1000) >= currentTime) p.kickPlayer("You have been AFK for too long!");
}
}
} |
package pt.fccn.saw.selenium;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.NoSuchElementException;
import pt.fccn.saw.selenium.RetryRule;
import java.util.ArrayList;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.*;
import com.saucelabs.common.SauceOnDemandAuthentication;
import pt.fccn.saw.selenium.SauceHelpers;
import org.junit.*;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.openqa.selenium.remote.CapabilityType;
import com.saucelabs.junit.ConcurrentParameterized;
import com.saucelabs.junit.SauceOnDemandTestWatcher;
import java.net.URL;
import java.util.LinkedList;
import org.json.*;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;
import com.saucelabs.common.SauceOnDemandSessionIdProvider;
//import org.json.*;
/**
* The base class for tests using WebDriver to test specific browsers.
* This test read system properties to know which browser to test or,
* if tests are te be run remotely, it also read login information and
* the browser, browser version and OS combination to be used.
*
* The WebDriver tests provide the more precise results without the
* restrictions present in selenium due to browers' security models.
*/
@Ignore
@RunWith(ConcurrentParameterized.class)
public class WebDriverTestBaseParalell implements SauceOnDemandSessionIdProvider{
public String username = System.getenv("SAUCE_USERNAME");
public String accesskey = System.getenv("SAUCE_ACCESS_KEY");
public static String seleniumURI;
public static String buildTag;
/**
* Constructs a {@link SauceOnDemandAuthentication} instance using the supplied user name/access key. To use the authentication
* supplied by environment variables or from an external file, use the no-arg {@link SauceOnDemandAuthentication} constructor.
*/
public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication(username, accesskey);
/**
* JUnit Rule which will mark the Sauce Job as passed/failed when the test succeeds or fails.
*/
@Rule
public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication);
@Rule
public TestName name = new TestName() {
public String getMethodName() {
return String.format("%s", super.getMethodName());
}
};
/**
* Test decorated with @Retry will be run X times in case they fail using this rule.
*/
@Rule
public RetryRule rule = new RetryRule(1);
/**
* Represents the browser to be used as part of the test run.
*/
protected String browser;
/**
* Represents the operating system to be used as part of the test run.
*/
protected String os;
/**
* Represents the version of the browser to be used as part of the test run.
*/
protected String version;
/**
* Represents the deviceName of mobile device
*/
protected String deviceName;
/**
* Represents the device-orientation of mobile device
*/
protected String deviceOrientation;
/**
* Instance variable which contains the Sauce Job Id.
*/
protected String sessionId;
protected WebDriver driver;
//protected static ArrayList<WebDriver> drivers;
protected static String screenResolution;
protected static String testURL;
protected static String browserVersion;
protected static String titleOfFirstResult;
protected static String pre_prod="preprod";
//protected static String pre_prod="p24";
protected static boolean Ispre_prod=false;
public WebDriverTestBaseParalell(String os, String version, String browser, String deviceName, String deviceOrientation) {
super();
this.os = os;
this.version = version;
this.browser = browser;
this.deviceName = deviceName;
this.deviceOrientation = deviceOrientation;
testURL = System.getProperty("test.url");
screenResolution = System.getProperty("test.resolution");
System.out.println("OS: " + os);
System.out.println("Version: " + version);
System.out.println("Browser: " + browser);
System.out.println("Device: " +deviceName);
System.out.println("Orientation: " + deviceOrientation);
}
/**
* @return a LinkedList containing String arrays representing the browser combinations the test should be run against. The values
* in the String array are used as part of the invocation of the test constructor
*/
@ConcurrentParameterized.Parameters
public static LinkedList browsersStrings() {
String browsersJSON = System.getenv("SAUCE_ONDEMAND_BROWSERS");
LinkedList browsers = new LinkedList();
System.out.println("JSON: " + browsersJSON);
JSONObject browsersJSONObject = new JSONObject("{browsers:"+browsersJSON+"}");
JSONArray browsersJSONArray = browsersJSONObject.getJSONArray("browsers");
if(browsersJSON == null){
System.out.println("You did not specify browsers, testing with firefox and chrome...");
browsers.add(new String[]{"Windows 7", "41", "chrome", null, null});
browsers.add(new String[]{"Windows 8.1", "46", "firefox", null, null});
}
else{
for (int i = 0; i < browsersJSONArray.length(); i++) {
//TODO:: find names of extra properties for mobile Devices such as orientation and device name
JSONObject browserConfigs = browsersJSONArray.getJSONObject(i);
String browserOS = browserConfigs.getString("os");
String browserPlatform= browserConfigs.getString("platform");
String browserName= browserConfigs.getString("browser");
String browserVersion = browserConfigs.getString("browser-version");
String device = null;
String deviceOrientation = null;
try{
device = browserConfigs.getString("device");
deviceOrientation = browserConfigs.getString("device-orientation");
}catch(JSONException e){/* Intentionally empty */}
browsers.add(new String[]{browserOS, browserVersion, browserName, device, deviceOrientation});
}
}
// windows xp, IE 8
//browsers.add(new String[]{"Windows XP", "8", "internet explorer", null, null});
// OS X 10.8, Safari 6
// browsers.add(new String[]{"OSX 10.8", "6", "safari", null, null});
return browsers;
}
/**
* Constructs a new {@link RemoteWebDriver} instance which is configured to use the capabilities defined by the {@link #browser},
* {@link #version} and {@link #os} instance variables, and which is configured to run against ondemand.saucelabs.com, using
* the username and access key populated by the {@link #authentication} instance.
*
* @throws Exception if an error occurs during the creation of the {@link RemoteWebDriver} instance.
*/
@Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
if (browser != null) capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
if (version != null) capabilities.setCapability(CapabilityType.VERSION, version);
if (deviceName != null) capabilities.setCapability("deviceName", deviceName);
if (deviceOrientation != null) capabilities.setCapability("device-orientation", deviceOrientation);
capabilities.setCapability(CapabilityType.PLATFORM, os);
String methodName = name.getMethodName() + " " + browser + " " + version;
capabilities.setCapability("name", methodName);
System.out.println("Screen Resolution: " + screenResolution);
if(!screenResolution.equals("no")){
capabilities.setCapability("screenResolution", screenResolution);
}
//Getting the build name.
//Using the Jenkins ENV var. You can use your own. If it is not set test will run without a build id.
/*if (buildTag != null) {
capabilities.setCapability("build", buildTag);
}*/
capabilities.setCapability("build", System.getenv("JOB_NAME") + "__" + System.getenv("BUILD_NUMBER"));
System.out.println("https://" + username+ ":" + accesskey + /*seleniumURI*/ "@127.0.0.1:4445" +"/wd/hub");
SauceHelpers.addSauceConnectTunnelId(capabilities);
this.driver = new RemoteWebDriver(
new URL("http://" + username+ ":" + accesskey + /*seleniumURI*/ "@127.0.0.1:4445" +"/wd/hub"),
capabilities);
this.driver.get(testURL);
this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString();
String message = String.format("SauceOnDemandSessionID=%1$s job-name=%2$s", this.sessionId, methodName);
System.out.println(message);
}
/**
* This method is run before each test.
* It sets the browsers to the starting test url
*/
@Before
public void preTest() {
//for(WebDriver d: drivers)
driver.get(testURL);
}
/**
* Releases the resources used for the tests, i.e.,
* It closes the WebDriver.
*/
@After
public void tearDown() throws Exception {
driver.quit();
}
/**
* Creates a Local WebDriver given a string with the web browser name.
*
* @param browser The browser name for the WebDriver initialization
* @return The initialized Local WebDriver
*/
private static WebDriver selectLocalBrowser(String browser) throws java.net.MalformedURLException{
WebDriver driver = null;
if (browser.contains("firefox")) {
driver = new FirefoxDriver();
} else if (browser.contains("iexplorer")) {
driver = new InternetExplorerDriver();
} else if (browser.contains("chrome")) {
//DesiredCapabilities capabilities = DesiredCapabilities.chrome();
//capabilities.setCapability("chrome.binary", "/usr/lib/chromium-browser/chromium-browser");
//driver = new ChromeDriver(capabilities);
driver = new ChromeDriver();
} else if (browser.contains("opera")) {
driver = new OperaDriver();
} else if (browser.contains("remote-chrome")) {
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
} else if (browser.contains("remote-firefox")) {
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
driver.get("http:
} else {
// OH NOEZ! I DOAN HAZ DAT BROWSR!
System.err.println("Cannot find suitable browser driver for ["+ browser +"]");
}
return driver;
}
/**
* Gets a suitable Platform object given a OS/Platform string..
*
* @param platformString The given string for the OS/Platform to use
* @return The Platform object that represent the requested OS/Platform
*/
private static Platform selectPlatform(String platformString) {
Platform platform = null;
if (platformString.contains("Windows")) {
if (platformString.contains("2008")) {
platform = Platform.VISTA;
} else {
platform = Platform.XP;
}
} else if (platformString.toLowerCase().equals("linux")){
platform = Platform.LINUX;
} else {
System.err.println("Cannot find a suitable platform/OS for ["+ platformString +"]");
}
return platform;
}
/**
* Miscellaneous cleaning for browser and browser's version strings.
* @param browser The browser string to clean
* @param browserVersion The browser version string to clean
*/
private static void parameterCleanupForRemote(String browser, String browserVersion) {
// Selenium1 likes to prepend a "*" to browser string.
if (browser.startsWith("*")) {
browser = browser.substring(1);
}
// SauceLabs doesn't use version numbering for Google Chrome due to
// the fast release schedule of that browser.
if (browser.contains("googlechrome")) {
browserVersion = "";
}
}
/**
* Utility class to obtain the Class name in a static context.
*/
public static class CurrentClassGetter extends SecurityManager {
public String getClassName() {
return getClassContext()[1].getName();
}
}
@BeforeClass
public static void setupClass(){
//get the uri to send the commands to.
seleniumURI = SauceHelpers.buildSauceUri();
//If available add build tag. When running under Jenkins BUILD_TAG is automatically set.
//You can set this manually on manual runs.
buildTag = System.getenv("BUILD_TAG");
}
/**
*
* @return the value of the Sauce Job id.
*/
@Override
public String getSessionId() {
return sessionId;
}
/**
* Checks if an element is present in the page
*/
protected boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
} |
package ac.simons.tests.akismet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Assert;
import org.junit.Test;
import ac.simons.akismet.Akismet;
import ac.simons.akismet.AkismetComment;
import ac.simons.akismet.AkismetException;
/**
* @author Michael J. Simons
*/
public class AkismetTest {
private final static String validApiKey;
private final static String validApiConsumer;
static {
validApiKey = System.getProperty("akismetApiKey");
validApiConsumer = System.getProperty("akismetConsumer");
if(validApiKey == null || validApiConsumer == null)
throw new RuntimeException("Both api key and consumer must be specified!");
}
@Test
public void verify() throws AkismetException {
final Akismet akismet = new Akismet(new DefaultHttpClient());
akismet.setApiKey(validApiKey);
akismet.setApiConsumer(validApiConsumer);
Assert.assertTrue(akismet.verifyKey());
akismet.setApiKey("123test");
akismet.setApiConsumer("http://test.com");
Assert.assertFalse(akismet.verifyKey());
}
@Test
public void checkComment() throws AkismetException {
final Akismet akismet = new Akismet(new DefaultHttpClient());
akismet.setApiKey(validApiKey);
akismet.setApiConsumer(validApiConsumer);
AkismetComment comment = new AkismetComment();
comment.setUserIp("80.138.52.114");
comment.setUserAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10");
comment.setPermalink("http://dailyfratze.de/marie/2011/1/3");
comment.setCommentType("comment");
comment.setCommentAuthor("Michael");
comment.setCommentAuthorEmail("misi@planet-punk.de");
comment.setCommentAuthorUrl("http://planet-punk.de");
comment.setCommentContent("Scharfes Outfit :D");
Assert.assertFalse(akismet.commentCheck(comment));
comment = new AkismetComment();
comment.setUserIp("80.138.52.114");
comment.setUserAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
comment.setPermalink("http://dailyfratze.de/marie/2011/1/3");
comment.setCommentType("comment");
comment.setCommentAuthor("viagra-test-123");
comment.setCommentAuthorEmail("viagra-test-123@test.com");
comment.setCommentAuthorUrl("http://test.com");
comment.setCommentContent("Scharfes Outfit :D");
Assert.assertTrue(akismet.commentCheck(comment));
comment = new AkismetComment();
comment.setUserIp("92.99.136.158");
comment.setUserAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
comment.setPermalink("http://dailyfratze.de/tina/2009/6/5" );
comment.setCommentType("comment");
comment.setCommentAuthor("Yesid");
comment.setCommentAuthorEmail("");
comment.setCommentAuthorUrl("");
comment.setCommentContent("hello!This was a really otsitandung blog!I come from itlay, I was fortunate to approach your Topics in baiduAlso I obtain a lot in your topic really thanks very much i will come later");
Assert.assertTrue(akismet.commentCheck(comment));
comment = new AkismetComment();
comment.setUserIp("77.79.229.62");
comment.setUserAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
comment.setPermalink("http://dailyfratze.de/app/news/show/250" );
comment.setCommentType("comment");
comment.setCommentAuthor("Payal");
comment.setCommentContent("ett tips kan ju vara att du lc3a4gger ut olika magar ocksc3a5? Nu fc3b6rstc3a5r jag ju visserligen om du inte vill att din blogg ska fc3b6rvandlas till en blogg med massa elidbr pc3a5 random personers kroppar helt, men nc3a4r du c3a4ndc3a5 c3a4r inne pc3a5 spc3a5ret sc3a5 c3a4r ju mc3a5nga osc3a4kra pc3a5 sina magar. Jag vet att jag c3a4r det. Tvc3a5 personer har frc3a5gat mig helt random om jag c3a4r gravid trots att jag inte c3a4r det eftersom min mage putar ut (de kc3a4nner inte ens varandra). Jag c3a4lskar din blogg i vanliga fall, men nu c3a4lskar jag den c3a4nnu mer. Jag bc3b6rjar kc3a4nna lite att mina lc3a5r duger som de c3a4r. Tack Egoina fc3b6r att du bc3a5de inspirerar och bryr dig om personerna som lc3a4ser din blogg! <3");
Assert.assertTrue(akismet.commentCheck(comment));
}
@Test
public void submitSpam() throws AkismetException {
final Akismet akismet = new Akismet(new DefaultHttpClient());
akismet.setApiKey(validApiKey);
akismet.setApiConsumer(validApiConsumer);
AkismetComment comment = new AkismetComment();
comment.setUserIp("201.45.14.18");
comment.setUserAgent("UserAgent");
comment.setPermalink("http://dailyfratze.de/app/news/show/256");
comment.setCommentType("comment");
comment.setCommentAuthor("yohlctfwnem");
comment.setCommentAuthorEmail("rcphwp@nvwcjd.com");
comment.setCommentAuthorUrl("http://dzhnjufiaxlf.com/");
comment.setCommentContent("yKWClC <a href=\"http:
Assert.assertTrue(akismet.submitSpam(comment));
}
@Test
public void submitHam() throws AkismetException {
final Akismet akismet = new Akismet(new DefaultHttpClient());
akismet.setApiKey(validApiKey);
akismet.setApiConsumer(validApiConsumer);
AkismetComment comment = new AkismetComment();
comment.setUserIp("80.138.52.114");
comment.setUserAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10");
comment.setPermalink("http://dailyfratze.de/marie/2011/1/3");
comment.setCommentType("comment");
comment.setCommentAuthor("Michael");
comment.setCommentAuthorEmail("misi@planet-punk.de");
comment.setCommentAuthorUrl("http://planet-punk.de");
comment.setCommentContent("Scharfes Outfit :D");
Assert.assertTrue(akismet.submitHam(comment));
}
} |
package algorithms.misc;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import java.util.Random;
import junit.framework.TestCase;
/**
*
* @author nichole
*/
public class CDFRandomSelectTest extends TestCase {
public CDFRandomSelectTest(String testName) {
super(testName);
}
public void test0() {
double[] cdf;
double srch;
int idx;
double tol = 3.e-5;
cdf = new double[]{ 1., 2., 3., 3.1, 4.};
srch = 3.04;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(2, idx);
srch = 1.04;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(0, idx);
srch = 0.04;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(0, idx);
srch = 3.15;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(3, idx);
srch = 3.6;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(4, idx);
srch = 5.0;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(4, idx);
for (int i = 0; i < cdf.length; ++i) {
srch = cdf[i] + tol/2.;
idx = CDFRandomSelect.binarySearchForNearest(cdf, srch, tol);
assertEquals(i, idx);
}
}
public void test1() {
double[] cdf;
int[] selected;
Random rand = Misc0.getSecureRandom();
long seed = System.nanoTime();
//seed = 180328550254112L;
System.out.println("seed=" + seed);
System.out.flush();
rand.setSeed(seed);
cdf = new double[100];
for (int i = 0; i < cdf.length; ++i) {
cdf[i] = i + 1;
}
// normalize so that the last bin is "1".
double norm = cdf[cdf.length - 1];
for (int i = 0; i < cdf.length; ++i) {
cdf[i] /= norm;
}
int k = 1 * cdf.length;
selected = CDFRandomSelect.chooseKFromBinarySearch(cdf, k, rand);
assertEquals(k, selected.length);
TIntIntMap freq = new TIntIntHashMap();
int key;
int val;
int minKey = Integer.MAX_VALUE;
int maxKey = Integer.MIN_VALUE;
for (int i = 0; i < k; ++i) {
key = selected[i];
if (freq.containsKey(key)) {
val = freq.get(key) + 1;
} else {
val = 1;
}
freq.put(key, val);
if (key < minKey) {
minKey = key;
}
if (key > maxKey) {
maxKey = key;
}
}
double nBins = cdf.length;
double eUniform = (double)k/nBins;//nDraws/(double)nBins;
int dOF = cdf.length - 1 - 1;
double chiSqStat = ChiSquaredCriticalValues.upperTailStatistic(
ChiSquaredCriticalValues.PROB_UT.Z_90, dOF);
double expectedSigmaSq = (nBins*nBins)/12;
double expectedSigma = Math.sqrt(expectedSigmaSq);
double[] meanAndStDev = MiscMath0.getAvgAndStDev(selected);
assertTrue(Math.abs(meanAndStDev[1] - expectedSigma) < (expectedSigma/5.));
double diff;
double statSq = 0;
double frequency;
int totVals = 0;
//for (int key2 : sortedKeys) {
for (int i = 0; i < cdf.length; ++i) {
if (freq.containsKey(i)) {
frequency = freq.get(i);
} else {
frequency = 0;
}
totVals += frequency;
diff = frequency - eUniform;
diff *= diff;
statSq += (diff/eUniform);
}
/*
goodness of fit tests:
the test only rejects the assumed distribution when there is
definite evidence that the distribution is incorrect.
in hypothesis testing,
type I error = rejecting a true null hypothesis
type II error = accepting a false null hypothesis.
The power of a goodness-of-fit is the probability that the test
will rcjecL the null hypothesis.
*/
double pVal = ChiSquaredCriticalValues.approxPValueLin(statSq, dOF);
double chiSqStat3 = ChiSquaredCriticalValues.approxChiSqStatLin(
1./nBins, dOF);
double chiSqStat4 = ChiSquaredCriticalValues.approxChiSqStatLin(
1./(double)k, dOF);
// if statSq < chiSqStat, there is no evidence to suggest the
// distribution is not uniform.
//assertTrue(statSq < chiSqStat);
}
public void test2() {
double[] cdf;
int[] selected;
Random rand = Misc0.getSecureRandom();
long seed = System.nanoTime();
//seed = 182153812288260L;
System.out.println("*seed=" + seed);
System.out.flush();
rand.setSeed(seed);
cdf = new double[100];
for (int i = 0; i < cdf.length; ++i) {
cdf[i] = i + 1;
}
// normalize so that the last bin is "1".
double norm = cdf[cdf.length - 1];
for (int i = 0; i < cdf.length; ++i) {
cdf[i] /= norm;
}
int k = 5 * cdf.length;
selected = CDFRandomSelect.chooseKFromBinarySearch(cdf, k, rand);
assertEquals(k, selected.length);
TIntIntMap freq = new TIntIntHashMap();
int key;
int val;
int minKey = Integer.MAX_VALUE;
int maxKey = Integer.MIN_VALUE;
for (int i = 0; i < k; ++i) {
key = selected[i];
if (freq.containsKey(key)) {
val = freq.get(key) + 1;
} else {
val = 1;
}
freq.put(key, val);
if (key < minKey) {
minKey = key;
}
if (key > maxKey) {
maxKey = key;
}
}
double nBins = cdf.length;
double eUniform = (double)k/nBins;//nDraws/(double)nBins;
int dOF = cdf.length - 1;
double chiSqStat = ChiSquaredCriticalValues.upperTailStatistic(
ChiSquaredCriticalValues.PROB_UT.Z_95, dOF);
double expectedSigmaSq = (nBins*nBins)/12;
double expectedSigma = Math.sqrt(expectedSigmaSq);
double[] meanAndStDev = MiscMath0.getAvgAndStDev(selected);
assertTrue(Math.abs(meanAndStDev[1] - expectedSigma) < (expectedSigma/5.));
double diff;
double statSq = 0;
double frequency;
int totVals = 0;
//for (int key2 : sortedKeys) {
for (int i = 0; i < cdf.length; ++i) {
if (freq.containsKey(i)) {
frequency = freq.get(i);
} else {
frequency = 0;
}
totVals += frequency;
diff = frequency - eUniform;
diff *= diff;
statSq += (diff/eUniform);
}
double pVal = ChiSquaredCriticalValues.approxPValueLin(statSq, dOF);
double chiSqStat3 = ChiSquaredCriticalValues.approxChiSqStatLin(
1./nBins, dOF);
double chiSqStat4 = ChiSquaredCriticalValues.approxChiSqStatLin(
1./(double)k, dOF);
// if statSq < chiSqStat, there is no evidence to suggest the
// distribution is not uniform.
assertTrue(statSq < chiSqStat || statSq < chiSqStat4);
}
public void test3() {
double[] cdf;
int[] selected;
Random rand = Misc0.getSecureRandom();
long seed = System.nanoTime();
seed = 185069486225947L;
System.out.println("*seed=" + seed);
System.out.flush();
rand.setSeed(seed);
cdf = new double[100];
for (int i = 0; i < cdf.length; ++i) {
cdf[i] = i + 1;
}
// normalize so that the last bin is "1".
double norm = cdf[cdf.length - 1];
for (int i = 0; i < cdf.length; ++i) {
cdf[i] /= norm;
}
int k = 5 * cdf.length;
selected = CDFRandomSelect.chooseKFromBinarySearchFloor(cdf, k, rand);
assertEquals(k, selected.length);
TIntIntMap freq = new TIntIntHashMap();
int key;
int val;
int minKey = Integer.MAX_VALUE;
int maxKey = Integer.MIN_VALUE;
for (int i = 0; i < k; ++i) {
key = selected[i];
if (freq.containsKey(key)) {
val = freq.get(key) + 1;
} else {
val = 1;
}
freq.put(key, val);
if (key < minKey) {
minKey = key;
}
if (key > maxKey) {
maxKey = key;
}
}
double nBins = cdf.length;
double eUniform = (double)k/nBins;//nDraws/(double)nBins;
int dOF = cdf.length - 1;
double chiSqStat = ChiSquaredCriticalValues.upperTailStatistic(
ChiSquaredCriticalValues.PROB_UT.Z_95, dOF);
double expectedSigmaSq = (nBins*nBins)/12;
double expectedSigma = Math.sqrt(expectedSigmaSq);
double[] meanAndStDev = MiscMath0.getAvgAndStDev(selected);
assertTrue(Math.abs(meanAndStDev[1] - expectedSigma) < (expectedSigma/5.));
double diff;
double statSq = 0;
double frequency;
int totVals = 0;
//for (int key2 : sortedKeys) {
for (int i = 0; i < cdf.length; ++i) {
if (freq.containsKey(i)) {
frequency = freq.get(i);
} else {
frequency = 0;
}
totVals += frequency;
diff = frequency - eUniform;
diff *= diff;
statSq += (diff/eUniform);
}
double pVal = ChiSquaredCriticalValues.approxPValueLin(statSq, dOF);
double chiSqStat3 = ChiSquaredCriticalValues.approxChiSqStatLin(
1./nBins, dOF);
double chiSqStat4 = ChiSquaredCriticalValues.approxChiSqStatLin(
1./(double)k, dOF);
// if statSq < chiSqStat, there is no evidence to suggest the
// distribution is not uniform.
//assertTrue(statSq < chiSqStat || statSq < chiSqStat4);
}
} |
package com.tinkerrocks.structure;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.engine.StandardTraversalEngine;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class RocksTest {
RocksGraph graph;
@Before
public void setup() throws IOException, InstantiationException {
Configuration configuration = new BaseConfiguration();
FileUtils.deleteDirectory(new File("/tmp/databases"));
FileUtils.forceMkdir(new File("/tmp/databases"));
graph = RocksGraph.open(configuration);
}
@Test
public void testMultiValues() {
Vertex marko = graph.addVertex(T.label, "person", T.id, "jumbaho", "name", "marko", "age", 29);
Set<Object> ages = new HashSet<>();
ages.add("test");
ages.add(2);
ages.add(3);
ages.add(3);
marko.property("age", ages);
System.out.println("vertex:" + marko.properties("age").next().value().getClass());
}
@Test
public void addVertexTest() {
graph.createIndex("age", Vertex.class);
graph.createIndex("weight", Edge.class);
GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build()));
//System.out.println("g=" + g);
System.out.println("traversed edge" + g.V().toList()); //.bothE("knows").has("weight", 0.5f).tryNext().orElse(null));
//g.addV()
//g.addV().addE()
Vertex marko = graph.addVertex(T.label, "person", T.id, 1, "name", "marko", "age", 29);
Vertex vadas = graph.addVertex(T.label, "person", T.id, 2, "name", "vadas", "age", 27);
Vertex lop = graph.addVertex(T.label, "software", T.id, 3, "name", "lop", "lang", "java");
Vertex josh = graph.addVertex(T.label, "person", T.id, 4, "name", "josh", "age", 32);
Vertex ripple = graph.addVertex(T.label, "software", T.id, 5, "name", "ripple", "lang", "java");
Vertex peter = graph.addVertex(T.label, "person", T.id, 6, "name", "peter", "age", 35);
marko.addEdge("knows", vadas, T.id, 7, "weight", 0.5f, "weight1", 10.6f);
marko.addEdge("knows", josh, T.id, 8, "weight", 1.0f);
marko.addEdge("created", lop, T.id, 9, "weight", 0.4f);
josh.addEdge("created", ripple, T.id, 10, "weight", 1.0f);
josh.addEdge("created", lop, T.id, 11, "weight", 0.4f);
peter.addEdge("created", lop, T.id, 12, "weight", 0.2f);
Iterator<Vertex> iter = graph.vertices(1);
while (iter.hasNext()) {
Vertex test = iter.next();
Iterator<VertexProperty<Object>> properties = test.properties();
while (properties.hasNext()) {
System.out.println("vertex:" + test + "\tproperties:" + properties.next());
}
Iterator<Edge> edges = test.edges(Direction.BOTH);
while (edges.hasNext()) {
Edge edge = edges.next();
System.out.println("Edge: " + edge);
Iterator<Property<Object>> edge_properties = edge.properties();
while (edge_properties.hasNext()) {
System.out.println("edge:" + test + "\tproperties:" + edge_properties.next());
}
}
//System.out.println(iter.next().edges(Direction.BOTH).hasNext());
}
}
@Test
public void PerfTest() {
graph.createIndex("name", Vertex.class);
long start = System.currentTimeMillis();
int ITERATIONS = 10000;
for (int i = 0; i < ITERATIONS; i++) {
graph.addVertex(T.label, "person", T.id, 200 + i, "name", "marko" + i, "age", 29);
}
long end = System.currentTimeMillis() - start;
System.out.println("write time takes to add " + ITERATIONS + " vertices (ms):\t" + end);
start = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
graph.vertices(200 + i).next().property("name");
}
end = System.currentTimeMillis() - start;
System.out.println("read time takes to read " + ITERATIONS + " vertices (ms):\t" + end);
start = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
graph.vertices(200).next().property("name");
}
end = System.currentTimeMillis() - start;
System.out.println("read time takes to access same vertex " + ITERATIONS + " times (ms):\t" + end);
Vertex supernode = graph.vertices(200).next();
Vertex supernodeSink = graph.vertices(201).next();
start = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
supernode.addEdge("knows", supernodeSink, T.id, 700 + i, "weight", 0.5f);
}
end = System.currentTimeMillis() - start;
System.out.println("time to add " + ITERATIONS + " edges (ms):\t" + end);
start = System.currentTimeMillis();
supernode.edges(Direction.BOTH);
end = System.currentTimeMillis() - start;
System.out.println("time to read " + ITERATIONS + " edges (ms):\t" + end);
start = System.currentTimeMillis();
Iterator<Edge> test = supernode.edges(Direction.OUT, "knows");
end = System.currentTimeMillis() - start;
System.out.println("time to read " + ITERATIONS + " cached edges (ms):\t" + end);
long count = IteratorUtils.count(test);
System.out.println("got edges: " + count);
}
@Test
public void IndexTest() {
graph.createIndex("age", Vertex.class);
int i = 0;
while (i < 5000) {
graph.addVertex(T.label, "person", T.id, "index" + i, "name", "marko", "age", 29);
i++;
}
while (i < 5000) {
graph.addVertex(T.label, "personal", T.id, "index" + (5000 + i), "name", "marko", "age", 29);
i++;
}
while (i < 200000) {
graph.addVertex(T.label, "movie", T.id, "index" + (10000 + i), "name", "marko");
i++;
}
graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 30);
graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 31);
GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build()));
long start = System.currentTimeMillis();
System.out.println(g.V().has("age", 31).toList().size());
long end = System.currentTimeMillis();
System.out.println("time taken to search:" + (end - start));
}
@After
public void close() throws Exception {
this.graph.close();
}
} |
package com.tinkerrocks.structure;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.junit.Test;
import java.util.Iterator;
public class RocksTest {
@Test
public void addVertexTest() {
Configuration configuration = new BaseConfiguration();
RocksGraph graph = new RocksGraph(configuration);
Vertex marko = graph.addVertex(T.label, "person", T.id, 1, "name", "marko", "age", 29);
Vertex vadas = graph.addVertex(T.label, "person", T.id, 2, "name", "vadas", "age", 27);
Vertex lop = graph.addVertex(T.label, "software", T.id, 3, "name", "lop", "lang", "java");
Vertex josh = graph.addVertex(T.label, "person", T.id, 4, "name", "josh", "age", 32);
Vertex ripple = graph.addVertex(T.label, "software", T.id, 5, "name", "ripple", "lang", "java");
Vertex peter = graph.addVertex(T.label, "person", T.id, 6, "name", "peter", "age", 35);
marko.addEdge("knows", vadas, T.id, 7, "weight", 0.5f);
marko.addEdge("knows", josh, T.id, 8, "weight", 1.0f);
marko.addEdge("created", lop, T.id, 9, "weight", 0.4f);
josh.addEdge("created", ripple, T.id, 10, "weight", 1.0f);
josh.addEdge("created", lop, T.id, 11, "weight", 0.4f);
peter.addEdge("created", lop, T.id, 12, "weight", 0.2f);
Iterator<Vertex> iter = graph.vertices();
while (iter.hasNext()) {
Vertex test = iter.next();
Iterator<VertexProperty<Object>> properties = test.properties();
while (properties.hasNext()) {
System.out.println("vertex:" + test + "\tproperties:" + properties.next());
}
//System.out.println(iter.next().edges(Direction.BOTH).hasNext());
}
}
} |
package org.junit.internal;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
public class MethodSorterTest {
private static final String ALPHA = "java.lang.Object alpha(int,double,java.lang.Thread)";
private static final String BETA = "void beta(int[][])";
private static final String GAMMA_VOID = "int gamma()";
private static final String GAMMA_BOOLEAN = "void gamma(boolean)";
private static final String DELTA = "void delta()";
private static final String EPSILON = "void epsilon()";
private static final String SUPER_METHOD = "void superMario()";
private static final String SUB_METHOD = "void subBowser()";
static class Dummy {
Object alpha(int i, double d, Thread t) {
return null;
}
void beta(int[][] x) {
}
int gamma() {
return 0;
}
void gamma(boolean b) {
}
void delta() {
}
void epsilon() {
}
}
static class Super {
void superMario() {
}
}
static class Sub extends Super {
void subBowser() {
}
}
private String toString(Class<?> clazz, Method[] methods) {
return Arrays.toString(methods).replace(clazz.getName() + '.', "");
}
private String declaredMethods(Class<?> clazz) {
return toString(clazz, MethodSorter.getDeclaredMethods(clazz));
}
private List<String> getDeclaredFilteredMethods(Class<?> clazz, List<String> ofInterest) {
// the method under test.
Method[] actualMethods = MethodSorter.getDeclaredMethods(clazz);
// obtain just the names instead of the full methods.
List<String> names = new ArrayList<String>();
for (Method m : actualMethods) {
names.add(m.toString().replace(clazz.getName() + '.', ""));
}
// reduce to the methods of interest.
names.retainAll(ofInterest);
return names;
}
@Test
public void getMethodsNullSorterSelf() {
List<String> expected = Arrays.asList(
new String[]{EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN});
List<String> actual = getDeclaredFilteredMethods(Dummy.class, expected);
assertEquals(expected, actual);
}
@Test
public void getMethodsNullSorterSuper() {
List<String> expected = Arrays.asList(new String[]{SUPER_METHOD});
List<String> actual = getDeclaredFilteredMethods(Super.class, expected);
assertEquals(expected, actual);
}
@Test
public void getMethodsNullSorterSub() {
List<String> expected = Arrays.asList(new String[]{SUB_METHOD});
List<String> actual = getDeclaredFilteredMethods(Sub.class, expected);
assertEquals(expected, actual);
}
@Test
public void getMethodsNullSorter() throws Exception {
String[] expected = new String[]{EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN};
assertEquals(Arrays.asList(expected).toString(), declaredMethods(Dummy.class));
assertEquals("[void superMario()]", declaredMethods(Super.class));
assertEquals("[void subBowser()]", declaredMethods(Sub.class));
}
@FixMethodOrder(MethodSorters.DEFAULT)
static class DummySortWithDefault {
Object alpha(int i, double d, Thread t) {
return null;
}
void beta(int[][] x) {
}
int gamma() {
return 0;
}
void gamma(boolean b) {
}
void delta() {
}
void epsilon() {
}
}
@Test
public void testDefaultSorter() {
String[] expected = new String[]{EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN};
assertEquals(Arrays.asList(expected).toString(), declaredMethods(DummySortWithDefault.class));
}
@FixMethodOrder(MethodSorters.JVM)
static class DummySortJvm {
Object alpha(int i, double d, Thread t) {
return null;
}
void beta(int[][] x) {
}
int gamma() {
return 0;
}
void gamma(boolean b) {
}
void delta() {
}
void epsilon() {
}
}
@Test
public void testSortWithJvm() {
Class<?> clazz = DummySortJvm.class;
String actual = toString(clazz, clazz.getDeclaredMethods());
assertEquals(actual, declaredMethods(clazz));
}
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
static class DummySortWithNameAsc {
Object alpha(int i, double d, Thread t) {
return null;
}
void beta(int[][] x) {
}
int gamma() {
return 0;
}
void gamma(boolean b) {
}
void delta() {
}
void epsilon() {
}
}
@Test
public void testNameAsc() {
String[] expected = new String[]{ALPHA, BETA, DELTA, EPSILON, GAMMA_VOID, GAMMA_BOOLEAN};
assertEquals(Arrays.asList(expected).toString(), declaredMethods(DummySortWithNameAsc.class));
}
} |
package org.mac.sim.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.junit.Test;
import org.mac.sim.clock.Clock;
import org.mac.sim.clock.ClockBuilder;
import org.mac.sim.clock.ClockManager;
import org.mac.sim.domain.WorkerTask;
import junit.framework.Assert;
public class QueueManagerTest {
/**
* Test that the proper number of tasks have been added to the queue.
*
* @throws InterruptedException
*/
@Test
public void runTest() throws InterruptedException {
BlockingQueue<WorkerTask> queue = new ArrayBlockingQueue<WorkerTask>(25);
Clock fivePeriodClock = ClockBuilder.build(5);
ClockManager fiveClockManager = new ClockManager(fivePeriodClock);
QueueManager qm = new QueueManager(queue, 5, fivePeriodClock);
qm.start();
fiveClockManager.start();
while (!fiveClockManager.isStopped()) {
}
Assert.assertEquals(25, queue.size());
queue = new ArrayBlockingQueue<WorkerTask>(50);
Clock tenPeriodClock = ClockBuilder.build(10);
ClockManager tenClockManager = new ClockManager(tenPeriodClock);
QueueManager qm2 = new QueueManager(queue, 5, tenPeriodClock);
qm2.start();
tenClockManager.start();
while (!tenClockManager.isStopped()) {
}
Assert.assertEquals(50, queue.size());
queue = new ArrayBlockingQueue<WorkerTask>(500);
Clock hundredPeriodClock = ClockBuilder.build(100);
ClockManager hundredClockManager = new ClockManager(hundredPeriodClock);
qm = new QueueManager(queue, 5, hundredPeriodClock);
qm.start();
hundredClockManager.start();
while (!hundredClockManager.isStopped()) {
}
Assert.assertEquals(500, queue.size());
}
/**
* Assert that the time intervals are large enough to hit the specified
* number of periods. This may have to change depending on CPU value.
*
* @throws InterruptedException
*/
@Test
public void workersTest() throws InterruptedException {
BlockingQueue<WorkerTask> queue = new ArrayBlockingQueue<WorkerTask>(500);
Clock hundredClock = ClockBuilder.build(100);
ClockManager cm = new ClockManager(hundredClock);
QueueManager qm = new QueueManager(queue, 5, hundredClock);
Worker w1 = new Worker(queue, 3, 3);
Worker w2 = new Worker(queue, 3, 3);
qm.start();
w1.start();
w2.start();
cm.start();
Thread.sleep(200);
while (!cm.isStopped()) {
}
cm.doStop();
w1.doStop();
w2.doStop();
Assert.assertEquals(500, qm.getAddActions());
Assert.assertEquals(500, w1.getTasksCompleted() + w2.getTasksCompleted());
Assert.assertEquals(100, qm.getPeriodsSpentInLoop());
}
} |
package org.mariadb.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;
public class ConnectionPoolTest extends BaseTest {
/* For this test case to compile the following must be added to the pom.xml:
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
*/
@Test
public void testConnectionWithApacheDBCP() throws SQLException {
org.apache.commons.dbcp.BasicDataSource dataSource;
dataSource = new org.apache.commons.dbcp.BasicDataSource();
dataSource.setUrl(connU);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(5);
dataSource.setLogAbandoned(true);
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeout(300);
dataSource.setAccessToUnderlyingConnectionAllowed(true);
dataSource.setMinEvictableIdleTimeMillis(1800000);
dataSource.setTimeBetweenEvictionRunsMillis(-1);
dataSource.setNumTestsPerEvictionRun(3);
// dataSource.setValidationQuery("/* ping */ SELECT 1");
Connection connection = dataSource.getConnection();
connection.close();
dataSource.close();
}
@Test
public void testTimeoutsInPool() throws SQLException, InterruptedException {
org.apache.commons.dbcp.BasicDataSource dataSource;
dataSource = new org.apache.commons.dbcp.BasicDataSource();
dataSource.setUrl("jdbc:mysql://" + hostname + ":3306/test?useCursorFetch=true&useTimezone=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
dataSource.setUsername(username);
dataSource.setPassword(password);
// dataSource.setMaxActive(10);
// dataSource.setMinIdle(10); //keep 10 connections open
// dataSource.setValidationQuery("SELECT 1");
dataSource.setMaxActive(50);
dataSource.setLogAbandoned(true);
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeout(300);
dataSource.setAccessToUnderlyingConnectionAllowed(true);
dataSource.setMinEvictableIdleTimeMillis(1800000);
dataSource.setTimeBetweenEvictionRunsMillis(-1);
dataSource.setNumTestsPerEvictionRun(3);
// adjust server wait timeout to 1 second
// Statement stmt1 = conn1.createStatement();
// stmt1.execute("set session wait_timeout=1");
try {
Connection conn = dataSource.getConnection();
System.out.println("autocommit: " + conn.getAutoCommit());
Statement stmt = conn.createStatement();
stmt.executeUpdate("drop table if exists t3");
stmt.executeUpdate("create table t3(message text)");
conn.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InsertThread ins1 = new InsertThread(10000, dataSource);
Thread thread1 = new Thread(ins1);
thread1.start();
InsertThread ins2 = new InsertThread(10000, dataSource);
Thread thread2 = new Thread(ins2);
thread2.start();
InsertThread ins3 = new InsertThread(10000, dataSource);
Thread thread3 = new Thread(ins3);
thread3.start();
InsertThread ins4 = new InsertThread(10000, dataSource);
Thread thread4 = new Thread(ins4);
thread4.start();
InsertThread ins5 = new InsertThread(10000, dataSource);
Thread thread5 = new Thread(ins5);
thread5.start();
InsertThread ins6 = new InsertThread(10000, dataSource);
Thread thread6 = new Thread(ins6);
thread6.start();
InsertThread ins7 = new InsertThread(10000, dataSource);
Thread thread7 = new Thread(ins7);
thread7.start();
InsertThread ins8 = new InsertThread(10000, dataSource);
Thread thread8 = new Thread(ins8);
thread8.start();
InsertThread ins9 = new InsertThread(10000, dataSource);
Thread thread9 = new Thread(ins9);
thread9.start();
InsertThread ins10 = new InsertThread(10000, dataSource);
Thread thread10 = new Thread(ins10);
thread10.start();
// wait for threads to finish
while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive() || thread4.isAlive() || thread5.isAlive() || thread6.isAlive() || thread7.isAlive() || thread8.isAlive() || thread9.isAlive() || thread10.isAlive())
{
//keep on waiting for threads to finish
}
// wait for 70 seconds so that the server times out the connections
Thread.sleep(70000); // Wait for the server to kill the connections
// do something
Statement stmt1 = dataSource.getConnection().createStatement();
stmt1.execute("SELECT COUNT(*) FROM t3");
// close data source
dataSource.close();
/*
Connection conn1 = null;
Statement stmt1 = null;
ResultSet rs;
for(int i = 1; i < 100000; i++)
{
conn1 = dataSource.getConnection();
stmt1 = conn1.createStatement();
rs = stmt1.executeQuery("SELECT 1");
rs.next();
conn1.close();
}
*/
// close all connections but conn1
/* conn1.close();
conn2.close();
conn3.close();
conn4.close();
conn5.close();
*/
// dataSource.close();
}
/**
* This test case simulates how the Apache DBCP connection pools works. It is written so it
* should compile without Apache DBCP but still show the problem.
*/
@Test
public void testConnectionWithSimululatedApacheDBCP() throws SQLException {
java.sql.Driver driver = new org.mariadb.jdbc.Driver();
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
//A connection pool typically has a connection factor that stored everything needed to
//create a Connection. Here I create a factory that stores URL, username and password.
SimulatedDriverConnectionFactory factory = new SimulatedDriverConnectionFactory(driver,
connU, props);
//Create 1 first connection (This is typically done in the Connection validation step in a
//connection pool)
Connection connection1 = factory.createConnection();
//Create another connection to make sure we can access the database. This is typically the
//Connection that is exposed to the user of the connection pool
Connection connection2 = factory.createConnection();
connection1.close();
connection2.close();
}
/** This class is a simulated version of org.apache.commons.dbcp.DriverConnectionFactory */
private static class SimulatedDriverConnectionFactory {
public SimulatedDriverConnectionFactory(java.sql.Driver driver, String connectUri, Properties props) {
_driver = driver;
_connectUri = connectUri;
_props = props;
}
public Connection createConnection() throws SQLException {
return _driver.connect(_connectUri,_props);
}
protected java.sql.Driver _driver = null;
protected String _connectUri = null;
protected Properties _props = null;
}
private class InsertThread implements Runnable {
private org.apache.commons.dbcp.BasicDataSource dataSource;
private int insertTimes;
public InsertThread(int insertTimes, org.apache.commons.dbcp.BasicDataSource dataSource) {
this.insertTimes = insertTimes;
this.dataSource = dataSource;
}
public synchronized void setDataSource(org.apache.commons.dbcp.BasicDataSource dataSource) {
this.dataSource = dataSource;
}
public synchronized org.apache.commons.dbcp.BasicDataSource getDataSource() {
return this.dataSource;
}
public void run() {
Connection conn = null;
Statement stmt = null;
for(int i = 1; i < insertTimes + 1; i++)
{
try {
conn = this.dataSource.getConnection();
stmt = conn.createStatement();
stmt.execute("insert into t3 values('hello" + Thread.currentThread().getId() + "-" + i + "')");
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e.getSQLState());
}
System.out.println("thread: " + Thread.currentThread().getId());
}
}
}
} |
package twigkit.html;
import org.junit.Test;
/**
* @author mr.olafsson
*/
public class ConditionalWrapperTest extends AbstractHtmlCapabilityTest {
@Test
public void testTrue() throws Exception {
ContainerTag div = div().body(
when(true).use(
span().body(
text("Hello"),
text(" world!")
),
span().body(
text("Go go go!")
)
).otherwise(
text("No hello!")
)
);
assertEquals("<div><span>Hello world!</span><span>Go go go!</span></div>", div);
}
@Test
public void testFalse() throws Exception {
ContainerTag div = div().body(
when(false).use(
text("Hello World!")
).otherwise(
when(false).use(
text("Not this either!")
).otherwise(
text("No hello!")
)
)
);
assertEquals("<div>No hello!</div>", div);
}
@Test
public void testNoOtherwise() throws Exception {
ContainerTag div = div().body(
when(false).use(
span().body(
text("Hello"),
text(" world!")
),
span().body(
text("Go go go!")
)
),
span().body(text("no others"))
);
assertEquals("<div><span>no others</span></div>", div);
}
} |
package sg.edu.cs2103aug2015_w13_2j.ui;
import java.awt.Color;
// @@author A0121410H
/**
* FeedbackMessage class encapsulates the data necessary to display styled
* feedback messages to the user. It comprises a message string retrievable via
* {@link #getMessage()} and a {@link FeedbackType} object which determines the
* type of feedback as well as the styling.
*
* @author Zhu Chunqi
*/
public class FeedbackMessage {
public static final FeedbackMessage CLEAR = new FeedbackMessage("",
FeedbackType.INFO);
public static final FeedbackMessage ERROR_INVALID_FILTER = new FeedbackMessage(
"The filter that you have specified is not valid. Did you type the filter name correctly?",
FeedbackType.ERROR);
public static final FeedbackMessage ERROR_INVALID_TASK = new FeedbackMessage(
"Invalid task entered. Please provide a name!", FeedbackType.ERROR);
public static final FeedbackMessage ERROR_TASK_NOT_FOUND = new FeedbackMessage(
"Task not found. Did you enter the index correctly?",
FeedbackType.ERROR);
public static final FeedbackMessage ERROR_UNRECOGNIZED_COMMAND = new FeedbackMessage(
"Command not recognized.", FeedbackType.ERROR);
/**
* Enumeration of the styling for different types of user feedback messages.
* The color of font to be used for each feedback type can be retrieved via
* {@link #getAWTColor()} or {@link #getFXColor()}
*
* @author Zhu Chunqi
*
*/
public enum FeedbackType {
INFO(Color.BLACK), ERROR(Color.RED);
private Color mColor;
private FeedbackType(Color color) {
mColor = color;
}
/**
* Retrieves the color that should be used to style this type of
* feedback message
*
* @return AWT Color object to be used for this type of feedback
*/
public Color getAWTColor() {
return mColor;
}
/**
* Retrieves the color that should be used to style this type of
* feedback message
*
* @return JavaFX Color object to be used for this type of feedback
*/
public javafx.scene.paint.Color getFXColor() {
return javafx.scene.paint.Color.rgb(mColor.getRed(),
mColor.getGreen(), mColor.getBlue());
}
}
private String mMessage;
private FeedbackType mType;
public FeedbackMessage(String message, FeedbackType type) {
mMessage = message;
mType = type;
}
/**
* Retrieves the string message text
*
* @return String message text
*/
public String getMessage() {
return mMessage;
}
/**
* Retrieves the {@link FeedbackType} object containing the styling
* information for this feedback message
*
* @return {@link FeedbackType} object for this feedback message
*/
public FeedbackType getType() {
return mType;
}
} |
package space.gatt.JavacordCommander;
import de.btobastian.javacord.DiscordAPI;
import de.btobastian.javacord.entities.message.MessageBuilder;
import org.reflections.Reflections;
import space.gatt.JavacordCommander.annotations.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class JavacordCommander {
private static JavacordCommander instance;
private DiscordAPI javacordInstance;
/**
* Including the (String) dir variable, will automatically call the enableSnooper method.
*/
public JavacordCommander(DiscordAPI apiInstance){
this.javacordInstance = apiInstance;
JavacordCommander.instance = this;
javacordInstance.registerListener(new CommandListener());
MessageManager.startManager(1000);
}
public JavacordCommander(DiscordAPI apiInstance, Integer messageManagerDelay){
this.javacordInstance = apiInstance;
JavacordCommander.instance = this;
javacordInstance.registerListener(new CommandListener());
MessageManager.startManager(messageManagerDelay);
}
/**
* @dir The directory or package to look for classes in.
*/
public JavacordCommander(DiscordAPI apiInstance, String dir){
this.javacordInstance = apiInstance;
JavacordCommander.instance = this;
enableSnooper(dir);
javacordInstance.registerListener(new CommandListener());
MessageManager.startManager(1000);
}
public JavacordCommander(DiscordAPI apiInstance, String dir, Integer messageManagerDelay){
this.javacordInstance = apiInstance;
JavacordCommander.instance = this;
enableSnooper(dir);
javacordInstance.registerListener(new CommandListener());
MessageManager.startManager(messageManagerDelay);
}
public static JavacordCommander getInstance() {
return instance;
}
private List<Class> listeners = new ArrayList<>();
private List<Method> listeningMethods = new ArrayList<>();
private HashMap<String, Class> commandRegistrar = new HashMap<>();
private HashMap<String, Method> methodRegistrar = new HashMap<>();
private List<String> commandList = new ArrayList<>();
private HashMap<String, List<String>> helpLines = new HashMap<>();
private ArrayList<String> adminUsers = new ArrayList<>();
public List<Class> getListeners() {
return listeners;
}
public List<Method> getListeningMethods() {
return listeningMethods;
}
public HashMap<String, Class> getCommandRegistrar() {
return commandRegistrar;
}
public HashMap<String, Method> getMethodRegistrar() {
return methodRegistrar;
}
public List<String> getCommandList() {
return commandList;
}
private boolean allowAdminBypass = false;
public boolean allowAdminBypass() {
return allowAdminBypass;
}
public void setAllowAdminBypass(boolean allowAdminBypass) {
this.allowAdminBypass = allowAdminBypass;
}
public ArrayList<String> getAdminUsers() {
return adminUsers;
}
public void addAdminUser(String id) {
adminUsers.add(id);
}
/**
* @dir The directory or package to look for classes in.
*/
public void enableSnooper(String dir){
Reflections reflections = new Reflections(dir);
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Command.class);
for (final Class c : classes){
Annotation[] annotations = c.getAnnotations();
for (Annotation a : annotations) {
if (a instanceof Command) {
String cmd = ((Command)a).value();
if (!commandList.contains(cmd)) {
commandList.add(cmd);
System.out.println("Registered command " + cmd + " for class " + c.getName());
Method[] methods = c.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(IMethod.class)) {
if (Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())) {
listeners.add(method.getDeclaringClass());
listeningMethods.add(method);
commandRegistrar.put(cmd, method.getDeclaringClass());
methodRegistrar.put(cmd, method);
System.out.println("Registered method " + method.getName() + " for command " + cmd);
loadData(c, cmd);
} else {
throw new IllegalArgumentException(method.getName() + " in " + c.getSimpleName()
+ " is not public static!");
}
}
}
}else{
System.out.println("The class " + c.getName() + " tried to register the command " + cmd + " a second time!");
}
}
}
}
}
private static List<String> getParts(String string, int partitionSize) {
List<String> parts = new ArrayList<String>();
int len = string.length();
for (int i=0; i<len; i+=partitionSize)
{
parts.add("```" + Settings.getHelpMessageLanguage() + "\n" + string.substring(i, Math.min(len, i + partitionSize)) + "\n```");
}
return parts;
}
/**
* <p>Returns the Built Help Message with all the Groups and stuff.</p>
*/
public List<String> buildHelpMessage(){
MessageBuilder builder = new MessageBuilder();
for (String group : helpLines.keySet()){
builder.append(Settings.getHelpMessageBreaker().replace("%group", group));
builder.appendNewLine();
for (String msg : helpLines.get(group)){
builder.append(msg).appendNewLine();
}
}
List<String> parts = getParts(builder.build(), 1950);
return parts;
}
private void loadData(Class c, String cmd){
Annotation[] annotations = c.getAnnotations();
String group = "null";
String description = "nul";
String syntax = "null";
String[] aliases = new String[]{"null"};
for (Annotation a : annotations) {
if (a instanceof Group){
group = ((Group)a).value();
}
if (a instanceof Description){
description = ((Description)a).value();
}
if (a instanceof Syntax){
syntax = ((Syntax)a).value();
}
if (a instanceof Aliases){
aliases = ((Aliases)a).value();
}
}
if (group != "null" && !group.equalsIgnoreCase("hidden")){
List<String> list = new ArrayList<>();
if (helpLines.get(group) != null){
list = helpLines.get(group);
}
String msg = Settings.getHelpFormat();
String aliasesMsg = "";
if (!(aliases.length == 1 && !aliases[0].equalsIgnoreCase("null"))){
for (String s : aliases){
aliasesMsg = aliasesMsg + s + " ";
}
aliasesMsg.trim();
}
msg = msg.replace("%cmd", cmd).replace("%group", group).replace("%desc", description).replace("%syntax", syntax).replace("%aliases", aliasesMsg);
list.add(msg);
helpLines.put(group, list);
}
}
} |
package spacesettlers.simulator;
import java.awt.Color;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.martiansoftware.jsap.JSAPResult;
import com.thoughtworks.xstream.XStream;
import spacesettlers.actions.AbstractAction;
import spacesettlers.actions.DoNothingAction;
import spacesettlers.actions.PurchaseTypes;
import spacesettlers.clients.ImmutableTeamInfo;
import spacesettlers.clients.Team;
import spacesettlers.clients.TeamClient;
import spacesettlers.configs.*;
import spacesettlers.gui.SpaceSettlersGUI;
import spacesettlers.objects.AbstractActionableObject;
import spacesettlers.objects.AbstractObject;
import spacesettlers.objects.Asteroid;
import spacesettlers.objects.Base;
import spacesettlers.objects.Beacon;
import spacesettlers.objects.Drone;
import spacesettlers.objects.Flag;
import spacesettlers.objects.Ship;
import spacesettlers.objects.powerups.SpaceSettlersPowerupEnum;
import spacesettlers.utilities.Position;
import spacesettlers.utilities.Vector2D;
public final class SpaceSettlersSimulator {
/**
* Max time allowed in MILLISECONDS for a team to return actions
*/
public static int TEAM_ACTION_TIMEOUT = 300;
/**
* Max time allowed in MILLISECONDS for a getMovement to return
*/
public static int MOVEMENT_TIMEOUT = 300;
/**
* Max time allowed in MILLISECONDS for a endAction to return
*/
public static int TEAM_END_ACTION_TIMEOUT = 300;
/**
* Max time allowed in MILLISECONDS for a graphic generation to return
*/
public static int TEAM_GRAPHICS_TIMEOUT = 200;
/**
* Probability that new asteroids spawn on any given turn
*/
public final static double ASTEROID_SPAWN_PROBABILITY = 0.01;
/**
* A list of the clients (e.g. agents who can control ships) in the simulator. It is indexed by team name.
*/
HashMap<String,TeamClient> clientMap;
/**
* A list of all teams that can control agents (not indexed)
*/
Set<Team> teams;
/**
* If Graphics are turned on, this is a pointer to the main part of the GUI
*/
SpaceSettlersGUI gui = null;
/**
* Global random number generator for the game
*/
Random random;
/**
* The configuration for this simulation
*/
SpaceSettlersConfig simConfig;
/**
* The physics engine
*/
Toroidal2DPhysics simulatedSpace;
/**
* Current timestep of the simulator
*/
int timestep;
/**
* If debug mode is true, then only run single threaded
*/
boolean debug = false;
/**
* True if the simulation is paused and false otherwise
*/
boolean isPaused = false;
/**
* Time to sleep between graphics updates (in milliseconds, set to 40 for default but can be changed in the GUI)
*/
int graphicsSleep = 40;
/**
* Create a simulator with the command line arguments already parsed.
* @param args
* @throws SimulatorException
*/
public SpaceSettlersSimulator(JSAPResult parserConfig) throws SimulatorException {
// load in all the configuration
simConfig = loadConfigFiles(parserConfig);
teams = new LinkedHashSet<Team>();
clientMap = new HashMap<String, TeamClient>();
if (simConfig.getRandomSeed() == 0) {
random = new Random();
} else {
random = new Random(simConfig.getRandomSeed());
}
// and use it to make agents and the world
initializeSimulation(parserConfig);
// see if debug mode is on
if (parserConfig.getBoolean("debug")) {
debug = true;
TEAM_ACTION_TIMEOUT = Integer.MAX_VALUE;
MOVEMENT_TIMEOUT = Integer.MAX_VALUE;
TEAM_END_ACTION_TIMEOUT = Integer.MAX_VALUE;
TEAM_GRAPHICS_TIMEOUT = Integer.MAX_VALUE;
}
// create the GUI after everything is created in the simulator
System.out.println(this);
createGUI(parserConfig);
}
/**
* Initialize from an existing config file for the simulator (used by the ladder)
* @param simConfig
* @param parserConfig
* @throws SimulatorException
*/
public SpaceSettlersSimulator(SpaceSettlersConfig simConfig, JSAPResult parserConfig) throws SimulatorException {
// load in all the configuration
this.simConfig = simConfig;
teams = new LinkedHashSet<Team>();
clientMap = new HashMap<String, TeamClient>();
if (simConfig.getRandomSeed() == 0) {
random = new Random();
} else {
random = new Random(simConfig.getRandomSeed());
}
// and use it to make agents and the world
initializeSimulation(parserConfig);
// create the GUI if the user asked for it
if (parserConfig.getBoolean("graphics")) {
gui = new SpaceSettlersGUI(simConfig, this);
}
// see if debug mode is on
if (parserConfig.getBoolean("debug")) {
debug = true;
TEAM_ACTION_TIMEOUT = Integer.MAX_VALUE;
MOVEMENT_TIMEOUT = Integer.MAX_VALUE;
TEAM_END_ACTION_TIMEOUT = Integer.MAX_VALUE;
TEAM_GRAPHICS_TIMEOUT = Integer.MAX_VALUE;
}
// create the GUI after everything is created in the simulator
System.out.println(this);
createGUI(parserConfig);
}
/**
* Create the GUI after the simulator has been initialize
*
* @param parserConfig
*/
public void createGUI(JSAPResult parserConfig) {
// create the GUI if the user asked for it
if (parserConfig.getBoolean("graphics")) {
gui = new SpaceSettlersGUI(simConfig, this);
}
}
/**
* Sleep so the gui can update (From Andy Fagg's tree code)
* @param i
*/
static public void mySleep(int i) {
try{
Thread.sleep(i);
}catch(Exception e)
{
System.out.println(e);
}
}
/**
* Initialize the simulation given a configuration file. Creates all the objects.
* @throws SimulatorException
*/
void initializeSimulation(JSAPResult parserConfig) throws SimulatorException {
simulatedSpace = new Toroidal2DPhysics(simConfig);
// place the beacons
for (int b = 0; b < simConfig.getNumBeacons(); b++) {
Beacon beacon = new Beacon(simulatedSpace.getRandomFreeLocation(random, Beacon.BEACON_RADIUS * 2));
//System.out.println("New beacon at " + beacon.getPosition());
simulatedSpace.addObject(beacon);
}
// place any fixed location asteroids
FixedAsteroidConfig[] fixedAsteroidConfigs = simConfig.getFixedAsteroids();
if (fixedAsteroidConfigs != null) {
for (FixedAsteroidConfig fixedAsteroidConfig : fixedAsteroidConfigs) {
Asteroid asteroid = createNewFixedAsteroid(fixedAsteroidConfig);
simulatedSpace.addObject(asteroid);
}
}
// place the asteroids
RandomAsteroidConfig randomAsteroidConfig = simConfig.getRandomAsteroids();
for (int a = 0; a < randomAsteroidConfig.getNumberInitialAsteroids(); a++) {
boolean mineable = false;
if (random.nextDouble() < simConfig.getRandomAsteroids().getProbabilityMineable()) {
mineable = true;
}
Asteroid asteroid = createNewRandomAsteroid(randomAsteroidConfig, mineable);
simulatedSpace.addObject(asteroid);
}
// create the clients
for (HighLevelTeamConfig teamConfig : simConfig.getTeams()) {
// ensure this team isn't a duplicate
if (clientMap.containsKey(teamConfig.getTeamName())) {
throw new SimulatorException("Error: duplicate team name " + teamConfig.getTeamName());
}
TeamClientConfig teamClientConfig = getTeamClientConfig(teamConfig, parserConfig.getString("configPath"));
// grab the home base config for this team (to get starting locations as needed)
BaseConfig thisBaseConfig = null;
for (BaseConfig baseConfig : simConfig.getBases()) {
String teamName = baseConfig.getTeamName();
if (teamName.equalsIgnoreCase(teamConfig.getTeamName())) {
thisBaseConfig = baseConfig;
break;
}
}
// now either use the base config for the default region radius or the teamConfig file
if (thisBaseConfig != null && thisBaseConfig.isFixedLocation()) {
teamConfig.setInitialRegionULX(thisBaseConfig.getBoundingBoxULX());
teamConfig.setInitialRegionULY(thisBaseConfig.getBoundingBoxULY());
teamConfig.setInitialRegionLRX(thisBaseConfig.getBoundingBoxLRX());
teamConfig.setInitialRegionLRY(thisBaseConfig.getBoundingBoxLRY());
System.out.println("Initial provided for team " + teamConfig.getTeamName()
+ "UL (x,y) = " + teamConfig.getInitialRegionULX() + ", " +
teamConfig.getInitialRegionULY() + " LR (x,y) = " +
teamConfig.getInitialRegionLRX() + ", " +
teamConfig.getInitialRegionLRY());
} else {
// if the team doesn't provide default radiii and bases, create one
if (teamConfig.getInitialRegionULX() == 0 && teamConfig.getInitialRegionLRX() == 0) {
teamConfig.setInitialRegionULX(random.nextInt(simConfig.getWidth()));
teamConfig.setInitialRegionLRX(teamConfig.getInitialRegionULX() + simConfig.getWidth() / 4);
teamConfig.setInitialRegionULY(random.nextInt(simConfig.getHeight()));
teamConfig.setInitialRegionLRY(teamConfig.getInitialRegionULX() + simConfig.getHeight() / 4);
System.out.println("Initial location not provided for team " + teamConfig.getTeamName()
+ "...generating: UL (x,y) = " + teamConfig.getInitialRegionULX() + ", " +
teamConfig.getInitialRegionULY() + " LR (x,y) = " +
teamConfig.getInitialRegionLRX() + ", " +
teamConfig.getInitialRegionLRY());
}
}
TeamClient teamClient = createTeamClient(teamConfig, teamClientConfig);
// make the team inside the simulator for this team
Team team = createTeam(teamConfig, teamClient, teamClientConfig);
clientMap.put(teamConfig.getTeamName(), teamClient);
}
// make sure the base count matches the team count
if (simConfig.getTeams().length != simConfig.getBases().length) {
throw new SimulatorException("Error: You specified " + simConfig.getTeams().length +
" teams and " + simConfig.getBases().length + " bases. They must match.");
}
// create the bases and ensure there is a base for each team
for (BaseConfig baseConfig : simConfig.getBases()) {
String teamName = baseConfig.getTeamName();
if (!clientMap.containsKey(teamName)) {
throw new SimulatorException("Error: base is listed as team " + teamName + " but there is no corresponding team");
}
TeamClient teamClient = clientMap.get(teamName);
// find the team config for this team
HighLevelTeamConfig thisTeamConfig = null;
for (HighLevelTeamConfig teamConfig : simConfig.getTeams()) {
if (teamConfig.getTeamName().equalsIgnoreCase(teamName)) {
thisTeamConfig = teamConfig;
break;
}
}
// make the location based on fixed or random
Position baseLocation;
if (baseConfig.isFixedLocation()) {
baseLocation = new Position(baseConfig.getX(), baseConfig.getY());
} else {
// make the base in the region specified for this team
// ensure bases are not created right next to asteroids (free by 4 * base_radius for now)
baseLocation = simulatedSpace.getRandomFreeLocationInRegion(random, 4 * Base.BASE_RADIUS,
thisTeamConfig.getInitialRegionULX(), thisTeamConfig.getInitialRegionULY(),
thisTeamConfig.getInitialRegionLRX(), thisTeamConfig.getInitialRegionLRY());
}
// get this team as well as the client
Team thisTeam = null;
for (Team team : teams) {
if (team.getTeamName().equalsIgnoreCase(teamName)) {
thisTeam = team;
break;
}
}
Base base = new Base(baseLocation, baseConfig.getTeamName(), thisTeam, true);
simulatedSpace.addObject(base);
thisTeam.addBase(base);
}
/**
* If there are flags specified (presumably for capture the flag games), create them
* and match their color to their team. Randomly choose their starting location
* from the specified set of starting locations.
*/
if (simConfig.getFlags() != null) {
for (FlagConfig flagConfig : simConfig.getFlags()) {
// get the right team to match the flag
Team thisTeam = null;
for (Team team : teams) {
if (team.getTeamName().equalsIgnoreCase(flagConfig.getTeamName())) {
thisTeam = team;
break;
}
}
int[] startX = flagConfig.getStartX();
int[] startY = flagConfig.getStartY();
Position[] startingPositions = new Position[startX.length];
for (int i = 0; i < startX.length; i++) {
startingPositions[i] = new Position(startX[i], startY[i]);
}
//System.out.println("Starting Locations are " + startingPositions);
Position flagPosition = startingPositions[random.nextInt(startingPositions.length)];
//System.out.println("Chosen location is " + flagPosition);
Flag flag = new Flag(flagPosition, flagConfig.getTeamName(), thisTeam, startingPositions);
simulatedSpace.addObject(flag);
}
}
}
/**
* Create a new fixed location asteroid following all rules of the config files
*
* Fixed asteroids specify a x, y location and a radius. They are always non-mineable.
*
* @param asteroidConfig
* @return
*/
private Asteroid createNewFixedAsteroid(FixedAsteroidConfig asteroidConfig) {
boolean mineable = asteroidConfig.isMineable();
boolean moveable = asteroidConfig.isMoveable();
int radius = asteroidConfig.getRadius();
// create the asteroid (no fuels in it either)
Asteroid asteroid = new Asteroid(new Position(asteroidConfig.getX(), asteroidConfig.getY()),
mineable, radius, moveable, 0, 0, 0);
// fixed ones can move (new change 2019, fixed just means it is pre-specified really)
if (asteroid.isMoveable()) {
Vector2D randomMotion = Vector2D.getRandom(random, asteroidConfig.getMaxInitialVelocity());
asteroid.getPosition().setTranslationalVelocity(randomMotion);
}
return asteroid;
}
/**
* Create a new asteroid following all rules of the config files
*
* Asteroids can either be fixed location or randomly generated. If they are
* fixed, they need x, y, and radius.
*
* @param asteroidConfig
* @return
*/
private Asteroid createNewRandomAsteroid(RandomAsteroidConfig asteroidConfig, boolean mineable) {
// choose if the asteroid is mine-able
double prob = random.nextDouble();
// asteroids
// choose the radius randomly for random asteroids
int radius = random.nextInt(Asteroid.MAX_ASTEROID_RADIUS - Asteroid.MIN_ASTEROID_RADIUS) + Asteroid.MIN_ASTEROID_RADIUS;
// choose if the asteroid is moving or stationary
prob = random.nextDouble();
boolean moveable = false;
if (prob < asteroidConfig.getProbabilityMoveable()) {
moveable = true;
}
// choose the asteroid mixture
double fuel = random.nextDouble() * asteroidConfig.getProbabilityFuelType();
double water = random.nextDouble() * asteroidConfig.getProbabilityWaterType();
double metals = random.nextDouble() * asteroidConfig.getProbabilityMetalsType();
// renormalize so it all adds to 1
double normalize = fuel + water + metals;
fuel = fuel / normalize;
water = water / normalize;
metals = metals / normalize;
// create the asteroid
Asteroid asteroid = new Asteroid(simulatedSpace.getRandomFreeLocation(random, radius * 2),
mineable, radius, moveable, fuel, water, metals);
if (asteroid.isMoveable()) {
Vector2D randomMotion = Vector2D.getRandom(random, asteroidConfig.getMaxInitialVelocity());
asteroid.getPosition().setTranslationalVelocity(randomMotion);
}
return asteroid;
}
/**
* Make the actual team (holds a pointer to the client)
*
* @param teamConfig
* @param teamClient
* @return
*/
public Team createTeam(HighLevelTeamConfig teamConfig, TeamClient teamClient, TeamClientConfig teamClientConfig) {
// it succeeded! Now make the team ships
int numShips = Math.min(simConfig.getMaximumInitialShipsPerTeam(), teamClientConfig.getNumberInitialShipsInTeam());
Team team = new Team(teamClient, teamClientConfig.getLadderName(), simConfig.getMaximumShipsPerTeam());
for (int s = 0; s < numShips; s++) {
// put the ships in the initial region for the team
// moved this to ship radius * 4 to keep ships away from each other initially
Position freeLocation = simulatedSpace.getRandomFreeLocationInRegion(random, Ship.SHIP_RADIUS * 4,
teamConfig.getInitialRegionULX(), teamConfig.getInitialRegionULY(),
teamConfig.getInitialRegionLRX(), teamConfig.getInitialRegionLRY());
System.out.println("Starting ship for team " + team.getTeamName() + " in location " + freeLocation);
Ship ship = new Ship(teamConfig.getTeamName(), team.getTeamColor(), freeLocation);
team.addShip(ship);
simulatedSpace.addObject(ship);
}
teams.add(team);
return team;
}
public TeamClientConfig getTeamClientConfig(HighLevelTeamConfig teamConfig, String configPath) throws SimulatorException {
String fileName = configPath + teamConfig.getConfigFile();
XStream xstream = new XStream();
xstream.alias("TeamClientConfig", TeamClientConfig.class);
xstream.allowTypesByRegExp(new String[] { ".*" });
TeamClientConfig lowLevelTeamConfig;
try {
lowLevelTeamConfig = (TeamClientConfig) xstream.fromXML(new File(fileName));
} catch (Exception e) {
throw new SimulatorException("Error parsing config team config file " + fileName + " at string " + e.getMessage());
}
return lowLevelTeamConfig;
}
/**
* Make the team client from the configuration file
*
* @param teamConfig
* @return
* @throws SimulatorException
*/
@SuppressWarnings("unchecked")
public TeamClient createTeamClient(HighLevelTeamConfig teamConfig, TeamClientConfig teamClientConfig) throws SimulatorException {
try {
// make a team client of the class specified in the config file
Class<TeamClient> newTeamClass = (Class<TeamClient>) Class.forName(teamClientConfig.getClassname());
TeamClient newTeamClient = (TeamClient) newTeamClass.newInstance();
Color teamColor = new Color(teamClientConfig.getTeamColorRed(), teamClientConfig.getTeamColorGreen(),
teamClientConfig.getTeamColorBlue());
newTeamClient.setTeamColor(teamColor);
newTeamClient.setTeamName(teamConfig.getTeamName());
newTeamClient.setKnowledgeFile(teamClientConfig.getKnowledgeFile());
newTeamClient.setRandom(random);
newTeamClient.setMaxNumberShips(simConfig.getMaximumShipsPerTeam());
newTeamClient.initialize(simulatedSpace.deepClone());
return newTeamClient;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new SimulatorException("Unable to make a new team client " + teamClientConfig.getClassname());
} catch (InstantiationException e) {
e.printStackTrace();
throw new SimulatorException("Unable to create a new instance of class " + teamClientConfig.getClassname());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new SimulatorException("Unable to create a new instance of class " + teamClientConfig.getClassname());
}
}
/**
* @return all objects in the simulator
*/
public Set<AbstractObject> getAllObjects() {
return simulatedSpace.allObjects;
}
/**
* Load in the configuration files
* @throws SimulatorException
*
*/
public SpaceSettlersConfig loadConfigFiles(JSAPResult parserConfig) throws SimulatorException {
String configFile = parserConfig.getString("configPath") + parserConfig.getString("simulatorConfigFile");
XStream xstream = new XStream();
xstream.alias("SpaceSettlersConfig", SpaceSettlersConfig.class);
xstream.alias("HighLevelTeamConfig", HighLevelTeamConfig.class);
xstream.alias("BaseConfig", BaseConfig.class);
xstream.alias("AsteroidConfig", RandomAsteroidConfig.class);
xstream.alias("FixedAsteroidConfig", FixedAsteroidConfig.class);
xstream.alias("FlagConfig", FlagConfig.class);
xstream.allowTypesByRegExp(new String[] { ".*" });
try {
simConfig = (SpaceSettlersConfig) xstream.fromXML(new File(configFile));
} catch (Exception e) {
throw new SimulatorException("Error parsing config file at string " + e.getMessage());
}
return simConfig;
}
/**
* Advance time one step
*/
void advanceTime() {
// update the team info (to send into the space for use by other teams)
updateTeamInfo();
ExecutorService teamExecutor;
if (debug) {
teamExecutor = Executors.newSingleThreadExecutor();
} else {
teamExecutor = Executors.newCachedThreadPool();
}
Map<Team, Future<Map<UUID,AbstractAction>>> clientActionFutures =
new HashMap<Team, Future<Map<UUID,AbstractAction>>>();
// get the actions from each team
for (Team team : teams) {
clientActionFutures.put(team, teamExecutor.submit(new AdvanceTimeCallable(team)));
}
for (Team team : teams) {
Map<UUID, AbstractAction> teamActions;
try {
teamActions = clientActionFutures.get(team).get();
} catch (InterruptedException e) {
//System.out.println("interruptedException, empty map");
//something went wrong...return empty map
teamActions = new HashMap<UUID, AbstractAction>();
} catch (ExecutionException e) {
//System.out.println("execution exception");
//something went wrong...return empty map
teamActions = new HashMap<UUID, AbstractAction>();
}
// get the actions for each ship
for (Ship ship : team.getShips()) {
// if the client forgets to set an action, set it to DoNothing
if (teamActions == null || !teamActions.containsKey(ship.getId())) {
teamActions.put(ship.getId(), new DoNothingAction());
}
ship.setCurrentAction(teamActions.get(ship.getId()));
}
/*
* herr0861
* Loop through the drones and assign them their actions from the team.
*/
for (UUID droneID : team.getDrones()) {
Drone drone = (Drone)simulatedSpace.getObjectById(droneID);
if (teamActions == null || !teamActions.containsKey(droneID)) {
drone.setCurrentAction(simulatedSpace.deepClone());
teamActions.put(droneID, drone.getCurrentAction());
}
/*
* herr0861
* TODO: Check if this does everything
* This allows the use to set in actions for the drones and have them be followed!
*/
drone.setCurrentAction(teamActions.get(drone.getId()));
}
} //End for loop through teams
teamExecutor.shutdown();
// get the power ups being used on this turn
Map<UUID, SpaceSettlersPowerupEnum> allPowerups = new HashMap<UUID, SpaceSettlersPowerupEnum>();
for (Team team : teams) {
Map<UUID, SpaceSettlersPowerupEnum> powerups = team.getTeamPowerups(simulatedSpace);
if (powerups != null) {
for (UUID key : powerups.keySet()) {
// verify power ups belong to this team
if (!team.isValidTeamID(key)) {
continue;
}
// get the object and ensure it can have a power up on it
AbstractObject swObject = simulatedSpace.getObjectById(key);
if (!(swObject instanceof AbstractActionableObject) || (swObject instanceof Drone)) {
continue;
}
// verify that the object has the power up associated with it
AbstractActionableObject actionableObject = (AbstractActionableObject) swObject;
if (actionableObject.isValidPowerup(powerups.get(key))) {
allPowerups.put(key, powerups.get(key));
}
}
}
}
// now update the physics on all objects
simulatedSpace.advanceTime(random, this.getTimestep(), allPowerups);
// and end any actions inside the team
for (Team team : teams) {
team.getTeamMovementEnd(simulatedSpace);
}
// handle purchases at the end of a turn (so ships will have movements next turn)
for (Team team : teams) {
// now get purchases for the team
Map<UUID, PurchaseTypes> purchases = team.getTeamPurchases(simulatedSpace);
handlePurchases(team, purchases);
}
// cleanup and remove dead weapons
simulatedSpace.cleanupDeadWeapons();
// cleanup and remove dead cores
simulatedSpace.cleanupDeadCores();
//cleanup and remove dead drones - herr0861 edit
simulatedSpace.cleanupDeadDrones();
// count up dead asteroids and ensure we generate as
// many mineable ones as existed before
int mineableAsteroids = simulatedSpace.cleanupAllAndCountMineableDeadAsteroids();
for (int i = 0; i < mineableAsteroids; i++) {
Asteroid asteroid = createNewRandomAsteroid(simConfig.getRandomAsteroids(), true);
simulatedSpace.addObject(asteroid);
}
// respawn any objects that should respawn - this includes Flags)
simulatedSpace.respawnDeadObjects(random);
// spawn new asteroids with a small probability (up to the maximum number allowed)
int maxAsteroids = simConfig.getRandomAsteroids().getMaximumNumberAsteroids();
int numAsteroids = simulatedSpace.getAsteroids().size();
if (numAsteroids < maxAsteroids) {
if (random.nextDouble() < ASTEROID_SPAWN_PROBABILITY) {
//System.out.println("Spawning a new asteroid");
boolean mineable = false;
if (random.nextDouble() < simConfig.getRandomAsteroids().getProbabilityMineable()) {
mineable = true;
}
Asteroid asteroid = createNewRandomAsteroid(simConfig.getRandomAsteroids(), mineable);
simulatedSpace.addObject(asteroid);
}
}
updateScores();
// for (Team team : teams) {
// for (Ship ship : team.getShips()) {
// System.out.println("Ship " + ship.getTeamName() + ship.getId() + " has resourcesAvailable " + ship.getMoney());
}
/**
* Update the team infomation that is sharable
*/
private void updateTeamInfo() {
LinkedHashSet<ImmutableTeamInfo> teamInfo = new LinkedHashSet<ImmutableTeamInfo>();
for (Team team : teams) {
teamInfo.add(new ImmutableTeamInfo(team));
}
simulatedSpace.setTeamInfo(teamInfo);
}
/**
* Handle purchases for a team
*
* @param team
* @param purchases
*/
private void handlePurchases(Team team, Map<UUID, PurchaseTypes> purchases) {
// handle teams that don't purchase
if (purchases == null) {
return;
}
for (UUID key : purchases.keySet()) {
PurchaseTypes purchase = purchases.get(key);
// skip the purchase if there isn't enough resourcesAvailable
if (!team.canAfford(purchase)) {
continue;
}
// get the object where the item is to be purchased (on on whom it is to be purchased)
AbstractActionableObject purchasingObject = (AbstractActionableObject) simulatedSpace.getObjectById(key);
// can only make purchases for your team
if (!purchasingObject.getTeamName().equalsIgnoreCase(team.getTeamName())) {
continue;
}
switch (purchase) {
case BASE:
// only purchase if this is a ship (can't buy a base next to a base)
if (purchasingObject instanceof Ship) {
Ship ship = (Ship) purchasingObject;
// set the base just away from the ship (to avoid a collision)
Position newPosition = simulatedSpace.getRandomFreeLocationInRegion(random,
Base.BASE_RADIUS, (int) ship.getPosition().getX(),
(int) ship.getPosition().getY(), (6 * (ship.getRadius() + Base.BASE_RADIUS)));
// make the new base and add it to the lists
Base base = new Base(newPosition, team.getTeamName(), team, false);
simulatedSpace.addObject(base);
team.addBase(base);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
}
break;
case SHIP:
// can only buy if there are enough ships
if (team.getShips().size() >= team.getMaxNumberShips())
break;
// Ships can only be purchased near a base (which launches them)
if (purchasingObject instanceof Base) {
Base base = (Base) purchasingObject;
// set the new ship just away from the base (to avoid a collision)
Position newPosition = simulatedSpace.getRandomFreeLocationInRegion(random,
Ship.SHIP_RADIUS, (int) base.getPosition().getX(),
(int) base.getPosition().getY(), (10 * (base.getRadius() + Ship.SHIP_RADIUS)));
// make the new ship and add it to the lists
Ship ship = new Ship(team.getTeamName(), team.getTeamColor(), newPosition);
simulatedSpace.addObject(ship);
team.addShip(ship);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
}
break;
case CORE: //herr0861 edit
if (purchasingObject instanceof Ship) { //only a ship can buy cores
Ship ship = (Ship) purchasingObject;
//Give the ship a core.
ship.incrementCores(1);
//Charge the team
team.decrementAvailableResources(team.getCurrentCost(purchase));
System.out.println("Buying an AiCore");
}
break;
case DRONE: //herr0861 edit
if (purchasingObject instanceof Ship) { //only a ship can buy drones
Ship ship = (Ship) purchasingObject;
if (ship.getNumCores() > 0) { //can only purchase a drone if you have cores
ship.incrementCores(-1);//use the parent class's increment cores method with int parameter to charge the ship an AiCore since costs only use ResourcePiles
//herr0861return
//Add the drone
// make the new drone and add it to the lists
Position newPosition = simulatedSpace.getRandomFreeLocationInRegion(random,
Drone.DRONE_RADIUS, (int) ship.getPosition().getX(),
(int) ship.getPosition().getY(), (10 * (ship.getRadius() + Drone.DRONE_RADIUS)));
//Makes a new resource pile using the ship's, so we don't have to import ResourcePile here. Cleaner that way.
Drone drone = new Drone(team.getTeamName(), team.getTeamColor(), team, newPosition, ship.getResources());
drone.incrementCores(ship.getNumCores()); //add cores to the drone.
//remove the cores and resources from the ship that have been added to the drone
ship.resetAiCores();
ship.resetResources();
//Transfer the flag if the ship has it
if (ship.isCarryingFlag()) {
drone.addFlag(ship.getFlag());
ship.depositFlag(); //make the ship drop the flag
drone.getFlag().pickupFlag(drone); //the pickup method in the flag will automatically cause it to not be carried by the ship when the drone has it
}
//add the drone to the space and team list
//drone.setCurrentAction(simulatedSpace);
drone.setCurrentAction(drone.getDroneAction(simulatedSpace));
simulatedSpace.addObject(drone);
//System.out.println("Adding the following drone to space: [" + drone.toString() + "]");
team.addDrone(drone);
//Charge the team (This comes from the turned in resources, so shouldn't effect resources on the ship, but it would be interesting to be able to make up the difference with what you hold)
team.decrementAvailableResources(team.getCurrentCost(purchase));
System.out.println("Buying a Drone");
}
}
break;
case POWERUP_SHIELD:
purchasingObject.addPowerup(SpaceSettlersPowerupEnum.TOGGLE_SHIELD);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
System.out.println("Buying a shield");
break;
case POWERUP_EMP_LAUNCHER:
// only purchase if this is a ship (can't buy a base next to a base)
if (purchasingObject instanceof Ship) {
purchasingObject.addPowerup(SpaceSettlersPowerupEnum.FIRE_EMP);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
System.out.println("Buying a emp launcher");
}
break;
case POWERUP_DOUBLE_BASE_HEALING_SPEED:
// this can only be purchased on bases
if (purchasingObject instanceof Base) {
purchasingObject.addPowerup(SpaceSettlersPowerupEnum.DOUBLE_BASE_HEALING_SPEED);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
System.out.println("Buying a healing doubler for a base");
}
break;
case POWERUP_DOUBLE_MAX_ENERGY:
purchasingObject.addPowerup(SpaceSettlersPowerupEnum.DOUBLE_MAX_ENERGY);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
System.out.println("Buying a energy doubler");
break;
case POWERUP_DOUBLE_WEAPON_CAPACITY:
purchasingObject.addPowerup(SpaceSettlersPowerupEnum.DOUBLE_WEAPON_CAPACITY);
// charge the team for the purchase
team.decrementAvailableResources(team.getCurrentCost(purchase));
team.updateCost(purchase);
System.out.println("Buying a weapons doubler");
break;
case NOTHING:
break;
default:
break;
}
}
}
/**
* Updates the scores for the teams
*/
private void updateScores() {
if (simConfig.getScoringMethod().equalsIgnoreCase("Resources")) {
for (Team team : teams) {
team.setScore(team.getSummedTotalResources());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("ResourcesAndCores")) {
for (Team team : teams) {
team.setScore(team.getSummedTotalResources() + 100.0 * team.getTotalCoresCollected());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("Beacons")) {
for (Team team : teams) {
int beacons = 0;
for (Ship ship : team.getShips()) {
beacons += ship.getNumBeacons();
}
team.setScore(beacons);
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("Kills")) {
for (Team team : teams) {
team.setScore(team.getTotalKillsInflicted());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("Hits")) {
for (Team team : teams) {
team.setScore(team.getTotalHitsInflicted());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("Damage")) {
for (Team team : teams) {
team.setScore(team.getTotalDamageInflicted());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("DamageCorrected")) {
for (Team team : teams) {
// not subtracting damage received because it is a negative number (inflicted is positive)
team.setScore(1000* team.getTotalKillsInflicted() + team.getTotalDamageInflicted() + team.getTotalDamageReceived());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("DamageCorrected2018")) {
for (Team team : teams) {
// not subtracting damage received because it is a negative number (inflicted is positive)
team.setScore(1000* team.getTotalKillsInflicted() + team.getTotalDamageInflicted() + team.getTotalDamageReceived() -
(1000 * ((team.getTotalKillsReceived() + 1) * team.getTotalKillsReceived()) / 2.0) +
(team.getSummedTotalResources() / 2.0));
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("KillAssistsAndCores")) {
// revised from original kill death ratio to get rid of suicide issues (by tagging deaths)
for (Team team : teams) {
// adding one to the denominator to handle divide by zero issues
double numerator = (double) team.getTotalKillsInflicted() + team.getTotalAssistsInflicted() + team.getTotalCoresCollected();
double denominator = team.getTotalKillsReceived() + 1.0;
team.setScore(numerator/denominator);
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("KillsMinusDeathsPlusCores")) {
// revised from original kill death ratio to get rid of suicide issues (by tagging deaths)
for (Team team : teams) {
// adding one to the denominator to handle divide by zero issues
double kills = (double) team.getTotalKillsInflicted() + team.getTotalAssistsInflicted();
double deaths = team.getTotalKillsReceived();
double cores = team.getTotalCoresCollected();
team.setScore(kills - deaths + cores);
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("Cores")) {
for (Team team : teams) {
team.setScore(team.getTotalCoresCollected());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("Flags")) {
// this scores by the raw number of flags collected (competitive ladder)
for (Team team : teams) {
team.setScore(team.getTotalFlagsCollected());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("FlagsPlusCores")) {
// this scores by the raw number of flags collected (competitive ladder)
for (Team team : teams) {
team.setScore(team.getTotalFlagsCollected() + team.getTotalCoresCollected());
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("TotalFlagsMinusKills")) {
// this scores by the raw number of flags collected (competitive ladder) minus any kills from either team
int totalFlags = 0;
int totalKills = 0;
for (Team team : teams) {
totalFlags += team.getTotalFlagsCollected();
totalKills += team.getTotalKillsInflicted();
}
for (Team team : teams) {
team.setScore(totalFlags - totalKills);
}
} else if (simConfig.getScoringMethod().equalsIgnoreCase("TotalFlags")) {
// this score sums the flags for the two sides (cooperative ladder)
int totalFlags = 0;
for (Team team : teams) {
totalFlags += team.getTotalFlagsCollected();
}
for (Team team : teams) {
team.setScore(totalFlags);
}
} else {
System.err.println("Error: Scoring method " + simConfig.getScoringMethod() + " is not recognized. Scores will all be 0.");
}
}
/**
* Main control loop of the simulator
* @throws SimulatorException
*/
public void run() throws SimulatorException {
if (gui != null) {
gui.redraw();
}
// run the game loop until the maximum time has elapsed
// if the pause is activated, just wait
for (timestep = 0; timestep < simConfig.getSimulationSteps(); timestep++) {
while (isPaused()) {
mySleep(50);
}
advanceTime();
if (gui != null) {
gui.redraw();
mySleep(graphicsSleep);
}
if (timestep % 5000 == 0) {
System.out.println("On time step " + timestep);
// print out the score every 5000 steps for debugging
for (Team team : teams) {
String str = "Team: " + team.getLadderName() + " scored " + team.getScore();
System.out.println(str);
}
}
}
// update the team info (to send into the space for use by other teams)
updateTeamInfo();
// shutdown all the teams
shutdownTeams();
}
/**
* Called after the simulation ends so the clients all cleanly shutdown
*/
public void shutdownTeams() {
for (Team team : teams) {
team.shutdownClients(simulatedSpace);
}
}
/**
* Returns the current timestep
* @return
*/
public int getTimestep() {
return timestep;
}
/**
* Returns the list of teams
* @return
*/
public Set<Team> getTeams() {
return teams;
}
/**
* Inner class to do parallel actions from clients
* @author amy
*
*/
class AdvanceTimeCallable implements Callable<Map<UUID,AbstractAction>>{
private Team team;
AdvanceTimeCallable(Team team){
this.team = team;
}
public Map<UUID,AbstractAction> call() throws Exception {
if(this.team != null){
return this.team.getTeamMovementStart(simulatedSpace);
}else{
//something went wrong...lets return empty map
return new HashMap<UUID, AbstractAction>();
}
}
}
/**
* Returns the physics engine (should only be called outside of the clients because they don't have access to this for security)
* @return
*/
public Toroidal2DPhysics getSimulatedSpace() {
return simulatedSpace;
}
/**
* Is the simulator paused?
* @return
*/
public boolean isPaused() {
return isPaused;
}
/**
* Set the paused state (called from the GUI)
* @param isPaused
*/
public void setPaused(boolean isPaused) {
this.isPaused = isPaused;
}
/**
* Set the sleep (called by the GUI)
* @return
*/
public int getGraphicsSleep() {
return graphicsSleep;
}
/**
* Get the sleep (for the GUI)
* @param graphicsSleep
*/
public void setGraphicsSleep(int graphicsSleep) {
this.graphicsSleep = graphicsSleep;
}
} |
package com.ams.pageobject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.ams.testsetup.SetUp;
public class SignUpFieldsEmpty extends SetUp {
//locators to find the element on web page
By email = By.name("email");
By Firstname = By.name("firstname");
By Lastname = By.name("lastname");
By Designation = By.name("designation");
By Role = By.name("role");
By Password = By.name("password");
By Confirmpwd = By.name("confirm");
By signup = By.tagName("span");
//to verify email field is empty
public boolean VerifyEmailEmpty() {
driver.findElement(signup).click();
WebElement emailEmpty = driver.findElement(email);
if(emailEmpty.getAttribute("value").isEmpty()){
return true;
}
return false;
}
//verify first name field is empty
public boolean VerifyFirstNameEmpty() {
driver.findElement(signup).click();
WebElement firstnameEmpty = driver.findElement(Firstname);
if(firstnameEmpty.getAttribute("value").isEmpty()){
return true;
}
return false;
}
//to verify last name field is empty
public boolean VerifyLastNameEmpty() {
driver.findElement(signup).click();
WebElement LastnameEmpty = driver.findElement(Firstname);
if(LastnameEmpty.getAttribute("value").isEmpty()){
return true;
}
return false;
}
//to verify designation field is empty
public boolean VerifyDesignationEmpty() {
driver.findElement(signup).click();
WebElement DesignationEmpty = driver.findElement(Firstname);
if(DesignationEmpty.getAttribute("value").isEmpty()){
return true;
}
return false;
}
//to verify password field is empty
public boolean VerifyPasswordEmpty() {
driver.findElement(signup).click();
WebElement passwordEmpty = driver.findElement(Firstname);
if(passwordEmpty.getAttribute("value").isEmpty()){
return true;
}
return false;
}
//to verify confirm password field is empty
public boolean VerifyConfirmpwdEmpty() {
driver.findElement(signup).click();
WebElement confirpwdEmpty = driver.findElement(Firstname);
if(confirpwdEmpty.getAttribute("value").isEmpty()){
return true;
}
return false;
}
} |
package com.englishtown.promises;
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.*;
public class PromiseTest {
private Runnable<Promise<Integer, Integer>, Integer> onSuccess = new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
return null;
}
};
private Runnable<Promise<Integer, Integer>, Value<Integer>> onFail = new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
return null;
}
};
private Runnable<Value<Integer>, Value<Integer>> onProgress = new Runnable<Value<Integer>, Value<Integer>>() {
@Override
public Value<Integer> run(Value<Integer> value) {
return value;
}
};
private Fail<Integer, Integer> fail = new Fail<>();
private Fail<Object, Object> fail2 = new Fail<>();
private Object sentinel = new Object();
private Object other = new Object();
@Test
public void testPromise_should_return_a_promise() {
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(null));
}
@Test
public void testPromise_should_allow_a_single_callback_function() {
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(onSuccess));
}
@Test
public void testPromise_should_allow_a_callback_and_errback_function() {
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(onSuccess, onFail));
}
@Test
public void testPromise_should_allow_a_callback_errback_and_progback_function() {
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(onSuccess, onFail, onProgress));
}
// 'should allow null and undefined': function() {
// assert.isFunction(defer().promise.then().then);
// assert.isFunction(defer().promise.then(null).then);
// assert.isFunction(defer().promise.then(null, null).then);
// assert.isFunction(defer().promise.then(null, null, null).then);
// assert.isFunction(defer().promise.then(undef).then);
// assert.isFunction(defer().promise.then(undef, undef).then);
// assert.isFunction(defer().promise.then(undef, undef, undef).then);
@Test
public void testPromise_should_allow_functions_and_null_or_undefined_to_be_mixed() {
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(null, onFail));
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(null, null, onProgress));
assertNotNull(new When<Integer, Integer>().defer().getPromise().then(null, onFail, onProgress));
}
@Test
public void testPromise_should_preserve_object_whose_valueOf_differs_from_original_object() {
Done<Date, Integer> done = new Done<>();
Deferred<Date, Integer> d = new When<Date, Integer>().defer();
final Date expected = new Date();
d.getPromise().then(
new Runnable<Promise<Date, Integer>, Date>() {
@Override
public Promise<Date, Integer> run(Date value) {
assertEquals(expected, value);
return null;
}
},
new Runnable<Promise<Date, Integer>, Value<Date>>() {
@Override
public Promise<Date, Integer> run(Value<Date> value) {
fail();
return null;
}
}
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(expected);
done.assertSuccess();
}
@Test
public void testPromise_should_forward_result_when_callback_is_null() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
null,
fail.onFail
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(1, value.intValue());
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testPromise_should_forward_callback_result_to_next_callback() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
When<Integer, Integer> w1 = new When<>();
return w1.resolve(value + 1);
}
},
fail.onFail
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(2, value.intValue());
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testPromise_should_forward_undefined() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
// intentionally return undefined
return null;
}
},
fail.onFail
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertNull(value);
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testPromise_should_forward_undefined_rejection_value() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
// presence of rejection handler is enough to switch back
// to resolve mode, even though it returns undefined.
// The ONLY way to propagate a rejection is to re-throw or
// return a rejected promise;
return null;
}
}
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertNull(value);
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testPromise_should_forward_promised_callback_result_value_to_next_callback() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
Deferred<Integer, Integer> d1 = new When<Integer, Integer>().defer();
d1.getResolver().resolve(value + 1);
return d1.getPromise();
}
},
fail.onFail
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(2, value.intValue());
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testPromise_should_switch_from_callbacks_to_errbacks_when_callback_returns_a_rejection() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
Deferred<Integer, Integer> d1 = new When<Integer, Integer>().defer();
d1.getResolver().reject(value + 1);
return d1.getPromise();
}
},
fail.onFail
).then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
assertEquals(2, value.value.intValue());
return null;
}
}
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testPromise_should_switch_from_callbacks_to_errbacks_when_callback_throws() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
throw new RuntimeException();
}
},
fail.onFail
).then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
assertNotNull(value.error);
return null;
}
}
).then(done.onSuccess, done.onFail);
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testPromise_should_switch_from_errbacks_to_callbacks_when_errback_does_not_explicitly_propagate() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
When<Integer, Integer> w1 = new When<>();
return w1.resolve(value.value + 1);
}
}
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(2, value.intValue());
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testPromise_should_switch_from_errbacks_to_callbacks_when_errback_returns_a_resolution() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
Deferred<Integer, Integer> d1 = new When<Integer, Integer>().defer();
d1.getResolver().resolve(value.value + 1);
return d1.getPromise();
}
}
).then(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(2, value.intValue());
return null;
}
},
fail.onFail
).then(done.onSuccess, done.onFail);
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testPromise_should_propagate_rejections_when_errback_throws() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
throw new RuntimeException();
}
}
).then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
assertNotNull(value.error);
return null;
}
}
).then(done.onSuccess, done.onFail);
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testPromise_should_propagate_rejections_when_errback_returns_a_rejection() {
Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
d.getPromise().then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
Deferred<Integer, Integer> d1 = new When<Integer, Integer>().defer();
d1.getResolver().reject(value.value + 1);
return d1.getPromise();
}
}
).then(
fail.onSuccess,
new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
assertEquals(2, value.value.intValue());
return null;
}
}
).then(done.onSuccess, done.onFail);
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testPromise_should_call_progback() {
final Done<Object, Object> done = new Done<>();
Deferred<Object, Object> d = new When<>().defer();
final Object expected = new Object();
d.getPromise().then(null, null, new Runnable<Value<Object>, Value<Object>>() {
@Override
public Value<Object> run(Value<Object> value) {
assertEquals(expected, value.value);
done.success = true;
return null;
}
});
d.getResolver().progress(expected);
done.assertSuccess();
}
@Test
public void testAlways_should_return_a_promise() {
When<Object, Object> when = new When<>();
PromiseExt<Object, Object> p = (PromiseExt<Object, Object>) when.defer().getPromise();
assertNotNull(p.always(null));
}
@Test
public void testAlways_should_register_callback() {
final Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
((PromiseExt<Integer, Integer>) d.getPromise()).always(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(1, value.intValue());
done.success = true;
return null;
}
});
d.getResolver().resolve(1);
done.assertSuccess();
}
@Test
public void testAlways_should_register_errback() {
final Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
((PromiseExt<Integer, Integer>) d.getPromise()).always(
new Runnable<Promise<Integer, Integer>, Integer>() {
@Override
public Promise<Integer, Integer> run(Integer value) {
assertEquals(1, value.intValue());
done.success = true;
return null;
}
});
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testAlways_should_register_progback() {
final Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
((PromiseExt<Integer, Integer>) d.getPromise()).always(
null,
new Runnable<Value<Integer>, Value<Integer>>() {
@Override
public Value<Integer> run(Value<Integer> value) {
assertEquals(1, value.value.intValue());
done.success = true;
return null;
}
});
d.getResolver().progress(1);
done.assertSuccess();
}
@Test
public void testOtherwise_should_return_a_promise() {
PromiseExt<Integer, Integer> p = (PromiseExt<Integer, Integer>) new When<Integer, Integer>().defer().getPromise();
assertNotNull(p.otherwise(null));
}
@Test
public void testOtherwise_should_register_errback() {
final Done<Integer, Integer> done = new Done<>();
Deferred<Integer, Integer> d = new When<Integer, Integer>().defer();
PromiseExt<Integer, Integer> p = (PromiseExt<Integer, Integer>) d.getPromise();
p.otherwise(new Runnable<Promise<Integer, Integer>, Value<Integer>>() {
@Override
public Promise<Integer, Integer> run(Value<Integer> value) {
assertEquals(1, value.value.intValue());
done.success = true;
return null;
}
});
d.getResolver().reject(1);
done.assertSuccess();
}
@Test
public void testYield_should_return_a_promise() {
PromiseExt<Object, Object> p = (PromiseExt<Object, Object>) new When<>().defer().getPromise();
assertNotNull(p.yield(null));
}
@Test
public void testYield_should_fulfill_with_the_supplied_value() {
Done<Object, Object> done = new Done<>();
When<Object, Object> when = new When<>();
PromiseExt<Object, Object> p = (PromiseExt<Object, Object>) when.resolve(other);
p.yield(sentinel).then(
new Runnable<Promise<Object, Object>, Object>() {
@Override
public Promise<Object, Object> run(Object value) {
assertEquals(sentinel, value);
return null;
}
},
fail2.onFail
).then(done.onSuccess, done.onFail);
done.assertSuccess();
}
@Test
public void testYield_should_fulfill_with_the_value_of_a_fulfilled_promise() {
Done<Object, Object> done = new Done<>();
When<Object, Object> when = new When<>();
PromiseExt<Object, Object> p = (PromiseExt<Object, Object>) when.resolve(other);
p.yield(when.resolve(sentinel)).then(
new Runnable<Promise<Object, Object>, Object>() {
@Override
public Promise<Object, Object> run(Object value) {
assertEquals(sentinel, value);
return null;
}
}).then(done.onSuccess, done.onFail);
done.assertSuccess();
}
@Test
public void testYield_should_reject_with_the_reason_of_a_rejected_promise() {
Done<Object, Object> done = new Done<>();
When<Object, Object> when = new When<>();
PromiseExt<Object, Object> p = (PromiseExt<Object, Object>) when.resolve(other);
p.yield(when.reject(sentinel)).then(
fail2.onSuccess,
new Runnable<Promise<Object, Object>, Value<Object>>() {
@Override
public Promise<Object, Object> run(Value<Object> reason) {
assertEquals(sentinel, reason.value);
return null;
}
}).then(done.onSuccess, done.onFail);
done.assertSuccess();
}
// 'spread': {
// 'should return a promise': function() {
// assert.isFunction(defer().promise.spread().then);
// 'should apply onFulfilled with array as argument list': function(done) {
// var expected = [1, 2, 3];
// when.resolve(expected).spread(function() {
// assert.equals(slice.call(arguments), expected);
// }).always(done);
// 'should resolve array contents': function(done) {
// var expected = [when.resolve(1), 2, when.resolve(3)];
// when.resolve(expected).spread(function() {
// assert.equals(slice.call(arguments), [1, 2, 3]);
// }).always(done);
// 'should reject if any item in array rejects': function(done) {
// var expected = [when.resolve(1), 2, when.reject(3)];
// when.resolve(expected)
// .spread(fail)
// .then(
// fail,
// function() {
// assert(true);
// ).always(done);
// 'when input is a promise': {
// 'should apply onFulfilled with array as argument list': function(done) {
// var expected = [1, 2, 3];
// when.resolve(when.resolve(expected)).spread(function() {
// assert.equals(slice.call(arguments), expected);
// }).always(done);
// 'should resolve array contents': function(done) {
// var expected = [when.resolve(1), 2, when.resolve(3)];
// when.resolve(when.resolve(expected)).spread(function() {
// assert.equals(slice.call(arguments), [1, 2, 3]);
// }).always(done);
// 'should reject if input is a rejected promise': function(done) {
// var expected = when.reject([1, 2, 3]);
// when.resolve(expected)
// .spread(fail)
// .then(
// fail,
// function() {
// assert(true);
// ).always(done);
} |
package com.github.davidmoten.geo;
import static com.github.davidmoten.geo.Base32.decodeBase32;
import static com.github.davidmoten.geo.Base32.encodeBase32;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Unit tests for {@link Base32}.
*
* @author dave
*
*/
public class Base32Test {
@Test
public void testEncodePositiveInteger() {
assertEquals("15pn7", encodeBase32(1234567));
}
@Test
public void testEncodesZero() {
assertEquals("0", encodeBase32(0));
}
@Test
public void testEncodesNegativeInteger() {
assertEquals("-3v", encodeBase32(-123));
}
@Test
public void testDecodeToPositiveInteger() {
assertEquals(1234567, decodeBase32("15pn7"));
}
@Test
public void testDecodeToZero() {
assertEquals("0", encodeBase32(0));
assertEquals(0, decodeBase32("0"));
}
@Test
public void testDecodeThenEncodeIsIdentity() {
assertEquals("1000", encodeBase32(decodeBase32("1000")));
}
@Test
public void testDecodeManyZeros() {
assertEquals(0, decodeBase32("0000000"));
}
@Test
public void testDecodeOneZero() {
assertEquals(0, decodeBase32("0"));
}
@Test
public void testDecodeToNegativeInteger() {
assertEquals("-3v", encodeBase32(-123));
assertEquals(-123, decodeBase32("-3v"));
}
@Test(expected = IllegalArgumentException.class)
public void testGetCharIndexThrowsExceptionWhenNonBase32CharacterGiven() {
Base32.getCharIndex('?');
}
@Test
public void getCoverageOfConstructorAndCheckConstructorIsPrivate() {
TestingUtil.callConstructorAndCheckIsPrivate(Base32.class);
}
} |
package com.jcabi.github;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Test;
public class RtRepoCommitsITCase {
/**
* RtRepoCommits can fetch commits.
* @throws Exception if there is no github key provided
*/
@Test
public final void fetchCommits() throws Exception {
final Iterator<Commit> iterator = repo().commits().iterate().iterator();
final List<String> shas = new ArrayList<String>();
shas.add("1aa4af45aa2c56421c3d911a0a06da513a7316a0");
shas.add("940dd5081fada0ead07762933036bf68a005cc40");
shas.add("05940dbeaa6124e4a87d9829fb2fce80b713dcbe");
shas.add("51cabb8e759852a6a40a7a2a76ef0afd4beef96d");
shas.add("11bd4d527236f9cb211bc6667df06fde075beded");
int existsCount = 0;
while (iterator.hasNext()) {
if (shas.contains(iterator.next().sha())) {
existsCount += 1;
}
}
MatcherAssert.assertThat(
existsCount,
Matchers.equalTo(shas.size())
);
}
/**
* Create and return repo to test.
* @return Repo
* @throws Exception If some problem inside
*/
private static Repo repo() throws Exception {
final String key = System.getProperty("failsafe.github.key");
Assume.assumeThat(key, Matchers.notNullValue());
return new RtGithub(key).repos().get(
new Coordinates.Simple("jcabi", "jcabi-github")
);
}
} |
package com.levelup.java.string;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
public class SplitStrings {
private static final Logger logger = Logger.getLogger(SplitStrings.class);
private static final String CONSTANT_STRING = "The Dog goes woof, The cat goes meow, the cow says moo, the duck says quack";
@Test
public void split_string_using_stringtokenizer_java () {
StringTokenizer stringTokenizer = new StringTokenizer(CONSTANT_STRING);
int numberOfTokens = stringTokenizer.countTokens();
while (stringTokenizer.hasMoreElements()) {
logger.info(stringTokenizer.nextElement());
}
assertTrue(numberOfTokens == 16);
}
@Test
public void split_string_using_string_split_java () {
String delims = "[ ]+";
String[] tokens = CONSTANT_STRING.split(delims);
logger.info(Arrays.toString(tokens));
assertTrue(tokens.length == 16);
}
@Test
public void split_string_whitespace_using_guava () {
List<String> elementsInString = Lists.newArrayList(Splitter.on(" ").split(CONSTANT_STRING));
logger.info(elementsInString);
assertTrue(elementsInString.size() == 16);
}
@Test
public void split_string_white_space_using_apache_commons () {
String[] elementsInString = StringUtils.split(CONSTANT_STRING);
logger.info(Arrays.toString(elementsInString));
assertTrue(elementsInString.length == 16);
}
} |
package com.orasi.core.angular;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orasi.core.by.angular.ByNG;
import com.orasi.core.by.angular.WaitForAngularRequestsToFinish;
import com.orasi.core.by.angular.internal.ByAngular;
import com.orasi.core.by.angular.internal.ByAngularButtonText;
import com.orasi.core.by.angular.internal.ByAngularController;
import com.orasi.core.by.angular.internal.ByAngularModel;
import com.orasi.core.by.angular.internal.ByAngularRepeater;
import com.orasi.utils.Sleeper;
import com.orasi.utils.TestEnvironment;
public class TestByAngular extends TestEnvironment{
@BeforeTest(groups ={"regression", "interfaces", "ByAngularModel", "dev"})
@Parameters({ "runLocation", "browserUnderTest", "browserVersion",
"operatingSystem", "environment" })
public void setup(@Optional String runLocation, String browserUnderTest,
String browserVersion, String operatingSystem, String environment) {
setApplicationUnderTest("Test App");
setBrowserUnderTest(browserUnderTest);
setBrowserVersion(browserVersion);
setOperatingSystem(operatingSystem);
if(getBrowserUnderTest().toLowerCase().equals("html") || getBrowserUnderTest().isEmpty() ) throw new SkipException("Test not valid for HTMLUnitDriver");
setRunLocation(runLocation);
setPageURL("http://cafetownsend-angular-rails.herokuapp.com/login");
setTestEnvironment(environment);
testStart("TestByAngularModel");
}
@AfterTest(groups ={"regression", "interfaces", "ByAngularModel", "dev"})
public void close(ITestContext testResults){
endTest("TestAlert", testResults);
}
@Test(groups ={"regression", "interfaces", "ByAngularModel"})
public void byAngular(){
ByAngular angular = new ByAngular(driver);
Assert.assertNotNull(angular);
}
@Test(groups ={"regression", "interfaces", "ByAngularModel"})
public void byAngularModel(){
ByAngularModel model = new ByAngularModel((JavascriptExecutor)driver.getDriver(), "user.name");
Assert.assertNotNull(model);
}
@Test(groups ={"regression", "interfaces", "ByAngularModel"})
public void byAngularButtonText(){
ByAngularButtonText buttonText = new ByAngularButtonText((JavascriptExecutor)driver.getDriver(), "Login");
Assert.assertNotNull(buttonText);
driver.findTextbox(ByNG.model("user.name")).set("Luke");
driver.findTextbox(ByNG.model("user.password")).set("Skywalker");
driver.findTextbox(ByNG.buttonText("Login")).click();
driver.findTextbox(ByNG.buttonText("Login")).syncHidden();
Sleeper.sleep(2000);
}
@Test(groups={"regression", "interfaces", "WaitForAngularRequestsToFinish"}, dependsOnMethods="byAngularButtonText")
public void waitForAngularRequestsToFinish(){
WaitForAngularRequestsToFinish.waitForAngularRequestsToFinish(driver);
}
@Test(groups ={"regression", "interfaces", "byAngularController"}, dependsOnMethods="byAngularButtonText")
public void byAngularController(){
ByAngularController controller = new ByAngularController((JavascriptExecutor)driver.getDriver(), "HeaderController");
Assert.assertNotNull(controller);
}
@Test(groups ={"regression", "interfaces", "byAngularController"}, dependsOnMethods="byAngularButtonText")
public void byAngularRepeater(){
ByAngularRepeater repeat = new ByAngularRepeater((JavascriptExecutor)driver.getDriver(), "employee in employees");
Assert.assertNotNull(repeat);
}
} |
package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
/**
* A handle to the Command Box in the GUI.
*/
public class CommandBoxHandle extends GuiHandle{
private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";
public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
super(guiRobot, primaryStage, stageTitle);
}
public void enterCommand(String command) {
setTextField(COMMAND_INPUT_FIELD_ID, command);
}
public String getCommandInput() {
return getTextFieldText(COMMAND_INPUT_FIELD_ID);
}
/**
* Enters the given command in the Command Box and presses enter.
*/
public void runCommand(String command) {
enterCommand(command);
pressEnter();
guiRobot.sleep(10);
if (command.equals("clear")) // any commands that has an alert dialog that pops out
pressEnter();
guiRobot.sleep(100); //Give time for the command to take effect
}
public HelpWindowHandle runHelpCommand() {
enterCommand("help");
pressEnter();
return new HelpWindowHandle(guiRobot, primaryStage);
}
} |
package jenkins.plugins.git;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.model.Action;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.plugins.git.GitStatus;
import hudson.util.LogTaskListener;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.plugins.git.traits.BranchDiscoveryTrait;
import jenkins.plugins.git.traits.TagDiscoveryTrait;
import jenkins.scm.api.SCMEventListener;
import jenkins.scm.api.SCMFile;
import jenkins.scm.api.SCMFileSystem;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMHeadEvent;
import jenkins.scm.api.SCMHeadObserver;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import jenkins.scm.api.SCMSourceCriteria;
import jenkins.scm.api.SCMSourceOwner;
import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction;
import jenkins.scm.api.trait.SCMSourceTrait;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import org.jvnet.hudson.test.TestExtension;
import org.mockito.Mockito;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class GitSCMSourceTest {
public static final String REMOTE = "git@remote:test/project.git";
@Rule
public JenkinsRule jenkins = new JenkinsRule();
private GitStatus gitStatus;
@Before
public void setup() {
gitStatus = new GitStatus();
}
@Test
public void testSourceOwnerTriggeredByDoNotifyCommit() throws Exception {
GitSCMSource gitSCMSource = new GitSCMSource("id", REMOTE, "", "*", "", false);
GitSCMSourceOwner scmSourceOwner = setupGitSCMSourceOwner(gitSCMSource);
jenkins.getInstance().add(scmSourceOwner, "gitSourceOwner");
gitStatus.doNotifyCommit(mock(HttpServletRequest.class), REMOTE, "master", "");
SCMHeadEvent event =
jenkins.getInstance().getExtensionList(SCMEventListener.class).get(SCMEventListenerImpl.class)
.waitSCMHeadEvent(1, TimeUnit.SECONDS);
assertThat(event, notNullValue());
assertThat((Iterable<SCMHead>) event.heads(gitSCMSource).keySet(), hasItem(is(new SCMHead("master"))));
verify(scmSourceOwner, times(0)).onSCMSourceUpdated(gitSCMSource);
}
private GitSCMSourceOwner setupGitSCMSourceOwner(GitSCMSource gitSCMSource) {
GitSCMSourceOwner owner = mock(GitSCMSourceOwner.class);
when(owner.hasPermission(Item.READ)).thenReturn(true, true, true);
when(owner.getSCMSources()).thenReturn(Collections.<SCMSource>singletonList(gitSCMSource));
return owner;
}
private interface GitSCMSourceOwner extends TopLevelItem, SCMSourceOwner {
}
@TestExtension
public static class SCMEventListenerImpl extends SCMEventListener {
SCMHeadEvent<?> head = null;
@Override
public void onSCMHeadEvent(SCMHeadEvent<?> event) {
synchronized (this) {
head = event;
notifyAll();
}
}
public SCMHeadEvent<?> waitSCMHeadEvent(long timeout, TimeUnit units)
throws TimeoutException, InterruptedException {
long giveUp = System.currentTimeMillis() + units.toMillis(timeout);
while (System.currentTimeMillis() < giveUp) {
synchronized (this) {
SCMHeadEvent h = head;
if (h != null) {
head = null;
return h;
}
wait(Math.max(1L, giveUp - System.currentTimeMillis()));
}
}
throw new TimeoutException();
}
}
@Issue("JENKINS-47526")
@Test
public void telescopeFetch() throws Exception {
GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git");
assertThat(GitSCMTelescope.of(instance), nullValue());
instance.setOwner(mock(SCMSourceOwner.class));
assertThat(GitSCMTelescope.of(instance), notNullValue());
instance.setTraits(Arrays.<SCMSourceTrait>asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
Map<SCMHead, SCMRevision> result = instance.fetch(SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"
),
new GitTagSCMRevision(
new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"
)));
instance.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
result = instance.fetch(SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"
)));
instance.setTraits(Collections.<SCMSourceTrait>singletonList(new TagDiscoveryTrait()));
result = instance.fetch(SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new GitTagSCMRevision(
new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"
)));
}
@Issue("JENKINS-47526")
@Test
public void telescopeFetchWithCriteria() throws Exception {
GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git");
assertThat(GitSCMTelescope.of(instance), nullValue());
instance.setOwner(mock(SCMSourceOwner.class));
assertThat(GitSCMTelescope.of(instance), notNullValue());
instance.setTraits(Arrays.<SCMSourceTrait>asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
Map<SCMHead, SCMRevision> result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"),
SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
),
new GitTagSCMRevision(
new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"
)));
result = instance.fetch(new MySCMSourceCriteria("README.md"),
SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"
)));
instance.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
)));
instance.setTraits(Collections.<SCMSourceTrait>singletonList(new TagDiscoveryTrait()));
result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null).result();
assertThat(result.values(), Matchers.<SCMRevision>containsInAnyOrder(
new GitTagSCMRevision(
new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"
)));
}
@Issue("JENKINS-47526")
@Test
public void telescopeFetchRevisions() throws Exception {
GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git");
assertThat(GitSCMTelescope.of(instance), nullValue());
instance.setOwner(mock(SCMSourceOwner.class));
assertThat(GitSCMTelescope.of(instance), notNullValue());
instance.setTraits(Arrays.<SCMSourceTrait>asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
Set<String> result = instance.fetchRevisions(null);
assertThat(result, containsInAnyOrder("foo", "bar", "manchu", "v1.0.0"));
instance.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
result = instance.fetchRevisions(null);
assertThat(result, containsInAnyOrder("foo", "bar", "manchu"));
instance.setTraits(Collections.<SCMSourceTrait>singletonList(new TagDiscoveryTrait()));
result = instance.fetchRevisions(null);
assertThat(result, containsInAnyOrder("v1.0.0"));
}
@Issue("JENKINS-47526")
@Test
public void telescopeFetchRevision() throws Exception {
GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git");
assertThat(GitSCMTelescope.of(instance), nullValue());
instance.setOwner(mock(SCMSourceOwner.class));
assertThat(GitSCMTelescope.of(instance), notNullValue());
instance.setTraits(Arrays.<SCMSourceTrait>asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
assertThat(instance.fetch(new SCMHead("foo"), null),
hasProperty("hash", is("6769413a79793e242c73d7377f0006c6aea95480")));
assertThat(instance.fetch(new SCMHead("bar"), null),
hasProperty("hash", is("3f0b897057d8b43d3b9ff55e3fdefbb021493470")));
assertThat(instance.fetch(new SCMHead("manchu"), null),
hasProperty("hash", is("a94782d8d90b56b7e0d277c04589bd2e6f70d2cc")));
assertThat(instance.fetch(new GitTagSCMHead("v1.0.0", 0L), null),
hasProperty("hash", is("315fd8b5cae3363b29050f1aabfc27c985e22f7e")));
}
@Issue("JENKINS-47526")
@Test
public void telescopeFetchRevisionByName() throws Exception {
GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git");
assertThat(GitSCMTelescope.of(instance), nullValue());
instance.setOwner(mock(SCMSourceOwner.class));
assertThat(GitSCMTelescope.of(instance), notNullValue());
instance.setTraits(Arrays.<SCMSourceTrait>asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
assertThat(instance.fetch("foo", null),
hasProperty("hash", is("6769413a79793e242c73d7377f0006c6aea95480")));
assertThat(instance.fetch("bar", null),
hasProperty("hash", is("3f0b897057d8b43d3b9ff55e3fdefbb021493470")));
assertThat(instance.fetch("manchu", null),
hasProperty("hash", is("a94782d8d90b56b7e0d277c04589bd2e6f70d2cc")));
assertThat(instance.fetch("v1.0.0", null),
hasProperty("hash", is("315fd8b5cae3363b29050f1aabfc27c985e22f7e")));
}
@Issue("JENKINS-47526")
@Test
public void telescopeFetchActions() throws Exception {
GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git");
assertThat(GitSCMTelescope.of(instance), nullValue());
AbstractGitSCMSourceTest.ActionableSCMSourceOwner owner =
Mockito.mock(AbstractGitSCMSourceTest.ActionableSCMSourceOwner.class);
when(owner.getSCMSource(instance.getId())).thenReturn(instance);
when(owner.getSCMSources()).thenReturn(Collections.<SCMSource>singletonList(instance));
instance.setOwner(owner);
assertThat(GitSCMTelescope.of(instance), notNullValue());
instance.setTraits(Arrays.<SCMSourceTrait>asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
List<Action> actions = instance.fetchActions(null, null);
assertThat(actions,
contains(allOf(
instanceOf(GitRemoteHeadRefAction.class),
hasProperty("remote", is("http://git.test/telescope.git")),
hasProperty("name", is("manchu"))
))
);
when(owner.getActions(GitRemoteHeadRefAction.class))
.thenReturn(Collections.singletonList((GitRemoteHeadRefAction) actions.get(0)));
assertThat(instance.fetchActions(new SCMHead("foo"), null, null), is(Collections.<Action>emptyList()));
assertThat(instance.fetchActions(new SCMHead("bar"), null, null), is(Collections.<Action>emptyList()));
assertThat(instance.fetchActions(new SCMHead("manchu"), null, null), contains(
instanceOf(PrimaryInstanceMetadataAction.class)));
assertThat(instance.fetchActions(new GitTagSCMHead("v1.0.0", 0L), null, null),
is(Collections.<Action>emptyList()));
}
@TestExtension
public static class MyGitSCMTelescope extends GitSCMTelescope {
@Override
public boolean supports(@NonNull String remote) {
return "http://git.test/telescope.git".equals(remote);
}
@Override
public void validate(@NonNull String remote, StandardCredentials credentials)
throws IOException, InterruptedException {
}
@Override
protected SCMFileSystem build(@NonNull String remote, StandardCredentials credentials,
@NonNull SCMHead head,
final SCMRevision rev) throws IOException, InterruptedException {
final String hash;
if (rev instanceof AbstractGitSCMSource.SCMRevisionImpl) {
hash = ((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash();
} else {
switch (head.getName()) {
case "foo":
hash = "6769413a79793e242c73d7377f0006c6aea95480";
break;
case "bar":
hash = "3f0b897057d8b43d3b9ff55e3fdefbb021493470";
break;
case "manchu":
hash = "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc";
break;
case "v1.0.0":
hash = "315fd8b5cae3363b29050f1aabfc27c985e22f7e";
break;
default:
return null;
}
}
return new SCMFileSystem(rev) {
@Override
public long lastModified() throws IOException, InterruptedException {
switch (hash) {
case "6769413a79793e242c73d7377f0006c6aea95480":
return 15086163840000L;
case "3f0b897057d8b43d3b9ff55e3fdefbb021493470":
return 15086173840000L;
case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc":
return 15086183840000L;
case "315fd8b5cae3363b29050f1aabfc27c985e22f7e":
return 15086193840000L;
}
return 0L;
}
@NonNull
@Override
public SCMFile getRoot() {
return new MySCMFile(hash);
}
};
}
@Override
public long getTimestamp(@NonNull String remote, StandardCredentials credentials, @NonNull String refOrHash)
throws IOException, InterruptedException {
switch (refOrHash) {
case "refs/heads/foo":
refOrHash = "6769413a79793e242c73d7377f0006c6aea95480";
break;
case "refs/heads/bar":
refOrHash = "3f0b897057d8b43d3b9ff55e3fdefbb021493470";
break;
case "refs/heads/manchu":
refOrHash = "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc";
break;
case "refs/tags/v1.0.0":
refOrHash = "315fd8b5cae3363b29050f1aabfc27c985e22f7e";
break;
}
switch (refOrHash) {
case "6769413a79793e242c73d7377f0006c6aea95480":
return 15086163840000L;
case "3f0b897057d8b43d3b9ff55e3fdefbb021493470":
return 15086173840000L;
case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc":
return 15086183840000L;
case "315fd8b5cae3363b29050f1aabfc27c985e22f7e":
return 15086193840000L;
}
return 0L;
}
@Override
public SCMRevision getRevision(@NonNull String remote, StandardCredentials credentials,
@NonNull String refOrHash)
throws IOException, InterruptedException {
switch (refOrHash) {
case "refs/heads/foo":
return new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"
);
case "refs/heads/bar":
return new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
);
case "refs/heads/manchu":
return new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"
);
case "refs/tags/v1.0.0":
return new GitTagSCMRevision(
new GitTagSCMHead("v1.0.0", 15086193840000L),
"315fd8b5cae3363b29050f1aabfc27c985e22f7e"
);
}
return null;
}
@Override
public Iterable<SCMRevision> getRevisions(@NonNull String remote, StandardCredentials credentials,
@NonNull Set<ReferenceType> referenceTypes)
throws IOException, InterruptedException {
return Arrays.<SCMRevision>asList(
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"
),
new AbstractGitSCMSource.SCMRevisionImpl(
new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"
),
new GitTagSCMRevision(
new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"
)
);
}
@Override
public String getDefaultTarget(@NonNull String remote, StandardCredentials credentials)
throws IOException, InterruptedException {
return "manchu";
}
private static class MySCMFile extends SCMFile {
private final String hash;
private final SCMFile.Type type;
public MySCMFile(String hash) {
this.hash = hash;
this.type = Type.DIRECTORY;
}
public MySCMFile(MySCMFile parent, String name, SCMFile.Type type) {
super(parent, name);
this.type = type;
this.hash = parent.hash;
}
@NonNull
@Override
protected SCMFile newChild(@NonNull String name, boolean assumeIsDirectory) {
return new MySCMFile(this, name, assumeIsDirectory ? Type.DIRECTORY : Type.REGULAR_FILE);
}
@NonNull
@Override
public Iterable<SCMFile> children() throws IOException, InterruptedException {
if (parent().isRoot()) {
switch (hash) {
case "6769413a79793e242c73d7377f0006c6aea95480":
return Collections.singleton(newChild("Jenkinsfile", false));
case "3f0b897057d8b43d3b9ff55e3fdefbb021493470":
return Arrays.asList(newChild("Jenkinsfile", false),
newChild("README.md", false));
case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc":
return Collections.singleton(newChild("README.md", false));
case "315fd8b5cae3363b29050f1aabfc27c985e22f7e":
return Collections.singleton(newChild("Jenkinsfile", false));
}
}
return Collections.emptySet();
}
@Override
public long lastModified() throws IOException, InterruptedException {
switch (hash) {
case "6769413a79793e242c73d7377f0006c6aea95480":
return 15086163840000L;
case "3f0b897057d8b43d3b9ff55e3fdefbb021493470":
return 15086173840000L;
case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc":
return 15086183840000L;
case "315fd8b5cae3363b29050f1aabfc27c985e22f7e":
return 15086193840000L;
}
return 0L;
}
@NonNull
@Override
protected Type type() throws IOException, InterruptedException {
switch (hash) {
case "6769413a79793e242c73d7377f0006c6aea95480":
switch (getPath()) {
case "Jenkinsfile":
return Type.REGULAR_FILE;
}
break;
case "3f0b897057d8b43d3b9ff55e3fdefbb021493470":
switch (getPath()) {
case "Jenkinsfile":
return Type.REGULAR_FILE;
case "README.md":
return Type.REGULAR_FILE;
}
break;
case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc":
switch (getPath()) {
case "README.md":
return Type.REGULAR_FILE;
}
break;
case "315fd8b5cae3363b29050f1aabfc27c985e22f7e":
switch (getPath()) {
case "Jenkinsfile":
return Type.REGULAR_FILE;
}
break;
}
return type == Type.DIRECTORY ? type : Type.NONEXISTENT;
}
@NonNull
@Override
public InputStream content() throws IOException, InterruptedException {
switch (hash) {
case "6769413a79793e242c73d7377f0006c6aea95480":
switch (getPath()) {
case "Jenkinsfile":
return new ByteArrayInputStream("pipeline{}".getBytes(StandardCharsets.UTF_8));
}
break;
case "3f0b897057d8b43d3b9ff55e3fdefbb021493470":
switch (getPath()) {
case "Jenkinsfile":
return new ByteArrayInputStream("pipeline{}".getBytes(StandardCharsets.UTF_8));
case "README.md":
return new ByteArrayInputStream("Welcome".getBytes(StandardCharsets.UTF_8));
}
break;
case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc":
switch (getPath()) {
case "README.md":
return new ByteArrayInputStream("Welcome".getBytes(StandardCharsets.UTF_8));
}
break;
case "315fd8b5cae3363b29050f1aabfc27c985e22f7e":
switch (getPath()) {
case "Jenkinsfile":
return new ByteArrayInputStream("pipeline{}".getBytes(StandardCharsets.UTF_8));
}
break;
}
throw new FileNotFoundException(getPath() + " does not exist");
}
}
}
private static class MySCMSourceCriteria implements SCMSourceCriteria {
private final String path;
private MySCMSourceCriteria(String path) {
this.path = path;
}
@Override
public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException {
return SCMFile.Type.REGULAR_FILE.equals(probe.stat(path).getType());
}
}
} |
package learning.java.util.regex;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class PatternTest {
public static final String REGEX_1 = "([PD]{1})-(\\d+)";
public static final String REGEX_2 = "([0-9.]*)\\/([0-9.]+)";
@Test
public void testUseage() {
Pattern pattern = Pattern.compile(REGEX_1);
Matcher matcher = pattern.matcher("P-4563");
assertThat(matcher.matches(), is(true));
assertThat(Pattern.matches(REGEX_1, "D-456"), is(true));
assertThat(Pattern.matches(REGEX_1, "D--456"), is(false));
assertThat(Pattern.matches(REGEX_1, "D-45D"), is(false));
}
@Test
public void testMatcher() {
Pattern pattern = Pattern.compile(REGEX_1);
Matcher matcher = pattern.matcher("P-4563");
assertThat(matcher.matches(), is(true));
assertThat(matcher.group(1), is("P"));
assertThat(matcher.group(2), is("4563"));
}
@Test
public void testMatcherForRegex2_1() {
Pattern pattern = Pattern.compile(REGEX_2);
Matcher matcher = pattern.matcher("3.4/4.5");
assertThat(matcher.matches(), is(true));
assertThat(matcher.group(1), is("3.4"));
assertThat(matcher.group(2), is("4.5"));
}
@Test
public void testMatcherForRegex2_2() {
Pattern pattern = Pattern.compile(REGEX_2);
Matcher matcher = pattern.matcher("3/4.5");
assertThat(matcher.matches(), is(true));
assertThat(matcher.group(1), is("3"));
assertThat(matcher.group(2), is("4.5"));
}
@Test
public void testMatcherForRegex2_3() {
Pattern pattern = Pattern.compile(REGEX_2);
Matcher matcher = pattern.matcher("3/5");
assertThat(matcher.matches(), is(true));
assertThat(matcher.group(1), is("3"));
assertThat(matcher.group(2), is("5"));
}
} |
package org.fcrepo.camel;
import org.apache.camel.Produce;
import org.apache.camel.Exchange;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
public class FedoraTransformTest extends CamelTestSupport {
@EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct:start")
protected ProducerTemplate template;
@Test
public void testTransform() throws Exception {
// Setup
Map<String, Object> headers = new HashMap<String, Object>();
headers.put(Exchange.HTTP_METHOD, "POST");
headers.put(Exchange.CONTENT_TYPE, "text/turtle");
final String fullPath = template.requestBodyAndHeaders(
"direct:setup", FedoraTestUtils.getTurtleDocument(), headers, String.class);
final String identifier = fullPath.replaceAll(FedoraTestUtils.getFcrepoBaseUri(), "");
// Test
template.sendBodyAndHeader(null, "FCREPO_IDENTIFIER",
identifier);
// Teardown
Map<String, Object> teardownHeaders = new HashMap<String, Object>();
teardownHeaders.put(Exchange.HTTP_METHOD, "DELETE");
teardownHeaders.put("FCREPO_IDENTIFIER", identifier);
template.sendBodyAndHeaders("direct:teardown", null, teardownHeaders);
// Assertions
resultEndpoint.expectedMessageCount(1);
resultEndpoint.expectedHeaderReceived("Content-Type", "application/json");
resultEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws IOException {
final String fcrepo_uri = FedoraTestUtils.getFcrepoEndpointUri();
from("direct:setup")
.to(fcrepo_uri);
from("direct:start")
.to(fcrepo_uri + "?accept=application/json&transform=default")
.to("mock:result");
from("direct:teardown")
.to(fcrepo_uri)
.to(fcrepo_uri + "?tombstone=true");
}
};
}
} |
package seedu.address.logic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.google.common.eventbus.Subscribe;
import seedu.address.commons.core.EventsCenter;
import seedu.address.commons.events.model.AddressBookChangedEvent;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.commons.events.ui.ShowHelpRequestEvent;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.ListCommand;
import seedu.address.logic.commands.SelectCommand;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.ReadOnlyTaskList;
import seedu.address.model.TaskList;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Description;
import seedu.address.model.task.Email;
import seedu.address.model.task.Priority;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.storage.StorageManager;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyTaskList latestSavedAddressBook;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(AddressBookChangedEvent abce) {
latestSavedAddressBook = new TaskList(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setUp() {
model = new ModelManager();
String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedAddressBook = new TaskList(model.getTaskList()); // last saved assumed to be up to date
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void tearDown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() {
String invalidCommand = " ";
assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command, confirms that a CommandException is not thrown and that the result message is correct.
* Also confirms that both the 'address book' and the 'last shown list' are as specified.
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List)
*/
private void assertCommandSuccess(String inputCommand, String expectedMessage,
ReadOnlyTaskList expectedAddressBook,
List<? extends ReadOnlyTask> expectedShownList) {
assertCommandBehavior(false, inputCommand, expectedMessage, expectedAddressBook, expectedShownList);
}
/**
* Executes the command, confirms that a CommandException is thrown and that the result message is correct.
* Both the 'address book' and the 'last shown list' are verified to be unchanged.
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List)
*/
private void assertCommandFailure(String inputCommand, String expectedMessage) {
TaskList expectedAddressBook = new TaskList(model.getTaskList());
List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList());
assertCommandBehavior(true, inputCommand, expectedMessage, expectedAddressBook, expectedShownList);
}
/**
* Executes the command, confirms that the result message is correct
* and that a CommandException is thrown if expected
* and also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal address book data are same as those in the {@code expectedAddressBook} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedAddressBook} was saved to the storage file. <br>
*/
private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage,
ReadOnlyTaskList expectedAddressBook,
List<? extends ReadOnlyTask> expectedShownList) {
try {
CommandResult result = logic.execute(inputCommand);
assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected);
assertEquals(expectedMessage, result.feedbackToUser);
} catch (CommandException e) {
assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected);
assertEquals(expectedMessage, e.getMessage());
}
//Confirm the ui display elements should contain the right data
assertEquals(expectedShownList, model.getFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedAddressBook, model.getTaskList());
assertEquals(expectedAddressBook, latestSavedAddressBook);
}
@Test
public void execute_unknownCommandWord() {
String unknownCommand = "uicfhmowqewca";
assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() {
assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskList(), Collections.emptyList());
assertTrue(helpShown);
}
@Test
public void execute_exit() {
assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT,
new TaskList(), Collections.emptyList());
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generatePerson(1));
model.addTask(helper.generatePerson(2));
model.addTask(helper.generatePerson(3));
assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskList(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandFailure("add wrong args wrong args", expectedMessage);
assertCommandFailure("add Valid Description 12345 e/valid@email.butNoPhonePrefix a/valid,address",
expectedMessage);
assertCommandFailure("add Valid Description p/1234 valid@email.butNoPrefix a/valid, address",
expectedMessage);
assertCommandFailure("add Valid Description p/12345 e/valid@email.butNoAddressPrefix valid, address",
expectedMessage);
}
@Test
public void execute_add_invalidPersonData() {
assertCommandFailure("add []\\[;] p/12345 e/valid@e.mail a/valid, address",
Description.MESSAGE_DESCRIPTION_CONSTRAINTS);
assertCommandFailure("add Valid Description p/not_numbers e/valid@e.mail a/valid, address",
Priority.MESSAGE_PRIORITY_CONSTRAINTS);
assertCommandFailure("add Valid Description p/12345 e/notAnEmail a/valid, address",
Email.MESSAGE_EMAIL_CONSTRAINTS);
assertCommandFailure("add Valid Description p/12345 e/valid@e.mail a/valid, address t/invalid_-[.tag",
Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.adam();
TaskList expectedAB = new TaskList();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandSuccess(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.adam();
// setup starting state
model.addTask(toBeAdded); // person already in internal address book
// execute command and verify result
assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_PERSON);
}
@Test
public void execute_list_showsAllPersons() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskList expectedAB = helper.generateAddressBook(2);
List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList();
// prepare address book state
helper.addToModel(model, 2);
assertCommandSuccess("list",
ListCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single person in the shown list, using visible index.
* @param commandWord to test assuming it targets a single person in the last shown list
* based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage)
throws Exception {
assertCommandFailure(commandWord , expectedMessage); //index missing
assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandFailure(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single person in the shown list, using visible index.
* @param commandWord to test assuming it targets a single person in the last shown list
* based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> personList = helper.generatePersonList(2);
// set AB state to 2 persons
model.resetData(new TaskList());
for (Task p : personList) {
model.addTask(p);
}
assertCommandFailure(commandWord + " 3", expectedMessage);
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectPerson() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threePersons = helper.generatePersonList(3);
TaskList expectedAB = helper.generateAddressBook(threePersons);
helper.addToModel(model, threePersons);
assertCommandSuccess("select 2",
String.format(SelectCommand.MESSAGE_SELECT_PERSON_SUCCESS, 2),
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredTaskList().get(1), threePersons.get(1));
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
@Test
public void execute_delete_removesCorrectPerson() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threePersons = helper.generatePersonList(3);
TaskList expectedAB = helper.generateAddressBook(threePersons);
expectedAB.removeTask(threePersons.get(1));
helper.addToModel(model, threePersons);
assertCommandSuccess("delete 2",
String.format(DeleteCommand.MESSAGE_DELETE_PERSON_SUCCESS, threePersons.get(1)),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandFailure("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generatePersonWithName("bla bla KEY bla");
Task pTarget2 = helper.generatePersonWithName("bla KEY bla bceofeia");
Task p1 = helper.generatePersonWithName("KE Y");
Task p2 = helper.generatePersonWithName("KEYKEYKEY sduauo");
List<Task> fourPersons = helper.generatePersonList(p1, pTarget1, p2, pTarget2);
TaskList expectedAB = helper.generateAddressBook(fourPersons);
List<Task> expectedList = helper.generatePersonList(pTarget1, pTarget2);
helper.addToModel(model, fourPersons);
assertCommandSuccess("find KEY",
Command.getMessageForPersonListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generatePersonWithName("bla bla KEY bla");
Task p2 = helper.generatePersonWithName("bla KEY bla bceofeia");
Task p3 = helper.generatePersonWithName("key key");
Task p4 = helper.generatePersonWithName("KEy sduauo");
List<Task> fourPersons = helper.generatePersonList(p3, p1, p4, p2);
TaskList expectedAB = helper.generateAddressBook(fourPersons);
List<Task> expectedList = fourPersons;
helper.addToModel(model, fourPersons);
assertCommandSuccess("find KEY",
Command.getMessageForPersonListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generatePersonWithName("bla bla KEY bla");
Task pTarget2 = helper.generatePersonWithName("bla rAnDoM bla bceofeia");
Task pTarget3 = helper.generatePersonWithName("key key");
Task p1 = helper.generatePersonWithName("sduauo");
List<Task> fourPersons = helper.generatePersonList(pTarget1, p1, pTarget2, pTarget3);
TaskList expectedAB = helper.generateAddressBook(fourPersons);
List<Task> expectedList = helper.generatePersonList(pTarget1, pTarget2, pTarget3);
helper.addToModel(model, fourPersons);
assertCommandSuccess("find key rAnDoM",
Command.getMessageForPersonListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper {
Task adam() throws Exception {
Description description = new Description("Adam Brown");
Priority privatePhone = new Priority("111111");
Email email = new Email("adam@gmail.com");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("longertag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Task(description, privatePhone, email, tags);
}
/**
* Generates a valid person using the given seed.
* Running this function with the same parameter values guarantees the returned person will have the same state.
* Each unique seed will generate a unique Task object.
*
* @param seed used to generate the person data field values
*/
Task generatePerson(int seed) throws Exception {
return new Task(
new Description("Task " + seed),
new Priority("" + Math.abs(seed)),
new Email(seed + "@email"),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the person given */
String generateAddCommand(Task p) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(p.getDescription().toString());
cmd.append(" e/").append(p.getDate());
cmd.append(" p/").append(p.getPriority());
UniqueTagList tags = p.getTags();
for (Tag t: tags) {
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
/**
* Generates an TaskList with auto-generated persons.
*/
TaskList generateAddressBook(int numGenerated) throws Exception {
TaskList taskList = new TaskList();
addToAddressBook(taskList, numGenerated);
return taskList;
}
/**
* Generates an TaskList based on the list of Persons given.
*/
TaskList generateAddressBook(List<Task> tasks) throws Exception {
TaskList taskList = new TaskList();
addToAddressBook(taskList, tasks);
return taskList;
}
/**
* Adds auto-generated Task objects to the given TaskList
* @param taskList The TaskList to which the Persons will be added
*/
void addToAddressBook(TaskList taskList, int numGenerated) throws Exception {
addToAddressBook(taskList, generatePersonList(numGenerated));
}
/**
* Adds the given list of Persons to the given TaskList
*/
void addToAddressBook(TaskList taskList, List<Task> personsToAdd) throws Exception {
for (Task p: personsToAdd) {
taskList.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Persons will be added
*/
void addToModel(Model model, int numGenerated) throws Exception {
addToModel(model, generatePersonList(numGenerated));
}
/**
* Adds the given list of Persons to the given model
*/
void addToModel(Model model, List<Task> personsToAdd) throws Exception {
for (Task p: personsToAdd) {
model.addTask(p);
}
}
/**
* Generates a list of Persons based on the flags.
*/
List<Task> generatePersonList(int numGenerated) throws Exception {
List<Task> tasks = new ArrayList<>();
for (int i = 1; i <= numGenerated; i++) {
tasks.add(generatePerson(i));
}
return tasks;
}
List<Task> generatePersonList(Task... persons) {
return Arrays.asList(persons);
}
/**
* Generates a Task object with given name. Other fields will have some dummy values.
*/
Task generatePersonWithName(String name) throws Exception {
return new Task(
new Description(name),
new Priority("1"),
new Email("1@email"),
new UniqueTagList(new Tag("tag"))
);
}
}
} |
package org.apache.commons.betwixt;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.betwixt.io.CyclicReferenceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.SimpleLog;
/** Test harness for the BeanWriter
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @author <a href="mailto:martin@mvdb.net">Martin van den Bemt</a>
* @version $Revision: 1.13 $
*/
public class TestBeanWriter extends AbstractTestCase {
public static void main( String[] args ) {
TestRunner.run( suite() );
}
public static Test suite() {
return new TestSuite(TestBeanWriter.class);
}
public TestBeanWriter(String testName) {
super(testName);
}
public void testBeanWriter() throws Exception {
Object bean = createBean();
System.out.println( "Now trying pretty print" );
BeanWriter writer = new BeanWriter();
writer.enablePrettyPrint();
writer.write( bean );
}
public void testLooping() throws Exception {
BeanWriter writer = new BeanWriter();
writer.enablePrettyPrint();
writer.write( LoopBean.createNoLoopExampleBean() );
writer.write( LoopBean.createLoopExampleBean() );
// test not writing IDs
writer.setWriteIDs(false);
writer.write( LoopBean.createNoLoopExampleBean() );
try {
writer.write( LoopBean.createLoopExampleBean() );
fail("CyclicReferenceException not thrown!");
} catch (CyclicReferenceException e) {
// everything's fine
}
}
public void testEscaping() throws Exception {
//XXX find a way to automatically verify test
ByteArrayOutputStream out = new ByteArrayOutputStream();
BeanWriter writer = new BeanWriter(out);
writer.enablePrettyPrint();
XMLIntrospector introspector = new XMLIntrospector();
introspector.setAttributesForPrimitives(true);
writer.setXMLIntrospector(introspector);
writer.write(new LoopBean("Escape<LessThan"));
writer.write(new LoopBean("Escape>GreaterThan"));
writer.write(new LoopBean("Escape&hersand"));
writer.write(new LoopBean("Escape'apostrophe"));
writer.write(new LoopBean("Escape\"Quote"));
CustomerBean bean = new CustomerBean();
bean.setEmails( new String[] {
"Escape<LessThan",
"Escape>GreaterThan",
"Escape&hersand",
"Escape'apostrophe",
"Escape\"Quote"} );
// The attribute value escaping needs test too..
bean.setName("Escape<LessThan");
AddressBean address = new AddressBean();
address.setCode("Escape>GreaterThan");
address.setCountry("Escape&hersand");
address.setCity("Escape'apostrophe");
address.setStreet("Escape\"Quote");
bean.setAddress(address);
writer.write(bean);
out.flush();
String result = out.toString();
System.out.println( "Created..." );
System.out.println( result );
// check for the elemant content..
assertTrue(result.indexOf("<email>Escape<LessThan</email>") > -1 );
assertTrue(result.indexOf("<email>Escape>GreaterThan</email>") > -1);
assertTrue(result.indexOf("<email>Escape&amphersand</email>") != -1);
assertTrue(result.indexOf("<email>Escape'apostrophe</email>") != -1);
assertTrue(result.indexOf("<email>Escape\"Quote</email>") != -1);
// check for the attributes..
assertTrue(result.indexOf("name=\"Escape<LessThan\"") > -1 );
assertTrue(result.indexOf("code=\"Escape>GreaterThan\"") > -1);
assertTrue(result.indexOf("country=\"Escape&amphersand\"") != -1);
assertTrue(result.indexOf("city=\"Escape'apostrophe\"") != -1);
assertTrue(result.indexOf("street=\"Escape"Quote\"") != -1);
}
/**
* Testing valid endofline characters.
* It tests if there is a warning on System.err
*/
public void testValidEndOfLine() throws Exception {
BeanWriter writer = new BeanWriter();
// store the system err
PrintStream errStream = System.err;
ByteArrayOutputStream warning = new ByteArrayOutputStream();
System.setErr(new PrintStream(warning));
// force logging to go to System.err
writer.setLog( new SimpleLog( "test.betwixt" ) );
writer.setEndOfLine("X");
warning.flush();
assertTrue(warning.toString().startsWith("[WARN]"));
warning.reset();
writer.setEndOfLine("\tX");
warning.flush();
assertTrue(warning.toString().startsWith("[WARN]"));
warning.reset();
// now test a valid value..
writer.setEndOfLine(" ");
warning.flush();
assertTrue(warning.toString().equals(""));
warning.reset();
// set the System.err back again..
System.setErr(errStream);
}
} |
package com.example;
//remove::start[]
import javax.annotation.Nullable;
import javax.net.ssl.SSLException;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import net.devh.boot.grpc.client.autoconfigure.GrpcClientAutoConfiguration;
import net.devh.boot.grpc.client.channelfactory.GrpcChannelConfigurer;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.assertj.core.api.BDDAssertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.contract.stubrunner.HttpServerStubConfiguration;
import org.springframework.cloud.contract.stubrunner.junit.StubRunnerExtension;
import org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer;
import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* @author Marcin Grzejszczak
*/
@SpringBootTest(webEnvironment = WebEnvironment.NONE, classes = GrpcTests.TestConfiguration.class, properties = {
"grpc.client.beerService.address=static://localhost:5432", "grpc.client.beerService.negotiationType=TLS"
})
// remove::end[]
public class GrpcTests {
//remove::start[]
@GrpcClient(value = "beerService", interceptorNames = "fixedStatusSendingClientInterceptor")
BeerServiceGrpc.BeerServiceBlockingStub beerServiceBlockingStub;
int port;
@RegisterExtension
static StubRunnerExtension rule = new StubRunnerExtension()
.downloadStub("com.example", "beer-api-producer-grpc")
// With WireMock PlainText mode
// .withPort(5432)
.stubsMode(StubRunnerProperties.StubsMode.LOCAL)
.withHttpServerStubConfigurer(MyWireMockConfigurer.class);
@BeforeAll
public static void beforeClass() {
Assumptions.assumeTrue(atLeast300(), "Spring Cloud Contract must be in version at least 3.0.0");
Assumptions.assumeTrue(StringUtils.isEmpty(System.getenv("OLD_PRODUCER_TRAIN")),
"Env var OLD_PRODUCER_TRAIN must not be set");
}
@BeforeEach
public void setupPort() {
this.port = rule.findStubUrl("beer-api-producer-grpc").getPort();
}
private static boolean atLeast300() {
try {
Class.forName("org.springframework.cloud.contract.verifier.dsl.wiremock.SpringCloudContractRequestMatcher");
}
catch (Exception ex) {
return false;
}
return true;
}
// tag::tests[]
@Test
public void should_give_me_a_beer_when_im_old_enough() throws Exception {
Response response = beerServiceBlockingStub.check(PersonToCheck.newBuilder().setAge(23).build());
BDDAssertions.then(response.getStatus()).isEqualTo(Response.BeerCheckStatus.OK);
}
@Test
public void should_reject_a_beer_when_im_too_young() throws Exception {
Response response = beerServiceBlockingStub.check(PersonToCheck.newBuilder().setAge(17).build());
// TODO: If someone knows how to do this properly for default responses that would be helpful
response = response == null ? Response.newBuilder().build() : response;
BDDAssertions.then(response.getStatus()).isEqualTo(Response.BeerCheckStatus.NOT_OK);
}
// end::tests[]
// Not necessary with WireMock PlainText mode
static class MyWireMockConfigurer extends WireMockHttpServerStubConfigurer {
@Override
public WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
return httpStubConfiguration
.httpsPort(5432);
}
}
@Configuration
@ImportAutoConfiguration(GrpcClientAutoConfiguration.class)
static class TestConfiguration {
// Not necessary with WireMock PlainText mode
@Bean
public GrpcChannelConfigurer keepAliveClientConfigurer() {
return (channelBuilder, name) -> {
if (channelBuilder instanceof NettyChannelBuilder) {
try {
((NettyChannelBuilder) channelBuilder)
.sslContext(GrpcSslContexts.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build());
}
catch (SSLException e) {
throw new IllegalStateException(e);
}
}
};
}
/**
* GRPC client interceptor that sets the returned status always to OK.
* You might want to change the return status depending on the received stub payload.
*
* Hopefully in the future this will be unnecessary and will be removed.
*/
@Bean
ClientInterceptor fixedStatusSendingClientInterceptor() {
return new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
return new ClientCall<ReqT, RespT>() {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
Listener<RespT> listener = new Listener<RespT>() {
@Override
public void onHeaders(Metadata headers) {
responseListener.onHeaders(headers);
}
@Override
public void onMessage(RespT message) {
responseListener.onMessage(message);
}
@Override
public void onClose(Status status, Metadata trailers) {
// TODO: This must be fixed somehow either in Jetty (WireMock) or somewhere else
responseListener.onClose(Status.OK, trailers);
}
@Override
public void onReady() {
responseListener.onReady();
}
};
call.start(listener, headers);
}
@Override
public void request(int numMessages) {
call.request(numMessages);
}
@Override
public void cancel(@Nullable String message, @Nullable Throwable cause) {
call.cancel(message, cause);
}
@Override
public void halfClose() {
call.halfClose();
}
@Override
public void sendMessage(ReqT message) {
call.sendMessage(message);
}
};
}
};
}
}
//remove::end[]
} |
/**
* An Image Picker Plugin for Cordova/PhoneGap.
*/
package com.synconset;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
public class ImagePicker extends CordovaPlugin {
public static String TAG = "ImagePicker";
private CallbackContext callbackContext;
private JSONObject params;
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
this.params = args.getJSONObject(0);
if (action.equals("getPictures")) {
Intent intent = new Intent(cordova.getActivity(), MultiImageChooserActivity.class);
int max = 20;
int desiredWidth = 0;
int desiredHeight = 0;
int quality = 100;
if (this.params.has("maximumImagesCount")) {
max = this.params.getInt("maximumImagesCount");
}
if (this.params.has("width")) {
desiredWidth = this.params.getInt("width");
}
if (this.params.has("height")) {
desiredHeight = this.params.getInt("height");
}
if (this.params.has("quality")) {
quality = this.params.getInt("quality");
}
intent.putExtra("MAX_IMAGES", max);
intent.putExtra("WIDTH", desiredWidth);
intent.putExtra("HEIGHT", desiredHeight);
intent.putExtra("QUALITY", quality);
if (this.cordova != null) {
this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
}
}
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && data != null) {
ArrayList<String> fileNames = data.getStringArrayListExtra("MULTIPLEFILENAMES");
JSONArray res = new JSONArray(fileNames);
this.callbackContext.success(res);
} else if (resultCode == Activity.RESULT_CANCELED && data != null) {
String error = data.getStringExtra("ERRORMESSAGE");
this.callbackContext.error(error);
} else if (resultCode == Activity.RESULT_CANCELED) {
JSONArray res = new JSONArray();
this.callbackContext.success(res);
} else {
this.callbackContext.error("No images selected");
}
}
} |
package com.onegini.gcm;
import java.io.IOException;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.onegini.mobile.sdk.android.library.OneginiClient;
import com.onegini.mobile.sdk.android.library.handlers.OneginiMobileAuthEnrollmentHandler;
public class GCMHelper {
private static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String SENDER_ID = "586427927998";
private static final String TAG = "GCMDemo";
private Context context;
private OneginiClient oneginiClient;
private GoogleCloudMessaging gcm;
private String regid;
public GCMHelper(Context context) {
this.context = context;
}
public void registerGCMService(final OneginiClient oneginiClient,
final String[] scopes,
final OneginiMobileAuthEnrollmentHandler mobileAuthEnrollmentHandler) {
this.oneginiClient = oneginiClient;
gcm = GoogleCloudMessaging.getInstance(context);
if (oneginiClient.isPushNotificationEnabled(context)) {
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground(scopes, mobileAuthEnrollmentHandler);
}
else {
oneginiClient.enrollForMobileAuthentication(regid, scopes, mobileAuthEnrollmentHandler);
}
}
else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Gets the current registration ID for application on GCM service. <p> If result is empty, the app needs to
* register.
*
* @return registration ID, or empty string if there is no existing registration ID.
*/
private String getRegistrationId(final Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
final String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
final int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
final int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGCMPreferences(final Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return context.getSharedPreferences(context.getApplicationInfo().name,
Context.MODE_PRIVATE);
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(final Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* Registers the application with GCM servers asynchronously. <p> Stores the registration ID and app versionCode in
* the application's shared preferences.
*/
private void registerInBackground(final String[] scopes,
final OneginiMobileAuthEnrollmentHandler mobileAuthEnrollmentHandler) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend(scopes, mobileAuthEnrollmentHandler);
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
Log.v("TEST", msg);
}
}.execute(null, null, null);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send messages to your app. Not
* needed for this demo since the device sends upstream messages to a server that echoes back the message using the
* 'from' address in the message.
*/
private void sendRegistrationIdToBackend(final String[] scopes,
final OneginiMobileAuthEnrollmentHandler mobileAuthEnrollmentHandler) {
oneginiClient.enrollForMobileAuthentication(regid, scopes, mobileAuthEnrollmentHandler);
}
/**
* Stores the registration ID and app versionCode in the application's {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
} |
package be.ibridge.kettle.job.entry.mail;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.eclipse.swt.widgets.Shell;
import org.w3c.dom.Node;
import be.ibridge.kettle.chef.JobTracker;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.ResultFile;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.job.Job;
import be.ibridge.kettle.job.JobEntryResult;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.job.entry.JobEntryBase;
import be.ibridge.kettle.job.entry.JobEntryDialogInterface;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.repository.Repository;
public class JobEntryMail extends JobEntryBase implements JobEntryInterface
{
private String server;
private String destination;
private String replyAddress;
private String subject;
private boolean includeDate;
private String contactPerson;
private String contactPhone;
private String comment;
private boolean includingFiles;
private int fileType[];
private boolean zipFiles;
private String zipFilename;
private boolean usingAuthentication;
private String authenticationUser;
private String authenticationPassword;
public JobEntryMail(String n)
{
super(n, "");
setType(JobEntryInterface.TYPE_JOBENTRY_MAIL);
allocate(0);
}
public JobEntryMail()
{
this("");
allocate(0);
}
public JobEntryMail(JobEntryBase jeb)
{
super(jeb);
allocate(0);
}
public String getXML()
{
StringBuffer retval = new StringBuffer();
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("server", server));
retval.append(" ").append(XMLHandler.addTagValue("destination", destination));
retval.append(" ").append(XMLHandler.addTagValue("replyto", replyAddress));
retval.append(" ").append(XMLHandler.addTagValue("subject", subject));
retval.append(" ").append(XMLHandler.addTagValue("include_date", includeDate));
retval.append(" ").append(XMLHandler.addTagValue("contact_person", contactPerson));
retval.append(" ").append(XMLHandler.addTagValue("contact_phone", contactPhone));
retval.append(" ").append(XMLHandler.addTagValue("comment", comment));
retval.append(" ").append(XMLHandler.addTagValue("include_files", includingFiles));
retval.append(" ").append(XMLHandler.addTagValue("zip_files", zipFiles));
retval.append(" ").append(XMLHandler.addTagValue("zip_name", zipFilename));
retval.append(" ").append(XMLHandler.addTagValue("use_auth", usingAuthentication));
retval.append(" ").append(XMLHandler.addTagValue("auth_user", authenticationUser));
retval.append(" ").append(XMLHandler.addTagValue("auth_password", authenticationPassword));
retval.append(" <filetypes>");
if (fileType!=null)
for (int i=0;i<fileType.length;i++)
{
retval.append(" ").append(XMLHandler.addTagValue("filetype", ResultFile.getTypeCode(fileType[i])));
}
retval.append(" </filetypes>");
return retval.toString();
}
public void allocate(int nrFileTypes)
{
fileType = new int[nrFileTypes];
}
public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
setServer ( XMLHandler.getTagValue(entrynode, "server") );
setDestination ( XMLHandler.getTagValue(entrynode, "destination") );
setReplyAddress ( XMLHandler.getTagValue(entrynode, "replyto") );
setSubject ( XMLHandler.getTagValue(entrynode, "subject") );
setIncludeDate ( "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "include_date")) );
setContactPerson( XMLHandler.getTagValue(entrynode, "concact_person") );
setContactPhone ( XMLHandler.getTagValue(entrynode, "concact_phone") );
setComment ( XMLHandler.getTagValue(entrynode, "comment") );
setIncludingFiles ( "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "include_files")) );
setUsingAuthentication( "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "use_auth")) );
setAuthenticationUser( XMLHandler.getTagValue(entrynode, "auth_user") );
setAuthenticationPassword( XMLHandler.getTagValue(entrynode, "auth_password") );
Node ftsnode = XMLHandler.getSubNode(entrynode, "filetypes");
int nrTypes = XMLHandler.countNodes(ftsnode, "filetype");
allocate(nrTypes);
for (int i=0;i<nrTypes;i++)
{
Node ftnode = XMLHandler.getSubNodeByNr(ftsnode, "filetype", i);
fileType[i]=ResultFile.getType(XMLHandler.getNodeValue(ftnode));
}
setZipFiles( "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "zip_files")) );
setZipFilename( XMLHandler.getTagValue(entrynode, "zip_name") );
}
catch(KettleException xe)
{
throw new KettleXMLException("Unable to load mail job entry from XML node", xe);
}
}
public void loadRep(Repository rep, long id_jobentry, ArrayList databases)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
// First load the common parts like name & description, then the attributes...
server = rep.getJobEntryAttributeString (id_jobentry, "server");
destination = rep.getJobEntryAttributeString (id_jobentry, "destination");
replyAddress = rep.getJobEntryAttributeString (id_jobentry, "replyto");
subject = rep.getJobEntryAttributeString (id_jobentry, "subject");
includeDate = rep.getJobEntryAttributeBoolean(id_jobentry, "include_date");
contactPerson = rep.getJobEntryAttributeString (id_jobentry, "contact_person");
contactPhone = rep.getJobEntryAttributeString (id_jobentry, "contact_phone");
comment = rep.getJobEntryAttributeString (id_jobentry, "comment");
includingFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "include_files");
usingAuthentication = rep.getJobEntryAttributeBoolean(id_jobentry, "use_auth");
authenticationUser = rep.getJobEntryAttributeString(id_jobentry, "auth_user");
authenticationPassword = rep.getJobEntryAttributeString(id_jobentry, "auth_password");
int nrTypes = rep.countNrJobEntryAttributes(id_jobentry, "file_type");
allocate(nrTypes);
for (int i=0;i<nrTypes;i++)
{
String typeCode = rep.getJobEntryAttributeString(id_jobentry, i, "file_type");
fileType[i] = ResultFile.getType(typeCode);
}
zipFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "zip_files");
zipFilename = rep.getJobEntryAttributeString(id_jobentry, "zip_name");
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load job entry of type mail from the repository with id_jobentry="+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "server", server);
rep.saveJobEntryAttribute(id_job, getID(), "destination", destination);
rep.saveJobEntryAttribute(id_job, getID(), "replyto", replyAddress);
rep.saveJobEntryAttribute(id_job, getID(), "subject", subject);
rep.saveJobEntryAttribute(id_job, getID(), "include_date", includeDate);
rep.saveJobEntryAttribute(id_job, getID(), "contact_person", contactPerson);
rep.saveJobEntryAttribute(id_job, getID(), "contact_phone", contactPhone);
rep.saveJobEntryAttribute(id_job, getID(), "comment", comment);
rep.saveJobEntryAttribute(id_job, getID(), "include_files", includingFiles);
rep.saveJobEntryAttribute(id_job, getID(), "use_auth", usingAuthentication);
rep.saveJobEntryAttribute(id_job, getID(), "auth_user", authenticationUser);
rep.saveJobEntryAttribute(id_job, getID(), "auth_password", authenticationPassword);
if (fileType!=null)
{
for (int i=0;i<fileType.length;i++)
{
rep.saveJobEntryAttribute(id_job, getID(), i, "file_type", ResultFile.getTypeCode(fileType[i]));
}
}
rep.saveJobEntryAttribute(id_job, getID(), "zip_files", zipFiles);
rep.saveJobEntryAttribute(id_job, getID(), "zip_name", zipFilename);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("unable to save jobentry of type mail to the repository for id_job="+id_job, dbe);
}
}
public void setServer(String s)
{
server=s;
}
public String getServer()
{
return server;
}
public void setDestination(String dest)
{
destination=dest;
}
public String getDestination()
{
return destination;
}
public void setReplyAddress(String reply)
{
replyAddress=reply;
}
public String getReplyAddress()
{
return replyAddress;
}
public void setSubject(String subj)
{
subject=subj;
}
public String getSubject()
{
return subject;
}
public void setIncludeDate(boolean incl)
{
includeDate=incl;
}
public boolean getIncludeDate()
{
return includeDate;
}
public void setContactPerson(String person)
{
contactPerson=person;
}
public String getContactPerson()
{
return contactPerson;
}
public void setContactPhone(String phone)
{
contactPhone=phone;
}
public String getContactPhone()
{
return contactPhone;
}
public void setComment(String comm)
{
comment = comm;
}
public String getComment()
{
return comment;
}
/**
* @return the result file types to select for attachement </b>
* @see ResultFile
*/
public int[] getFileType()
{
return fileType;
}
/**
* @param fileType the result file types to select for attachement
* @see ResultFile
*/
public void setFileType(int[] fileType)
{
this.fileType = fileType;
}
public boolean isIncludingFiles() {
return includingFiles;
}
public void setIncludingFiles(boolean includeFiles) {
this.includingFiles = includeFiles;
}
/**
* @return Returns the zipFilename.
*/
public String getZipFilename()
{
return zipFilename;
}
/**
* @param zipFilename The zipFilename to set.
*/
public void setZipFilename(String zipFilename)
{
this.zipFilename = zipFilename;
}
/**
* @return Returns the zipFiles.
*/
public boolean isZipFiles()
{
return zipFiles;
}
/**
* @param zipFiles The zipFiles to set.
*/
public void setZipFiles(boolean zipFiles)
{
this.zipFiles = zipFiles;
}
/**
* @return Returns the authenticationPassword.
*/
public String getAuthenticationPassword()
{
return authenticationPassword;
}
/**
* @param authenticationPassword The authenticationPassword to set.
*/
public void setAuthenticationPassword(String authenticationPassword)
{
this.authenticationPassword = authenticationPassword;
}
/**
* @return Returns the authenticationUser.
*/
public String getAuthenticationUser()
{
return authenticationUser;
}
/**
* @param authenticationUser The authenticationUser to set.
*/
public void setAuthenticationUser(String authenticationUser)
{
this.authenticationUser = authenticationUser;
}
/**
* @return Returns the usingAuthentication.
*/
public boolean isUsingAuthentication()
{
return usingAuthentication;
}
/**
* @param usingAuthentication The usingAuthentication to set.
*/
public void setUsingAuthentication(boolean usingAuthentication)
{
this.usingAuthentication = usingAuthentication;
}
public Result execute(Result result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
File masterZipfile=null;
// Send an e-mail...
// create some properties and get the default Session
Properties props = new Properties();
props.put("mail.smtp.host", StringUtil.environmentSubstitute(server));
boolean debug = log.getLogLevel()>=LogWriter.LOG_LEVEL_DEBUG;
if (debug) props.put("mail.debug", "true");
Authenticator authenticator = null;
if (usingAuthentication)
{
authenticator = new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(
StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))
);
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
try
{
// create a message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(StringUtil.environmentSubstitute(replyAddress)));
// Split the mail-address: space separated
String destinations[] = StringUtil.environmentSubstitute(destination).split(" ");
InternetAddress[] address = new InternetAddress[destinations.length];
for (int i=0;i<destinations.length;i++) address[i] = new InternetAddress(destinations[i]);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(StringUtil.environmentSubstitute(subject));
msg.setSentDate(new Date());
StringBuffer messageText = new StringBuffer();
if (comment!=null)
{
messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
}
messageText.append("Job:").append(Const.CR);
messageText.append("
messageText.append("Name : ").append(parentJob.getJobMeta().getName()).append(Const.CR);
messageText.append("Directory : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
messageText.append("JobEntry : ").append(getName()).append(Const.CR);
messageText.append(Const.CR);
if (includeDate)
{
Value date = new Value("date", new Date());
messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR);
}
if (result!=null)
{
messageText.append("Previous result:").append(Const.CR);
messageText.append("
messageText.append("Job entry nr : ").append(result.getEntryNr()).append(Const.CR);
messageText.append("Errors : ").append(result.getNrErrors()).append(Const.CR);
messageText.append("Lines read : ").append(result.getNrLinesRead()).append(Const.CR);
messageText.append("Lines written : ").append(result.getNrLinesWritten()).append(Const.CR);
messageText.append("Lines input : ").append(result.getNrLinesInput()).append(Const.CR);
messageText.append("Lines output : ").append(result.getNrLinesOutput()).append(Const.CR);
messageText.append("Lines updated : ").append(result.getNrLinesUpdated()).append(Const.CR);
messageText.append("Script exit status : ").append(result.getExitStatus()).append(Const.CR);
messageText.append("Result : ").append(result.getResult()).append(Const.CR);
messageText.append(Const.CR);
}
if (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson)) || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)) )
{
messageText.append("Contact information :").append(Const.CR);
messageText.append("
messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson)).append(Const.CR);
messageText.append("Telephone number : ").append(StringUtil.environmentSubstitute(contactPhone)).append(Const.CR);
messageText.append(Const.CR);
}
// Include the path to this job entry...
JobTracker jobTracker = parentJob.getJobTracker();
if (jobTracker!=null)
{
messageText.append("Path to this job entry:").append(Const.CR);
messageText.append("
addBacktracking(jobTracker, messageText);
}
Multipart parts = new MimeMultipart();
MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
// 1st part
part1.setText(messageText.toString());
parts.addBodyPart(part1);
if (includingFiles && result != null)
{
List resultFiles = result.getResultFiles();
if (resultFiles!=null && resultFiles.size() > 0)
{
if (!zipFiles)
{
// Add all files to the message...
for (Iterator iter = resultFiles.iterator(); iter.hasNext();)
{
ResultFile resultFile = (ResultFile) iter.next();
File file = resultFile.getFile();
if (file != null && file.exists())
{
// create a data source
MimeBodyPart files = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
// get a data Handler to manipulate this file type;
files.setDataHandler(new DataHandler(fds));
// include the file in th e data source
files.setFileName(fds.getName());
// add the part with the file in the BodyPart();
parts.addBodyPart(files);
}
}
}
else
{
// create a single ZIP archive of all files
masterZipfile = new File(System.getProperty("java.io.tmpdir")+Const.FILE_SEPARATOR+StringUtil.environmentSubstitute(zipFilename));
ZipOutputStream zipOutputStream = null;
try
{
zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
for (Iterator iter = resultFiles.iterator(); iter.hasNext();)
{
ResultFile resultFile = (ResultFile) iter.next();
File file = resultFile.getFile();
ZipEntry zipEntry = new ZipEntry(file.getPath());
zipOutputStream.putNextEntry(zipEntry);
// Now put the content of this file into this archive...
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
int c;
while ( (c=inputStream.read())>=0)
{
zipOutputStream.write(c);
}
inputStream.close();
zipOutputStream.closeEntry();
}
}
catch(Exception e)
{
log.logError(toString(), "Error zipping attachement files into file ["+masterZipfile.getPath()+"] : "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
result.setNrErrors(1);
}
finally
{
if (zipOutputStream!=null)
{
try
{
zipOutputStream.finish();
zipOutputStream.close();
}
catch(IOException e)
{
log.logError(toString(), "Unable to close attachement zip file archive : "+e.toString());
log.logError(toString(), Const.getStackTracker(e));
result.setNrErrors(1);
}
}
}
// Now attach the master zip file to the message.
if (result.getNrErrors()==0)
{
// create a data source
MimeBodyPart files = new MimeBodyPart();
FileDataSource fds = new FileDataSource(masterZipfile);
// get a data Handler to manipulate this file type;
files.setDataHandler(new DataHandler(fds));
// include the file in th e data source
files.setFileName(fds.getName());
// add the part with the file in the BodyPart();
parts.addBodyPart(files);
}
}
}
}
msg.setContent(parts);
Transport.send(msg);
}
catch (MessagingException mex)
{
log.logError(toString(), "Problem while sending message: "+mex.toString());
result.setNrErrors(1);
Exception ex = mex;
do
{
if (ex instanceof SendFailedException)
{
SendFailedException sfex = (SendFailedException)ex;
Address[] invalid = sfex.getInvalidAddresses();
if (invalid != null)
{
log.logError(toString(), " ** Invalid Addresses");
for (int i = 0; i < invalid.length; i++)
{
log.logError(toString(), " " + invalid[i]);
result.setNrErrors(1);
}
}
Address[] validUnsent = sfex.getValidUnsentAddresses();
if (validUnsent != null)
{
log.logError(toString(), " ** ValidUnsent Addresses");
for (int i = 0; i < validUnsent.length; i++)
{
log.logError(toString(), " "+validUnsent[i]);
result.setNrErrors(1);
}
}
Address[] validSent = sfex.getValidSentAddresses();
if (validSent != null)
{
//System.out.println(" ** ValidSent Addresses");
for (int i = 0; i < validSent.length; i++)
{
log.logError(toString(), " "+validSent[i]);
result.setNrErrors(1);
}
}
}
if (ex instanceof MessagingException)
{
ex = ((MessagingException)ex).getNextException();
}
else
{
ex = null;
}
} while (ex != null);
}
finally
{
if (masterZipfile!=null && masterZipfile.exists())
{
masterZipfile.delete();
}
}
if (result.getNrErrors() > 0)
{
result.setResult( false );
}
else
{
result.setResult( true );
}
return result;
}
private void addBacktracking(JobTracker jobTracker, StringBuffer messageText)
{
addBacktracking(jobTracker, messageText, 0);
}
private void addBacktracking(JobTracker jobTracker, StringBuffer messageText, int level)
{
int nr = jobTracker.nrJobTrackers();
messageText.append(Const.rightPad(" ", level*2));
messageText.append(Const.NVL( jobTracker.getJobMeta().getName(), "-") );
JobEntryResult jer = jobTracker.getJobEntryResult();
if (jer!=null)
{
messageText.append(" : ");
if (jer.getJobEntry()!=null && jer.getJobEntry().getName()!=null)
{
messageText.append(" : ");
messageText.append(jer.getJobEntry().getName());
}
if (jer.getResult()!=null)
{
messageText.append(" : ");
messageText.append("["+jer.getResult().toString()+"]");
}
if (jer.getReason()!=null)
{
messageText.append(" : ");
messageText.append(jer.getReason());
}
if (jer.getComment()!=null)
{
messageText.append(" : ");
messageText.append(jer.getComment());
}
}
messageText.append(Const.CR);
for (int i=0;i<nr;i++)
{
JobTracker jt = jobTracker.getJobTracker(i);
addBacktracking(jt, messageText, level+1);
}
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return true;
}
public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) {
return new JobEntryMailDialog(shell,this);
}
} |
package imagej.legacy;
import ij.Executer;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.Macro;
import ij.WindowManager;
import ij.gui.DialogListener;
import ij.gui.ImageWindow;
import ij.io.Opener;
import ij.plugin.filter.PlugInFilterRunner;
import imagej.data.display.ImageDisplay;
import imagej.platform.event.AppAboutEvent;
import imagej.platform.event.AppOpenFilesEvent;
import imagej.platform.event.AppPreferencesEvent;
import imagej.platform.event.AppQuitEvent;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.FocusEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.SwingUtilities;
import org.scijava.AbstractContextual;
import org.scijava.Context;
import org.scijava.event.EventHandler;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
/**
* A helper class to interact with ImageJ 1.x.
* <p>
* The DefaultLegacyService needs to patch ImageJ 1.x's classes before they are
* loaded. Unfortunately, this is tricky: if the DefaultLegacyService already
* uses those classes, it is a matter of luck whether we can get the patches in
* before those classes are loaded.
* </p>
* <p>
* Therefore, we put as much interaction with ImageJ 1.x as possible into this
* class and keep a reference to it in the DefaultLegacyService.
* </p>
*
* @author Johannes Schindelin
*/
public class IJ1Helper extends AbstractContextual {
/** A reference to the legacy service, just in case we need it */
private final DefaultLegacyService legacyService;
@Parameter
private LogService log;
public IJ1Helper(final DefaultLegacyService legacyService) {
setContext(legacyService.getContext());
this.legacyService = legacyService;
}
public void initialize() {
// initialize legacy ImageJ application
if (IJ.getInstance() == null) try {
if (GraphicsEnvironment.isHeadless()) {
IJ.runPlugIn("ij.IJ.init", null);
} else {
new ImageJ(ImageJ.NO_SHOW);
}
}
catch (final Throwable t) {
log.warn("Failed to instantiate IJ1.", t);
} else {
final LegacyImageMap imageMap = legacyService.getImageMap();
for (int i = 1; i <= WindowManager.getImageCount(); i++) {
imageMap.registerLegacyImage(WindowManager.getImage(i));
}
}
}
public void dispose() {
final ImageJ ij = IJ.getInstance();
if (ij != null) {
Runnable run = new Runnable() {
@Override
public void run() {
// close out all image windows, without dialog prompts
while (true) {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) break;
imp.changes = false;
imp.close();
}
// close any remaining (non-image) windows
WindowManager.closeAllWindows();
}
};
if (SwingUtilities.isEventDispatchThread()) {
run.run();
} else try {
SwingUtilities.invokeAndWait(run);
} catch (Exception e) {
// report & ignore
e.printStackTrace();
}
// quit legacy ImageJ on the same thread
ij.run();
}
}
public void setVisible(boolean toggle) {
final ImageJ ij = IJ.getInstance();
if (ij != null) {
if (toggle) ij.pack();
ij.setVisible(toggle);
}
// hide/show the legacy ImagePlus instances
final LegacyImageMap imageMap = legacyService.getImageMap();
for (final ImagePlus imp : imageMap.getImagePlusInstances()) {
final ImageWindow window = imp.getWindow();
if (window != null) window.setVisible(toggle);
}
}
public void syncActiveImage(final ImageDisplay activeDisplay) {
final LegacyImageMap imageMap = legacyService.getImageMap();
final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay);
// NB - old way - caused probs with 3d Project
// WindowManager.setTempCurrentImage(activeImagePlus);
// NB - new way - test thoroughly
if (activeImagePlus == null) WindowManager.setCurrentWindow(null);
else WindowManager.setCurrentWindow(activeImagePlus.getWindow());
}
public void setKeyDown(int keyCode) {
IJ.setKeyDown(keyCode);
}
public void setKeyUp(int keyCode) {
IJ.setKeyUp(keyCode);
}
public boolean hasInstance() {
return IJ.getInstance() != null;
}
public String getVersion() {
return IJ.getVersion();
}
public boolean isMacintosh() {
return IJ.isMacintosh();
}
/**
* Gets a macro parameter of type <i>boolean</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the boolean value
*/
public static boolean getMacroParameter(String label, boolean defaultValue) {
return getMacroParameter(label) != null || defaultValue;
}
/**
* Gets a macro parameter of type <i>double</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the double value
*/
public static double getMacroParameter(String label, double defaultValue) {
String value = Macro.getValue(Macro.getOptions(), label, null);
return value != null ? Double.parseDouble(value) : defaultValue;
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the value
*/
public static String getMacroParameter(String label, String defaultValue) {
return Macro.getValue(Macro.getOptions(), label, defaultValue);
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @return the value, <code>null</code> if the parameter was not specified
*/
public static String getMacroParameter(String label) {
return Macro.getValue(Macro.getOptions(), label, null);
}
public static class LegacyGenericDialog {
protected List<Double> numbers;
protected List<String> strings;
protected List<Boolean> checkboxes;
protected List<String> choices;
protected List<Integer> choiceIndices;
protected String textArea1, textArea2;
protected List<String> radioButtons;
protected int numberfieldIndex = 0, stringfieldIndex = 0, checkboxIndex = 0, choiceIndex = 0, textAreaIndex = 0, radioButtonIndex = 0;
protected boolean invalidNumber;
protected String errorMessage;
public LegacyGenericDialog() {
if (Macro.getOptions() == null)
throw new RuntimeException("Cannot instantiate headless dialog except in macro mode");
numbers = new ArrayList<Double>();
strings = new ArrayList<String>();
checkboxes = new ArrayList<Boolean>();
choices = new ArrayList<String>();
choiceIndices = new ArrayList<Integer>();
radioButtons = new ArrayList<String>();
}
public void addCheckbox(String label, boolean defaultValue) {
checkboxes.add(getMacroParameter(label, defaultValue));
}
@SuppressWarnings("unused")
public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues) {
for (int i = 0; i < labels.length; i++)
addCheckbox(labels[i], defaultValues[i]);
}
@SuppressWarnings("unused")
public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues, String[] headings) {
addCheckboxGroup(rows, columns, labels, defaultValues);
}
public void addChoice(String label, String[] items, String defaultItem) {
String item = getMacroParameter(label, defaultItem);
int index = 0;
for (int i = 0; i < items.length; i++)
if (items[i].equals(item)) {
index = i;
break;
}
choiceIndices.add(index);
choices.add(items[index]);
}
@SuppressWarnings("unused")
public void addNumericField(String label, double defaultValue, int digits) {
numbers.add(getMacroParameter(label, defaultValue));
}
@SuppressWarnings("unused")
public void addNumericField(String label, double defaultValue, int digits, int columns, String units) {
addNumericField(label, defaultValue, digits);
}
@SuppressWarnings("unused")
public void addSlider(String label, double minValue, double maxValue, double defaultValue) {
numbers.add(getMacroParameter(label, defaultValue));
}
public void addStringField(String label, String defaultText) {
strings.add(getMacroParameter(label, defaultText));
}
@SuppressWarnings("unused")
public void addStringField(String label, String defaultText, int columns) {
addStringField(label, defaultText);
}
@SuppressWarnings("unused")
public void addTextAreas(String text1, String text2, int rows, int columns) {
textArea1 = text1;
textArea2 = text2;
}
public boolean getNextBoolean() {
return checkboxes.get(checkboxIndex++);
}
public String getNextChoice() {
return choices.get(choiceIndex++);
}
public int getNextChoiceIndex() {
return choiceIndices.get(choiceIndex++);
}
public double getNextNumber() {
return numbers.get(numberfieldIndex++);
}
/** Returns the contents of the next text field. */
public String getNextString() {
return strings.get(stringfieldIndex++);
}
public String getNextText() {
switch (textAreaIndex++) {
case 0:
return textArea1;
case 1:
return textArea2;
}
return null;
}
/** Adds a radio button group. */
@SuppressWarnings("unused")
public void addRadioButtonGroup(String label, String[] items, int rows, int columns, String defaultItem) {
radioButtons.add(getMacroParameter(label, defaultItem));
}
public List<String> getRadioButtonGroups() {
return radioButtons;
}
/** Returns the selected item in the next radio button group. */
public String getNextRadioButton() {
return radioButtons.get(radioButtonIndex++);
}
public boolean invalidNumber() {
boolean wasInvalid = invalidNumber;
invalidNumber = false;
return wasInvalid;
}
public void showDialog() {
if (Macro.getOptions() == null)
throw new RuntimeException("Cannot run dialog headlessly");
numberfieldIndex = 0;
stringfieldIndex = 0;
checkboxIndex = 0;
choiceIndex = 0;
textAreaIndex = 0;
}
public boolean wasCanceled() {
return false;
}
public boolean wasOKed() {
return true;
}
public void dispose() {}
@SuppressWarnings("unused")
public void addDialogListener(DialogListener dl) {}
@SuppressWarnings("unused")
public void addHelp(String url) {}
@SuppressWarnings("unused")
public void addMessage(String text) {}
@SuppressWarnings("unused")
public void addMessage(String text, Font font) {}
@SuppressWarnings("unused")
public void addMessage(String text, Font font, Color color) {}
@SuppressWarnings("unused")
public void addPanel(Panel panel) {}
@SuppressWarnings("unused")
public void addPanel(Panel panel, int contraints, Insets insets) {}
@SuppressWarnings("unused")
public void addPreviewCheckbox(PlugInFilterRunner pfr) {}
@SuppressWarnings("unused")
public void addPreviewCheckbox(PlugInFilterRunner pfr, String label) {}
@SuppressWarnings("unused")
public void centerDialog(boolean b) {}
public void enableYesNoCancel() {}
@SuppressWarnings("unused")
public void enableYesNoCancel(String yesLabel, String noLabel) {}
@SuppressWarnings("unused")
public void focusGained(FocusEvent e) {}
@SuppressWarnings("unused")
public void focusLost(FocusEvent e) {}
public Button[] getButtons() { return null; }
public Vector<?> getCheckboxes() { return null; }
public Vector<?> getChoices() { return null; }
public String getErrorMessage() { return errorMessage; }
public Insets getInsets() { return null; }
public Component getMessage() { return null; }
public Vector<?> getNumericFields() { return null; }
public Checkbox getPreviewCheckbox() { return null; }
public Vector<?> getSliders() { return null; }
public Vector<?> getStringFields() { return null; }
public TextArea getTextArea1() { return null; }
public TextArea getTextArea2() { return null; }
public void hideCancelButton() {}
@SuppressWarnings("unused")
public void previewRunning(boolean isRunning) {}
@SuppressWarnings("unused")
public void setEchoChar(char echoChar) {}
@SuppressWarnings("unused")
public void setHelpLabel(String label) {}
@SuppressWarnings("unused")
public void setInsets(int top, int left, int bottom) {}
@SuppressWarnings("unused")
public void setOKLabel(String label) {}
protected void setup() {}
public void accessTextFields() {}
public void showHelp() {}
}
/**
* Replacement for ImageJ 1.x' MacAdapter.
* <p>
* ImageJ 1.x has a MacAdapter plugin that intercepts MacOSX-specific events
* and handles them. The way it does it is deprecated now, however, and
* unfortunately incompatible with the way ImageJ 2's platform service does
* it.
* </p>
* <p>
* This class implements the same functionality as the MacAdapter, but in a
* way that is compatible with ImageJ 2's platform service.
* </p>
* @author Johannes Schindelin
*/
private static class LegacyEventDelegator extends AbstractContextual {
@Parameter(required = false)
private LegacyService legacyService;
// -- MacAdapter re-implementations --
@EventHandler
private void onEvent(@SuppressWarnings("unused") final AppAboutEvent event)
{
if (isLegacyMode()) {
IJ.run("About ImageJ...");
}
}
@EventHandler
private void onEvent(final AppOpenFilesEvent event) {
if (isLegacyMode()) {
final List<File> files = new ArrayList<File>(event.getFiles());
for (final File file : files) {
new Opener().openAndAddToRecent(file.getAbsolutePath());
}
}
}
@EventHandler
private void onEvent(@SuppressWarnings("unused") final AppQuitEvent event) {
if (isLegacyMode()) {
new Executer("Quit", null); // works with the CommandListener
}
}
@EventHandler
private void onEvent(
@SuppressWarnings("unused") final AppPreferencesEvent event)
{
if (isLegacyMode()) {
IJ.error("The ImageJ preferences are in the Edit>Options menu.");
}
}
private boolean isLegacyMode() {
// We call setContext() indirectly from DefaultLegacyService#initialize,
// therefore legacyService might still be null at this point even if the
// context knows a legacy service now.
if (legacyService == null) {
final Context context = getContext();
if (context != null) legacyService = context.getService(LegacyService.class);
}
return legacyService != null && legacyService.isLegacyMode();
}
}
private static LegacyEventDelegator eventDelegator;
public static void subscribeEvents(final Context context) {
if (context == null) {
eventDelegator = null;
} else {
eventDelegator = new LegacyEventDelegator();
eventDelegator.setContext(context);
}
}
} |
package com.spaceproject.ui.menu;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.util.dialog.Dialogs;
import com.spaceproject.SpaceProject;
import com.spaceproject.screens.GameScreen;
import com.spaceproject.screens.debug.Test3DScreen;
import com.spaceproject.screens.debug.TestNoiseScreen;
import com.spaceproject.screens.debug.TestShipGenerationScreen;
import com.spaceproject.screens.debug.TestSpiralGalaxy;
import com.spaceproject.screens.debug.TestVoronoiScreen;
public class TitleScreenMenu {
public static Table buildMenu(final SpaceProject game, final Stage stage, boolean showDebugScreens) {
TextButton btnPlay = new TextButton("play", VisUI.getSkin());
btnPlay.getLabel().setAlignment(Align.left);
btnPlay.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new GameScreen());
}
});
TextButton btnVoronoi = new TextButton("voronoi [DEBUG]", VisUI.getSkin());
btnVoronoi.getLabel().setAlignment(Align.left);
btnVoronoi.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new TestVoronoiScreen());
}
});
TextButton btnNoise = new TextButton("noise [DEBUG]", VisUI.getSkin());
btnNoise.getLabel().setAlignment(Align.left);
btnNoise.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new TestNoiseScreen());
}
});
TextButton btnShip = new TextButton("ship gen [DEBUG]", VisUI.getSkin());
btnShip.getLabel().setAlignment(Align.left);
btnShip.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new TestShipGenerationScreen());
}
});
TextButton btn3D = new TextButton("3D rotate [DEBUG]", VisUI.getSkin());
btn3D.getLabel().setAlignment(Align.left);
btn3D.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new Test3DScreen());
}
});
TextButton btnSpiral = new TextButton("Spiral Gen [DEBUG]", VisUI.getSkin());
btnSpiral.getLabel().setAlignment(Align.left);
btnSpiral.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new TestSpiralGalaxy());
}
});
TextButton btnLoad = new TextButton("load", VisUI.getSkin());
btnLoad.getLabel().setAlignment(Align.left);
btnLoad.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Dialogs.showOKDialog(stage, "load", "not implemented yet");
}
});
TextButton btnOption = new TextButton("options", VisUI.getSkin());
btnOption.getLabel().setAlignment(Align.left);
btnOption.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Dialogs.showOKDialog(stage, "options", "not implemented yet");
}
});
//about
TextButton btnAbout = new TextButton("about", VisUI.getSkin());
btnAbout.getLabel().setAlignment(Align.left);
btnAbout.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Dialogs.showOKDialog(stage, "about", "a space game (WIP...)\nDeveloped by Whilow Schock");
}
});
TextButton btnExit = new TextButton("exit", VisUI.getSkin());
btnExit.getLabel().setAlignment(Align.left);
btnExit.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.exit();
}
});
//add buttons to table
Table table = new Table();
table.add(btnPlay).fillX().row();
if (showDebugScreens) {
table.add(btnSpiral).fillX().row();
table.add(btnVoronoi).fillX().row();
table.add(btnNoise).fillX().row();
table.add(btn3D).fillX().row();
table.add(btnShip).fillX().row();
}
table.add(btnLoad).fillX().row();
table.add(btnOption).fillX().row();
table.add(btnAbout).fillX().row();
table.add(btnExit).fillX().row();
//set bigger labels on mobile
if (SpaceProject.isMobile()) {
for (Actor button : table.getChildren()) {
if (button instanceof TextButton) {
//((TextButton) button).getLabel().getFont???.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
((TextButton) button).getLabel().setFontScale(2f);
}
}
}
return table;
}
} |
package ethanjones.cubes.graphics.menu;
import ethanjones.cubes.core.localization.Localization;
import ethanjones.cubes.core.platform.Adapter;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;
import com.badlogic.gdx.utils.Align;
import static ethanjones.cubes.graphics.Graphics.GUI_HEIGHT;
import static ethanjones.cubes.graphics.Graphics.GUI_WIDTH;
public class MenuTools {
public static enum Direction {
Above, Below, Left, Right
}
public static void arrange(float x, float y, float width, float height, Direction direction, Actor... actors) {
switch (direction) {
case Above:
case Below:
height = height / actors.length;
break;
case Left:
case Right:
width = width / actors.length;
break;
}
if (direction == Direction.Below) {
y -= height;
}
setSize(width, height, actors);
Actor prev = actors[0];
setPos(x, y, prev);
for (int i = 1; i < actors.length; i++) {
Actor curr = actors[i];
move(curr, direction, prev);
prev = curr;
}
}
public static void setSize(float width, float height, Actor... actors) {
for (Actor o : actors) {
o.setSize(width, height);
}
}
public static void setPos(float x, float y, Actor... actors) {
for (Actor o : actors) {
o.setPosition(x, y);
}
}
public static void setMaxPrefSize(Layout... actors) {
float width = 0f, height = 0f;
for (Layout actor : actors) {
if (actor.getPrefWidth() > width) width = actor.getPrefWidth();
if (actor.getPrefHeight() > height) height = actor.getPrefHeight();
}
for (Layout actor : actors) {
((Actor) actor).setSize(width, height);
}
}
public static void move(Actor move, Direction direction, Actor other) {
move(move, direction, other, 0);
}
public static void move(Actor move, Direction direction, Actor other, float padding) {
switch (direction) {
case Above:
move.setX(other.getX());
move.setY(other.getY() + other.getHeight() + padding);
break;
case Below:
move.setX(other.getX());
move.setY(other.getY() - other.getHeight() - padding);
break;
case Left:
move.setX(other.getX() - other.getWidth() - padding);
move.setY(other.getX());
break;
case Right:
move.setX(other.getX() + other.getWidth() + padding);
move.setY(other.getX());
break;
}
}
public static void setTitle(Label label) {
label.setBounds(0, GUI_HEIGHT / 6 * 5, GUI_WIDTH, GUI_HEIGHT / 6);
label.setAlignment(Align.center, Align.center);
}
public static void copySize(Actor main, Actor... others) {
setSize(main.getWidth(), main.getHeight(), others);
}
public static void copyPos(Actor main, Actor... others) {
setPos(main.getX(), main.getY(), others);
}
public static void copyPosAndSize(Actor main, Actor... others) {
setPos(main.getX(), main.getY(), others);
setSize(main.getWidth(), main.getHeight(), others);
}
public static void arrangeX(float y, boolean centerY, Actor... actors) {
float w = GUI_WIDTH / actors.length;
for (int i = 0; i < actors.length; i++) {
Actor a = actors[i];
a.setPosition(((i + 0.5f) * w) - (a.getWidth() / 2f), y - (centerY ? (a.getWidth() / 2f) : 0));
}
}
public static void arrangeY(float x, boolean centerX, Actor... actors) {
float w = (GUI_HEIGHT / (actors.length + 1));
for (int i = 0; i < actors.length; i++) {
Actor a = actors[i];
a.setPosition(x - (centerX ? (a.getWidth() / 2f) : 0), ((i + 0.5f) * w) - (a.getHeight() / 2f));
}
}
public static void center(Actor actor) {
actor.setPosition((GUI_WIDTH / 2) - (actor.getWidth() / 2), (GUI_HEIGHT / 2) - (actor.getHeight() / 2));
}
public static void center(Actor... actors) {
for (Actor actor : actors) {
actor.setPosition((GUI_WIDTH / 2) - (actor.getWidth() / 2), (GUI_HEIGHT / 2) - (actor.getHeight() / 2));
}
}
public static TextButton getBackButton(final Menu menu) {
TextButton textButton = new TextButton(Localization.get("menu.general.back"), Menu.skin);
textButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Menu prev = MenuManager.getPrevious(menu);
if (prev == null) return;
Adapter.setMenu(prev);
}
});
return textButton;
}
} |
package liquibase.database;
import liquibase.change.*;
import liquibase.change.core.*;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.RanChangeSet;
import liquibase.database.structure.*;
import liquibase.executor.WriteExecutor;
import liquibase.executor.LoggingExecutor;
import liquibase.executor.ExecutorService;
import liquibase.diff.DiffStatusListener;
import liquibase.exception.*;
import liquibase.sql.Sql;
import liquibase.sql.visitor.SqlVisitor;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.statement.*;
import liquibase.util.ISODateFormat;
import liquibase.util.LiquibaseUtil;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtils;
import liquibase.util.log.LogFactory;
import java.io.IOException;
import java.io.Writer;
import java.math.BigInteger;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* AbstractDatabase is extended by all supported databases as a facade to the underlying database.
* The physical connection can be retrieved from the AbstractDatabase implementation, as well as any
* database-specific characteristics such as the datatype for "boolean" fields.
*/
public abstract class AbstractDatabase implements Database {
private DatabaseConnection connection;
private String defaultSchemaName;
static final protected Logger log = LogFactory.getLogger();
protected String currentDateTimeFunction;
private List<RanChangeSet> ranChangeSetList;
private static final DataType DATE_TYPE = new DataType("DATE", false);
private static final DataType TIME_TYPE = new DataType("TIME", false);
private static final DataType BIGINT_TYPE = new DataType("BIGINT", true);
private static final DataType CHAR_TYPE = new DataType("CHAR", true);
private static final DataType VARCHAR_TYPE = new DataType("VARCHAR", true);
private static final DataType FLOAT_TYPE = new DataType("FLOAT", true);
private static final DataType DOUBLE_TYPE = new DataType("DOUBLE", true);
private static final DataType INT_TYPE = new DataType("INT", true);
private static final DataType TINYINT_TYPE = new DataType("TINYINT", true);
private static Pattern CREATE_VIEW_AS_PATTERN = Pattern.compile("^CREATE\\s+.*?VIEW\\s+.*?AS\\s+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private String databaseChangeLogTableName = "DatabaseChangeLog".toUpperCase();
private String databaseChangeLogLockTableName = "DatabaseChangeLogLock".toUpperCase();;
protected AbstractDatabase() {
}
public DatabaseObject[] getContainingObjects() {
return null;
}
public DatabaseConnection getConnection() {
return connection;
}
public void setConnection(Connection conn) {
this.connection = new SQLConnectionDelegate(conn);
try {
connection.setAutoCommit(getAutoCommitMode());
} catch (SQLException sqle) {
log.warning("Can not set auto commit to " + getAutoCommitMode() + " on connection");
}
}
public void setConnection(DatabaseConnection conn) {
this.connection = conn;
try {
connection.setAutoCommit(getAutoCommitMode());
} catch (SQLException sqle) {
log.warning("Can not set auto commit to " + getAutoCommitMode() + " on connection");
}
}
/**
* Auto-commit mode to run in
*/
public boolean getAutoCommitMode() {
return !supportsDDLInTransaction();
}
/**
* By default databases should support DDL within a transaction.
*/
public boolean supportsDDLInTransaction() {
return true;
}
/**
* Returns the name of the database product according to the underlying database.
*/
public String getDatabaseProductName() {
try {
return connection.getMetaData().getDatabaseProductName();
} catch (SQLException e) {
throw new RuntimeException("Cannot get database name");
}
}
public String getDatabaseProductName(Connection conn) throws JDBCException {
try {
return conn.getMetaData().getDatabaseProductName();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public String getDatabaseProductVersion() throws JDBCException {
try {
return connection.getMetaData().getDatabaseProductVersion();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public int getDatabaseMajorVersion() throws JDBCException {
try {
return connection.getMetaData().getDatabaseMajorVersion();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public int getDatabaseMinorVersion() throws JDBCException {
try {
return connection.getMetaData().getDatabaseMinorVersion();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public String getDriverName() throws JDBCException {
try {
return connection.getMetaData().getDriverName();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public String getConnectionURL() throws JDBCException {
try {
return connection.getMetaData().getURL();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public String getConnectionUsername() throws JDBCException {
try {
return connection.getMetaData().getUserName();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public String getDefaultCatalogName() throws JDBCException {
return null;
}
protected String getDefaultDatabaseSchemaName() throws JDBCException {
return getConnectionUsername();
}
public String getDefaultSchemaName() {
return defaultSchemaName;
}
public void setDefaultSchemaName(String schemaName) throws JDBCException {
this.defaultSchemaName = schemaName;
}
/**
* Returns system (undroppable) tables and views.
*/
protected Set<String> getSystemTablesAndViews() {
return new HashSet<String>();
}
/**
* Does the database type support sequence.
*/
public boolean supportsSequences() {
return true;
}
public boolean supportsAutoIncrement() {
return true;
}
public void setCurrentDateTimeFunction(String function) {
if (function != null) {
this.currentDateTimeFunction = function;
}
}
/**
* Returns the database-specific datatype for the given column configuration.
* This method will convert some generic column types (e.g. boolean, currency) to the correct type
* for the current database.
*/
public String getColumnType(String columnType, Boolean autoIncrement) {
// Parse out data type and precision
// Example cases: "CLOB", "java.sql.Types.CLOB", "CLOB(10000)", "java.sql.Types.CLOB(10000)
String dataTypeName = null;
String precision = null;
if (columnType.startsWith("java.sql.Types") && columnType.contains("(")) {
precision = columnType.substring(columnType.indexOf("(") + 1, columnType.indexOf(")"));
dataTypeName = columnType.substring(columnType.lastIndexOf(".") + 1, columnType.indexOf("("));
} else if (columnType.startsWith("java.sql.Types")) {
dataTypeName = columnType.substring(columnType.lastIndexOf(".") + 1);
} else if (columnType.contains("(")) {
precision = columnType.substring(columnType.indexOf("(") + 1, columnType.indexOf(")"));
dataTypeName = columnType.substring(0, columnType.indexOf("("));
} else {
dataTypeName = columnType;
}
// Translate type to database-specific type, if possible
DataType returnTypeName = null;
if (dataTypeName.equalsIgnoreCase("BIGINT")) {
returnTypeName = getBigIntType();
} else if (dataTypeName.equalsIgnoreCase("BLOB")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
returnTypeName = getBooleanType();
} else if (dataTypeName.equalsIgnoreCase("CHAR")) {
returnTypeName = getCharType();
} else if (dataTypeName.equalsIgnoreCase("CLOB")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
returnTypeName = getCurrencyType();
} else if (dataTypeName.equalsIgnoreCase("DATE")) {
returnTypeName = getDateType();
} else if (dataTypeName.equalsIgnoreCase("DATETIME")) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
returnTypeName = getDoubleType();
} else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
returnTypeName = getFloatType();
} else if (dataTypeName.equalsIgnoreCase("INT")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("TEXT")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("TIME")) {
returnTypeName = getTimeType();
} else if (dataTypeName.equalsIgnoreCase("TIMESTAMP")) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
returnTypeName = getTinyIntType();
} else if (dataTypeName.equalsIgnoreCase("UUID")) {
returnTypeName = getUUIDType();
} else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
returnTypeName = getVarcharType();
} else {
if (columnType.startsWith("java.sql.Types")) {
returnTypeName = getTypeFromMetaData(dataTypeName);
} else {
// Don't know what it is, just return it
return columnType;
}
}
// Return type and precision, if any
if (precision != null && returnTypeName.getSupportsPrecision()) {
return returnTypeName.getDataTypeName() + "(" + precision + ")";
} else {
return returnTypeName.getDataTypeName();
}
}
// Get the type from the Connection MetaData (use the MetaData to translate from java.sql.Types to DB-specific type)
private DataType getTypeFromMetaData(final String dataTypeName)
{
ResultSet resultSet = null;
try {
Integer requestedType = (Integer) Class.forName("java.sql.Types").getDeclaredField(dataTypeName).get(null);
DatabaseConnection connection = getConnection();
if (connection == null) {
throw new RuntimeException("Cannot evaluate java.sql.Types without a connection");
}
resultSet = connection.getMetaData().getTypeInfo();
while (resultSet.next()) {
String typeName = resultSet.getString("TYPE_NAME");
int dataType = resultSet.getInt("DATA_TYPE");
int maxPrecision = resultSet.getInt("PRECISION");
if (requestedType == dataType) {
if (maxPrecision > 0) {
return new DataType(typeName, true);
} else {
return new DataType(typeName, false);
}
}
}
// Connection MetaData does not contain the type, return null
return null;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// Can't close result set, no handling required
}
}
}
}
public final String getColumnType(ColumnConfig columnConfig) {
return getColumnType(columnConfig.getType(), columnConfig.isAutoIncrement());
}
/**
* The database-specific value to use for "false" "boolean" columns.
*/
public String getFalseBooleanValue() {
return "false";
}
/**
* The database-specific value to use for "true" "boolean" columns.
*/
public String getTrueBooleanValue() {
return "true";
}
/**
* Return a date literal with the same value as a string formatted using ISO 8601.
* <p/>
* Note: many databases accept date literals in ISO8601 format with the 'T' replaced with
* a space. Only databases which do not accept these strings should need to override this
* method.
* <p/>
* Implementation restriction:
* Currently, only the following subsets of ISO8601 are supported:
* yyyy-MM-dd
* hh:mm:ss
* yyyy-MM-ddThh:mm:ss
*/
public String getDateLiteral(String isoDate) {
if (isDateOnly(isoDate) || isTimeOnly(isoDate)) {
return "'" + isoDate + "'";
} else if (isDateTime(isoDate)) {
// StringBuffer val = new StringBuffer();
// val.append("'");
// val.append(isoDate.substring(0, 10));
// val.append(" ");
////noinspection MagicNumber
// val.append(isoDate.substring(11));
// val.append("'");
// return val.toString();
return "'" + isoDate.replace('T', ' ') + "'";
} else {
return "BAD_DATE_FORMAT:" + isoDate;
}
}
public String getDateLiteral(java.sql.Timestamp date) {
return getDateLiteral(new ISODateFormat().format(date).replaceFirst("^'", "").replaceFirst("'$", ""));
}
public String getDateLiteral(java.sql.Date date) {
return getDateLiteral(new ISODateFormat().format(date).replaceFirst("^'", "").replaceFirst("'$", ""));
}
public String getDateLiteral(java.sql.Time date) {
return getDateLiteral(new ISODateFormat().format(date).replaceFirst("^'", "").replaceFirst("'$", ""));
}
public String getDateLiteral(Date date) {
if (date instanceof java.sql.Date) {
return getDateLiteral(((java.sql.Date) date));
} else if (date instanceof java.sql.Time) {
return getDateLiteral(((java.sql.Time) date));
} else if (date instanceof Timestamp) {
return getDateLiteral(((Timestamp) date));
} else if (date instanceof ComputedDateValue) {
return date.toString();
} else {
throw new RuntimeException("Unexpected type: " + date.getClass().getName());
}
}
protected Date parseDate(String dateAsString) throws DateParseException {
try {
if (dateAsString.indexOf(" ") > 0) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAsString);
} else if (dateAsString.indexOf("T") > 0) {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateAsString);
} else {
if (dateAsString.indexOf(":") > 0) {
return new SimpleDateFormat("HH:mm:ss").parse(dateAsString);
} else {
return new SimpleDateFormat("yyyy-MM-dd").parse(dateAsString);
}
}
} catch (ParseException e) {
throw new DateParseException(dateAsString);
}
}
protected boolean isDateOnly(String isoDate) {
return isoDate.length() == "yyyy-MM-dd".length();
}
protected boolean isDateTime(String isoDate) {
return isoDate.length() >= "yyyy-MM-ddThh:mm:ss".length();
}
protected boolean isTimeOnly(String isoDate) {
return isoDate.length() == "hh:mm:ss".length();
}
/**
* Returns the actual database-specific data type to use a "date" (no time information) column.
*/
public DataType getDateType() {
return DATE_TYPE;
}
/**
* Returns the actual database-specific data type to use a "time" column.
*/
public DataType getTimeType() {
return TIME_TYPE;
}
public DataType getBigIntType() {
return BIGINT_TYPE;
}
/** Returns the actual database-specific data type to use for a "char" column. */
public DataType getCharType()
{
return CHAR_TYPE;
}
/** Returns the actual database-specific data type to use for a "varchar" column. */
public DataType getVarcharType()
{
return VARCHAR_TYPE;
}
/**
* Returns the actual database-specific data type to use for a "float" column.
*
* @return database-specific type for float
*/
public DataType getFloatType()
{
return FLOAT_TYPE;
}
/**
* Returns the actual database-specific data type to use for a "double" column.
*
* @return database-specific type for double
*/
public DataType getDoubleType()
{
return DOUBLE_TYPE;
}
/**
* Returns the actual database-specific data type to use for a "int" column.
*
* @return database-specific type for int
*/
public DataType getIntType()
{
return INT_TYPE;
}
/**
* Returns the actual database-specific data type to use for a "tinyint" column.
*
* @return database-specific type for tinyint
*/
public DataType getTinyIntType()
{
return TINYINT_TYPE;
}
/**
* Returns database-specific line comment string.
*/
public String getLineComment() {
return "
}
/**
* Returns database-specific auto-increment DDL clause.
*/
public String getAutoIncrementClause() {
return "AUTO_INCREMENT";
}
public String getConcatSql(String... values) {
StringBuffer returnString = new StringBuffer();
for (String value : values) {
returnString.append(value).append(" || ");
}
return returnString.toString().replaceFirst(" \\|\\| $", "");
}
/**
* @see liquibase.database.Database#getDatabaseChangeLogTableName()
*/
public String getDatabaseChangeLogTableName() {
return databaseChangeLogTableName;
}
/**
* @see liquibase.database.Database#getDatabaseChangeLogLockTableName()
*/
public String getDatabaseChangeLogLockTableName() {
return databaseChangeLogLockTableName;
}
/**
* @see liquibase.database.Database#setDatabaseChangeLogTableName(java.lang.String)
*/
public void setDatabaseChangeLogTableName(String tableName) {
this.databaseChangeLogTableName = tableName;
}
/**
* @see liquibase.database.Database#setDatabaseChangeLogLockTableName(java.lang.String)
*/
public void setDatabaseChangeLogLockTableName(String tableName) {
this.databaseChangeLogLockTableName = tableName;
}
private SqlStatement getChangeLogLockInsertSQL() throws JDBCException {
return new InsertStatement(getLiquibaseSchemaName(), getDatabaseChangeLogLockTableName())
.addColumnValue("ID", 1)
.addColumnValue("LOCKED", Boolean.FALSE);
}
protected SqlStatement getCreateChangeLogSQL() throws JDBCException {
return new CreateTableStatement(getLiquibaseSchemaName(), getDatabaseChangeLogTableName())
.addPrimaryKeyColumn("ID", "VARCHAR(63)", null, null, new NotNullConstraint())
.addPrimaryKeyColumn("AUTHOR", "VARCHAR(63)", null, null, new NotNullConstraint())
.addPrimaryKeyColumn("FILENAME", "VARCHAR(200)", null, null, new NotNullConstraint())
.addColumn("DATEEXECUTED", getDateTimeType().getDataTypeName(), new NotNullConstraint())
.addColumn("MD5SUM", "VARCHAR(35)")
.addColumn("DESCRIPTION", "VARCHAR(255)")
.addColumn("COMMENTS", "VARCHAR(255)")
.addColumn("TAG", "VARCHAR(255)")
.addColumn("LIQUIBASE", "VARCHAR(10)");
}
public boolean doesChangeLogTableExist() throws JDBCException {
DatabaseConnection connection = getConnection();
ResultSet rs = null;
try {
rs = connection.getMetaData().getTables(convertRequestedSchemaToCatalog(getDefaultSchemaName()), convertRequestedSchemaToSchema(getLiquibaseSchemaName()), getDatabaseChangeLogTableName(), new String[]{"TABLE"});
return rs.next();
} catch (Exception e) {
throw new JDBCException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warning("Error closing result set: " + e.getMessage());
}
}
}
}
/**
* This method will check the database ChangeLog table used to keep track of
* the changes in the file. If the table does not exist it will create one
* otherwise it will not do anything besides outputting a log message.
*/
public void checkDatabaseChangeLogTable() throws JDBCException {
WriteExecutor writeExecutor = ExecutorService.getInstance().getWriteExecutor(this);
if (!writeExecutor.executesStatements()) {
if (((LoggingExecutor) writeExecutor).alreadyCreatedChangeTable()) {
return;
} else {
((LoggingExecutor) writeExecutor).setAlreadyCreatedChangeTable(true);
}
}
DatabaseConnection connection = getConnection();
ResultSet checkColumnsRS = null;
List<SqlStatement> statementsToExecute = new ArrayList<SqlStatement>();
boolean changeLogCreateAttempted = false;
try {
if (doesChangeLogTableExist()) {
checkColumnsRS = connection.getMetaData().getColumns(convertRequestedSchemaToCatalog(getLiquibaseSchemaName()), convertRequestedSchemaToSchema(getLiquibaseSchemaName()), getDatabaseChangeLogTableName(), null);
boolean hasDescription = false;
boolean hasComments = false;
boolean hasTag = false;
boolean hasLiquibase = false;
while (checkColumnsRS.next()) {
String columnName = checkColumnsRS.getString("COLUMN_NAME");
if ("DESCRIPTION".equalsIgnoreCase(columnName)) {
hasDescription = true;
} else if ("COMMENTS".equalsIgnoreCase(columnName)) {
hasComments = true;
} else if ("TAG".equalsIgnoreCase(columnName)) {
hasTag = true;
} else if ("LIQUIBASE".equalsIgnoreCase(columnName)) {
hasLiquibase = true;
}
}
if (!hasDescription) {
statementsToExecute.add(new AddColumnStatement(getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", "VARCHAR(255)", null));
}
if (!hasTag) {
statementsToExecute.add(new AddColumnStatement(getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", "VARCHAR(255)", null));
}
if (!hasComments) {
statementsToExecute.add(new AddColumnStatement(getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", "VARCHAR(255)", null));
}
if (!hasLiquibase) {
statementsToExecute.add(new AddColumnStatement(getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", "VARCHAR(255)", null));
}
} else if (!changeLogCreateAttempted) {
writeExecutor.comment("Create Database Change Log Table");
SqlStatement createTableStatement = getCreateChangeLogSQL();
if (!canCreateChangeLogTable()) {
throw new JDBCException("Cannot create " + escapeTableName(getDefaultSchemaName(), getDatabaseChangeLogTableName()) + " table for your database.\n\n" +
"Please construct it manually using the following SQL as a base and re-run LiquiBase:\n\n" +
createTableStatement);
}
// If there is no table in the database for recording change history create one.
statementsToExecute.add(createTableStatement);
log.info("Creating database history table with name: " + escapeTableName(getDefaultSchemaName(), getDatabaseChangeLogTableName()));
}
for (SqlStatement sql : statementsToExecute) {
writeExecutor.execute(sql, new ArrayList<SqlVisitor>());
this.commit();
}
} catch (SQLException e) {
throw new JDBCException(e);
} finally {
if (checkColumnsRS != null) {
try {
checkColumnsRS.close();
} catch (SQLException e) {
//noinspection ThrowFromFinallyBlock
throw new JDBCException(e);
}
}
}
}
protected boolean canCreateChangeLogTable() throws JDBCException {
return true;
}
public boolean doesChangeLogLockTableExist() throws JDBCException {
DatabaseConnection connection = getConnection();
ResultSet rs = null;
try {
rs = connection.getMetaData().getTables(convertRequestedSchemaToCatalog(getLiquibaseSchemaName()), convertRequestedSchemaToSchema(getLiquibaseSchemaName()), getDatabaseChangeLogLockTableName(), new String[]{"TABLE"});
return rs.next();
} catch (Exception e) {
throw new JDBCException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warning("Error closing result set: " + e.getMessage());
}
}
}
}
public String getLiquibaseSchemaName() {
return getDefaultSchemaName();
}
/**
* This method will check the database ChangeLogLock table used to keep track of
* if a machine is updating the database. If the table does not exist it will create one
* otherwise it will not do anything besides outputting a log message.
*/
public void checkDatabaseChangeLogLockTable() throws JDBCException {
boolean knowMustInsertIntoLockTable = false;
WriteExecutor writeExecutor = ExecutorService.getInstance().getWriteExecutor(this);
if (!doesChangeLogLockTableExist()) {
if (!writeExecutor.executesStatements()) {
if (((LoggingExecutor) writeExecutor).alreadyCreatedChangeLockTable()) {
return;
} else {
((LoggingExecutor) writeExecutor).setAlreadyCreatedChangeLockTable(true);
}
}
SqlStatement createTableStatement = new CreateDatabaseChangeLogLockTableStatement();
writeExecutor.comment("Create Database Lock Table");
writeExecutor.execute(createTableStatement, new ArrayList<SqlVisitor>());
this.commit();
log.finest("Created database lock table with name: " + escapeTableName(getLiquibaseSchemaName(), getDatabaseChangeLogLockTableName()));
knowMustInsertIntoLockTable = true;
}
int rows = -1;
if (!knowMustInsertIntoLockTable) {
SqlStatement selectStatement = new SelectFromDatabaseChangeLogLockStatement("COUNT(*)");
try {
List<Map> returnList = ExecutorService.getInstance().getReadExecutor(this).queryForList(selectStatement, new ArrayList<SqlVisitor>());
if (returnList == null || returnList.size() == 0) {
rows = 0;
} else {
Map map = returnList.get(0);
rows = Integer.parseInt(map.values().iterator().next().toString());
}
} catch (JDBCException e) {
throw e;
}
}
if (knowMustInsertIntoLockTable || rows == 0) {
writeExecutor.update(getChangeLogLockInsertSQL(), new ArrayList<SqlVisitor>());
this.commit();
log.fine("Inserted lock row into: " + escapeTableName(getLiquibaseSchemaName(), getDatabaseChangeLogLockTableName()));
}
}
/**
* Drops all objects owned by the connected user.
*
* @param schema
*/
public void dropDatabaseObjects(String schema) throws JDBCException {
try {
DatabaseSnapshot snapshot = createDatabaseSnapshot(schema, new HashSet<DiffStatusListener>());
List<Change> dropChanges = new ArrayList<Change>();
for (View view : snapshot.getViews()) {
DropViewChange dropChange = new DropViewChange();
dropChange.setViewName(view.getName());
dropChange.setSchemaName(schema);
dropChanges.add(dropChange);
}
for (ForeignKey fk : snapshot.getForeignKeys()) {
DropForeignKeyConstraintChange dropFK = new DropForeignKeyConstraintChange();
dropFK.setBaseTableSchemaName(schema);
dropFK.setBaseTableName(fk.getForeignKeyTable().getName());
dropFK.setConstraintName(fk.getName());
dropChanges.add(dropFK);
}
// for (Index index : snapshot.getIndexes()) {
// DropIndexChange dropChange = new DropIndexChange();
// dropChange.setIndexName(index.getName());
// dropChange.setSchemaName(schema);
// dropChange.setTableName(index.getTableName());
// dropChanges.add(dropChange);
for (Table table : snapshot.getTables()) {
DropTableChange dropChange = new DropTableChange();
dropChange.setSchemaName(schema);
dropChange.setTableName(table.getName());
dropChange.setCascadeConstraints(true);
dropChanges.add(dropChange);
}
if (this.supportsSequences()) {
for (Sequence seq : snapshot.getSequences()) {
DropSequenceChange dropChange = new DropSequenceChange();
dropChange.setSequenceName(seq.getName());
dropChange.setSchemaName(schema);
dropChanges.add(dropChange);
}
}
if (snapshot.hasDatabaseChangeLogTable()) {
dropChanges.add(new AnonymousChange(new ClearDatabaseChangeLogTableStatement()));
}
for (Change change : dropChanges) {
for (SqlStatement statement : change.generateStatements(this)) {
ExecutorService.getInstance().getWriteExecutor(this).execute(statement, new ArrayList<SqlVisitor>());
}
}
} finally {
this.commit();
}
}
public boolean isSystemTable(String catalogName, String schemaName, String tableName) {
if ("information_schema".equalsIgnoreCase(schemaName)) {
return true;
} else if (tableName.equalsIgnoreCase(getDatabaseChangeLogLockTableName())) {
return true;
} else if (getSystemTablesAndViews().contains(tableName)) {
return true;
}
return false;
}
public boolean isSystemView(String catalogName, String schemaName, String viewName) {
if ("information_schema".equalsIgnoreCase(schemaName)) {
return true;
} else if (getSystemTablesAndViews().contains(viewName)) {
return true;
}
return false;
}
public boolean isLiquibaseTable(String tableName) {
return tableName.equalsIgnoreCase(this.getDatabaseChangeLogTableName()) || tableName.equalsIgnoreCase(this.getDatabaseChangeLogLockTableName());
}
/**
* Tags the database changelog with the given string.
*/
public void tag(String tagString) throws JDBCException {
WriteExecutor writeExecutor = ExecutorService.getInstance().getWriteExecutor(this);
try {
int totalRows = ExecutorService.getInstance().getReadExecutor(this).queryForInt(new SelectFromDatabaseChangeLogStatement("COUNT(*)"), new ArrayList<SqlVisitor>());
if (totalRows == 0) {
throw new JDBCException("Cannot tag an empty database");
}
// Timestamp lastExecutedDate = (Timestamp) this.getWriteExecutor().queryForObject(createChangeToTagSQL(), Timestamp.class);
int rowsUpdated = writeExecutor.update(new TagDatabaseStatement(tagString), new ArrayList<SqlVisitor>());
if (rowsUpdated == 0) {
throw new JDBCException("Did not tag database change log correctly");
}
this.commit();
} catch (Exception e) {
throw new JDBCException(e);
}
}
public boolean doesTagExist(String tag) throws JDBCException {
int count = ExecutorService.getInstance().getReadExecutor(this).queryForInt(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByTag("tag"), "COUNT(*)"), new ArrayList<SqlVisitor>());
return count > 0;
}
@Override
public String toString() {
if (getConnection() == null) {
return getTypeName() + " Database";
}
try {
return getConnectionUsername() + " @ " + getConnectionURL() + (getDefaultSchemaName() == null ? "" : " (Default Schema: " + getDefaultSchemaName() + ")");
} catch (JDBCException e) {
return super.toString();
}
}
public boolean shouldQuoteValue(String value) {
return true;
}
public String getViewDefinition(String schemaName, String viewName) throws JDBCException {
if (schemaName == null) {
schemaName = convertRequestedSchemaToSchema(null);
}
String definition = (String) ExecutorService.getInstance().getReadExecutor(this).queryForObject(getViewDefinitionSql(schemaName, viewName), String.class, new ArrayList<SqlVisitor>());
if (definition == null) {
return null;
}
return CREATE_VIEW_AS_PATTERN.matcher(definition).replaceFirst("");
}
public SqlStatement getViewDefinitionSql(String schemaName, String viewName) throws JDBCException {
return new GetViewDefinitionStatement(schemaName, viewName); //todo: remove
}
public int getDatabaseType(int type) {
int returnType = type;
if (returnType == Types.BOOLEAN) {
String booleanType = getBooleanType().getDataTypeName();
if (!booleanType.equalsIgnoreCase("boolean")) {
returnType = Types.TINYINT;
}
}
return returnType;
}
public Object convertDatabaseValueToJavaObject(Object defaultValue, int dataType, int columnSize, int decimalDigits) throws ParseException {
if (defaultValue == null) {
return null;
} else if (defaultValue instanceof String) {
return convertToCorrectJavaType(((String) defaultValue).replaceFirst("^'", "").replaceFirst("'$", ""), dataType, columnSize, decimalDigits);
} else {
return defaultValue;
}
}
protected Object convertToCorrectJavaType(String value, int dataType, int columnSize, int decimalDigits) throws ParseException {
if (value == null) {
return null;
}
if (dataType == Types.CLOB || dataType == Types.VARCHAR || dataType == Types.CHAR || dataType == Types.LONGVARCHAR) {
if (value.equalsIgnoreCase("NULL")) {
return null;
} else {
return value;
}
}
value = StringUtils.trimToNull(value);
if (value == null) {
return null;
}
try {
if (dataType == Types.DATE) {
return new java.sql.Date(parseDate(value).getTime());
} else if (dataType == Types.TIMESTAMP) {
return new Timestamp(parseDate(value).getTime());
} else if (dataType == Types.TIME) {
return new Time(parseDate(value).getTime());
} else if (dataType == Types.BIGINT) {
return new BigInteger(value);
} else if (dataType == Types.BIT) {
value = value.replaceFirst("b'",""); //mysql puts wierd chars in bit field
if (value.equalsIgnoreCase("true")) {
return Boolean.TRUE;
} else if (value.equalsIgnoreCase("false")) {
return Boolean.FALSE;
} else if (value.equals("1")) {
return Boolean.TRUE;
} else if (value.equals("0")) {
return Boolean.FALSE;
} else if (value.equals("(1)")) {
return Boolean.TRUE;
} else if (value.equals("(0)")) {
return Boolean.FALSE;
}
throw new ParseException("Unknown bit value: " + value, 0);
} else if (dataType == Types.BOOLEAN) {
return Boolean.valueOf(value);
} else if (dataType == Types.DECIMAL) {
if (decimalDigits == 0) {
return new Integer(value);
}
return new Double(value);
} else if (dataType == Types.DOUBLE || dataType == Types.NUMERIC) {
return new Double(value);
} else if (dataType == Types.FLOAT) {
return new Float(value);
} else if (dataType == Types.INTEGER) {
return new Integer(value);
} else if (dataType == Types.NULL) {
return null;
} else if (dataType == Types.REAL) {
return new Float(value);
} else if (dataType == Types.SMALLINT) {
return new Integer(value);
} else if (dataType == Types.TINYINT) {
return new Integer(value);
} else if (dataType == Types.BLOB) {
return "!!!!!! LIQUIBASE CANNOT OUTPUT BLOB VALUES !!!!!!";
} else {
log.warning("Do not know how to convert type " + dataType);
return value;
}
} catch (DateParseException e) {
return new ComputedDateValue(value);
} catch (NumberFormatException e) {
return new ComputedNumericValue(value);
}
}
public String convertJavaObjectToString(Object value) {
if (value != null) {
if (value instanceof String) {
if ("null".equalsIgnoreCase(((String) value))) {
return null;
}
return "'" + ((String) value).replaceAll("'", "''") + "'";
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof Boolean) {
String returnValue;
if (((Boolean) value)) {
returnValue = this.getTrueBooleanValue();
} else {
returnValue = this.getFalseBooleanValue();
}
if (returnValue.matches("\\d+")) {
return returnValue;
} else {
return "'" + returnValue + "'";
}
} else if (value instanceof java.sql.Date) {
return this.getDateLiteral(((java.sql.Date) value));
} else if (value instanceof java.sql.Time) {
return this.getDateLiteral(((java.sql.Time) value));
} else if (value instanceof java.sql.Timestamp) {
return this.getDateLiteral(((java.sql.Timestamp) value));
} else if (value instanceof ComputedDateValue) {
return ((ComputedDateValue) value).getValue();
} else {
throw new RuntimeException("Unknown default value type: " + value.getClass().getName());
}
} else {
return null;
}
}
public String escapeTableName(String schemaName, String tableName) {
if (schemaName == null) {
schemaName = getDefaultSchemaName();
}
if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) {
return escapeDatabaseObject(tableName);
} else {
return escapeDatabaseObject(schemaName)+"."+escapeDatabaseObject(tableName);
}
}
public String escapeDatabaseObject(String objectName) {
return objectName;
}
public String escapeIndexName(String schemaName, String indexName) {
if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) {
return escapeDatabaseObject(indexName);
} else {
return escapeDatabaseObject(schemaName)+"."+escapeDatabaseObject(indexName);
}
}
public String escapeSequenceName(String schemaName, String sequenceName) {
if (schemaName == null) {
schemaName = getDefaultSchemaName();
}
if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) {
return escapeDatabaseObject(sequenceName);
} else {
return escapeDatabaseObject(schemaName)+"."+escapeDatabaseObject(sequenceName);
}
}
public String escapeConstraintName(String constraintName) {
return escapeDatabaseObject(constraintName);
}
public String escapeColumnName(String schemaName, String tableName, String columnName) {
if (schemaName == null) {
schemaName = getDefaultSchemaName();
}
return escapeDatabaseObject(columnName);
}
public String escapeColumnNameList(String columnNames) {
StringBuffer sb = new StringBuffer();
for(String columnName : columnNames.split(",")) {
if(sb.length() > 0) {
sb.append(", ");
}
sb.append(escapeDatabaseObject(columnName.trim()));
}
return sb.toString();
}
public String convertRequestedSchemaToCatalog(String requestedSchema) throws JDBCException {
if (getDefaultCatalogName() == null) {
return null;
} else {
if (requestedSchema == null) {
return getDefaultCatalogName();
}
return StringUtils.trimToNull(requestedSchema);
}
}
public String convertRequestedSchemaToSchema(String requestedSchema) throws JDBCException {
String returnSchema = requestedSchema;
if (returnSchema == null) {
returnSchema = getDefaultDatabaseSchemaName();
}
if (returnSchema != null) {
returnSchema = returnSchema.toUpperCase();
}
return returnSchema;
}
public boolean supportsSchemas() {
return true;
}
public String generatePrimaryKeyName(String tableName) {
return "PK_" + tableName.toUpperCase();
}
public String escapeViewName(String schemaName, String viewName) {
return escapeTableName(schemaName, viewName);
}
public boolean isColumnAutoIncrement(String schemaName, String tableName, String columnName) throws SQLException, JDBCException {
if (!supportsAutoIncrement()) {
return false;
}
boolean autoIncrement = false;
ResultSet selectRS = null;
try {
selectRS = getConnection().createStatement().executeQuery("SELECT " + escapeColumnName(schemaName, tableName, columnName) + " FROM " + escapeTableName(schemaName, tableName) + " WHERE 1 = 0");
ResultSetMetaData meta = selectRS.getMetaData();
autoIncrement = meta.isAutoIncrement(1);
} finally {
if (selectRS != null) {
selectRS.close();
}
}
return autoIncrement;
}
/**
* Returns the run status for the given ChangeSet
*/
public ChangeSet.RunStatus getRunStatus(ChangeSet changeSet) throws JDBCException, DatabaseHistoryException {
if (!doesChangeLogTableExist()) {
return ChangeSet.RunStatus.NOT_RAN;
}
RanChangeSet foundRan = getRanChangeSet(changeSet);
if (foundRan == null) {
return ChangeSet.RunStatus.NOT_RAN;
} else {
if (foundRan.getLastCheckSum() == null) {
try {
log.info("Updating NULL md5sum for " + changeSet.toString());
DatabaseConnection connection = getConnection();
PreparedStatement updatePstmt = connection.prepareStatement("UPDATE " + escapeTableName(getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " SET MD5SUM=? WHERE ID=? AND AUTHOR=? AND FILENAME=?");
updatePstmt.setString(1, changeSet.generateCheckSum().toString());
updatePstmt.setString(2, changeSet.getId());
updatePstmt.setString(3, changeSet.getAuthor());
updatePstmt.setString(4, changeSet.getFilePath());
updatePstmt.executeUpdate();
updatePstmt.close();
this.commit();
} catch (SQLException e) {
throw new JDBCException(e);
}
return ChangeSet.RunStatus.ALREADY_RAN;
} else {
if (foundRan.getLastCheckSum().equals(changeSet.generateCheckSum())) {
return ChangeSet.RunStatus.ALREADY_RAN;
} else {
if (changeSet.shouldRunOnChange()) {
return ChangeSet.RunStatus.RUN_AGAIN;
} else {
return ChangeSet.RunStatus.INVALID_MD5SUM;
// throw new DatabaseHistoryException("MD5 Check for " + changeSet.toString() + " failed");
}
}
}
}
}
public RanChangeSet getRanChangeSet(ChangeSet changeSet) throws JDBCException, DatabaseHistoryException {
if (!doesChangeLogTableExist()) {
throw new DatabaseHistoryException("Database change table does not exist");
}
RanChangeSet foundRan = null;
for (RanChangeSet ranChange : getRanChangeSetList()) {
if (ranChange.isSameAs(changeSet)) {
foundRan = ranChange;
break;
}
}
return foundRan;
}
/**
* Returns the ChangeSets that have been run against the current database.
*/
public List<RanChangeSet> getRanChangeSetList() throws JDBCException {
if (this.ranChangeSetList != null) {
return this.ranChangeSetList;
}
try {
String databaseChangeLogTableName = escapeTableName(getLiquibaseSchemaName(), getDatabaseChangeLogTableName());
ranChangeSetList = new ArrayList<RanChangeSet>();
if (doesChangeLogTableExist()) {
log.info("Reading from " + databaseChangeLogTableName);
String sql = "SELECT * FROM " + databaseChangeLogTableName + " ORDER BY DATEEXECUTED ASC".toUpperCase();
Statement statement = getConnection().createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
String fileName = rs.getString("FILENAME");
String author = rs.getString("AUTHOR");
String id = rs.getString("ID");
String md5sum = rs.getString("MD5SUM");
Date dateExecuted = rs.getTimestamp("DATEEXECUTED");
String tag = rs.getString("TAG");
RanChangeSet ranChangeSet = new RanChangeSet(fileName, id, author, CheckSum.parse(md5sum), dateExecuted, tag);
ranChangeSetList.add(ranChangeSet);
}
rs.close();
statement.close();
}
return ranChangeSetList;
} catch (SQLException e) {
if (!ExecutorService.getInstance().getWriteExecutor(this).executesStatements()) {
//probably not created, no problem
return new ArrayList<RanChangeSet>();
} else {
throw new JDBCException(e);
}
}
}
public Date getRanDate(ChangeSet changeSet) throws JDBCException, DatabaseHistoryException {
RanChangeSet ranChange = getRanChangeSet(changeSet);
if (ranChange == null) {
return null;
} else {
return ranChange.getDateExecuted();
}
}
/**
* After the change set has been ran against the database this method will update the change log table
* with the information.
*/
public void markChangeSetAsRan(ChangeSet changeSet) throws JDBCException {
String dateValue = getCurrentDateTimeFunction();
InsertStatement statement = new InsertStatement(getLiquibaseSchemaName(), getDatabaseChangeLogTableName());
statement.addColumnValue("ID", escapeStringForDatabase(changeSet.getId()));
statement.addColumnValue("AUTHOR", changeSet.getAuthor());
statement.addColumnValue("FILENAME", changeSet.getFilePath());
statement.addColumnValue("DATEEXECUTED", new ComputedDateValue(dateValue));
statement.addColumnValue("MD5SUM", changeSet.generateCheckSum().toString());
statement.addColumnValue("DESCRIPTION", limitSize(changeSet.getDescription()));
statement.addColumnValue("COMMENTS", limitSize(StringUtils.trimToEmpty(changeSet.getComments())));
statement.addColumnValue("LIQUIBASE", LiquibaseUtil.getBuildVersion());
ExecutorService.getInstance().getWriteExecutor(this).execute(statement, new ArrayList<SqlVisitor>());
getRanChangeSetList().add(new RanChangeSet(changeSet));
}
public void markChangeSetAsReRan(ChangeSet changeSet) throws JDBCException {
String dateValue = getCurrentDateTimeFunction();
String sql = "UPDATE " + escapeTableName(getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " SET DATEEXECUTED=" + dateValue + ", MD5SUM='?' WHERE ID='?' AND AUTHOR='?' AND FILENAME='?'";
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.generateCheckSum().toString()));
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.getId()));
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.getAuthor()));
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.getFilePath()));
ExecutorService.getInstance().getWriteExecutor(this).execute(new RawSqlStatement(sql), new ArrayList<SqlVisitor>());
this.commit();
}
public void removeRanStatus(ChangeSet changeSet) throws JDBCException {
String sql = "DELETE FROM " + escapeTableName(getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " WHERE ID='?' AND AUTHOR='?' AND FILENAME='?'";
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.getId()));
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.getAuthor()));
sql = sql.replaceFirst("\\?", escapeStringForDatabase(changeSet.getFilePath()));
ExecutorService.getInstance().getWriteExecutor(this).execute(new RawSqlStatement(sql), new ArrayList<SqlVisitor>());
commit();
getRanChangeSetList().remove(new RanChangeSet(changeSet));
}
public String escapeStringForDatabase(String string) {
return string.replaceAll("'", "''");
}
private String limitSize(String string) {
int maxLength = 255;
if (string.length() > maxLength) {
return string.substring(0, maxLength - 3) + "...";
}
return string;
}
public void commit() throws JDBCException {
try {
getConnection().commit();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public void rollback() throws JDBCException {
try {
getConnection().rollback();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractDatabase that = (AbstractDatabase) o;
return !(connection != null ? !connection.equals(that.connection) : that.connection != null);
}
@Override
public int hashCode() {
return (connection != null ? connection.hashCode() : 0);
}
public void close() throws JDBCException {
try {
DatabaseConnection connection = getConnection();
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public abstract DatabaseSnapshot createDatabaseSnapshot(String schema, Set<DiffStatusListener> statusListeners) throws JDBCException;
public boolean supportsRestrictForeignKeys() {
return true;
}
public boolean isAutoCommit() throws JDBCException {
try {
return getConnection().getAutoCommit();
} catch (SQLException e) {
throw new JDBCException(e);
}
}
public void setAutoCommit(boolean b) throws JDBCException {
try {
getConnection().setAutoCommit(b);
} catch (SQLException e) {
throw new JDBCException(e);
}
}
/**
* Default implementation, just look for "local" IPs
* @throws JDBCException
*/
public boolean isLocalDatabase() throws JDBCException {
String url = getConnectionURL();
return (url.indexOf("localhost") >= 0) || (url.indexOf("127.0.0.1") >= 0);
}
public void executeStatements(Change change, List<SqlVisitor> sqlVisitors) throws LiquibaseException, UnsupportedChangeException {
SqlStatement[] statements = change.generateStatements(this);
execute(statements, sqlVisitors);
}
/*
* Executes the statements passed as argument to a target {@link Database}
*
* @param statements an array containing the SQL statements to be issued
* @param database the target {@link Database}
* @throws JDBCException if there were problems issuing the statements
*/
public void execute(SqlStatement[] statements, List<SqlVisitor> sqlVisitors) throws LiquibaseException {
for (SqlStatement statement : statements) {
LogFactory.getLogger().finest("Executing Statement: " + statement);
ExecutorService.getInstance().getWriteExecutor(this).execute(statement, sqlVisitors);
}
}
public void saveStatements(Change change, List<SqlVisitor> sqlVisitors, Writer writer) throws IOException, UnsupportedChangeException, StatementNotSupportedOnDatabaseException, LiquibaseException {
SqlStatement[] statements = change.generateStatements(this);
for (SqlStatement statement : statements) {
for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, this)) {
writer.append(sql.toSql()).append(sql.getEndDelimiter()).append(StreamUtil.getLineSeparator()).append(StreamUtil.getLineSeparator());
}
}
}
public void executeRollbackStatements(Change change, List<SqlVisitor> sqlVisitors) throws LiquibaseException, UnsupportedChangeException, RollbackImpossibleException {
SqlStatement[] statements = change.generateRollbackStatements(this);
execute(statements, sqlVisitors);
}
public void saveRollbackStatement(Change change, List<SqlVisitor> sqlVisitors, Writer writer) throws IOException, UnsupportedChangeException, RollbackImpossibleException, StatementNotSupportedOnDatabaseException, LiquibaseException {
SqlStatement[] statements = change.generateRollbackStatements(this);
for (SqlStatement statement : statements) {
for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, this)) {
writer.append(sql.toSql()).append(sql.getEndDelimiter()).append("\n\n");
}
}
}
public boolean isPeculiarLiquibaseSchema() {
return false;
}
} |
package arez.component;
import arez.Arez;
import arez.Disposable;
import arez.SafeProcedure;
import java.util.ArrayList;
import java.util.HashMap;
import javax.annotation.Nonnull;
import static org.realityforge.braincheck.Guards.*;
/**
* The class responsible for notifying listeners when an element is disposed.
* Listeners are added to a notify list using a key and should be added at most once.
* The listeners can also be removed from the notify list. The notifier will then notifier
* will then notify all listeners when {@link #dispose()} is invoked after which this
* class should no longer been interacted with.
*/
public final class DisposeNotifier
implements Disposable
{
private final HashMap<Object, SafeProcedure> _listeners = new HashMap<>();
private boolean _disposed;
/**
* {@inheritDoc}
*/
@Override
public void dispose()
{
if ( isNotDisposed() )
{
for ( final SafeProcedure procedure : new ArrayList<>( _listeners.values() ) )
{
procedure.call();
}
_disposed = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDisposed()
{
return _disposed;
}
/**
* Add the listener to notify list under key.
* This method MUST NOT be invoked after {@link #dispose()} has been invoked.
* This method should not be invoked if another listener has been added with the same key without
* being removed.
*
* @param key the key to uniquely identify listener.
* @param action the listener callback.
*/
public void addOnDisposeListener( @Nonnull final Object key, @Nonnull final SafeProcedure action )
{
if ( Arez.shouldCheckApiInvariants() )
{
invariant( this::isNotDisposed,
() -> "Arez-0170: Attempting to add OnDispose listener but DisposeNotifier has been disposed." );
invariant( () -> !_listeners.containsKey( key ),
() -> "Arez-0166: Attempting to add dispose listener with key '" + key +
"' but a listener with that key already exists." );
}
_listeners.put( key, action );
}
/**
* Remove the listener with specified key from the notify list.
* This method MUST NOT be invoked after {@link #dispose()} has been invoked.
* This method should only be invoked when a listener has been added for specific key using
* {@link #addOnDisposeListener(Object, SafeProcedure)} and has not been removed by another
* call to this method.
*
* @param key the key under which the listener was previously added.
*/
public void removeOnDisposeListener( @Nonnull final Object key )
{
if ( Arez.shouldCheckApiInvariants() )
{
invariant( this::isNotDisposed,
() -> "Arez-0169: Attempting to remove OnDispose listener but DisposeNotifier has been disposed." );
}
final SafeProcedure removed = _listeners.remove( key );
if ( Arez.shouldCheckApiInvariants() )
{
invariant( () -> null != removed,
() -> "Arez-0167: Attempting to remove dispose listener with key '" + key +
"' but no such listener exists." );
}
}
@Nonnull
HashMap<Object, SafeProcedure> getListeners()
{
return _listeners;
}
} |
package brooklyn.util.config;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.config.ConfigKey;
import brooklyn.config.ConfigKey.HasConfigKey;
import brooklyn.util.flags.TypeCoercions;
import com.google.common.collect.Sets;
/**
* Stores config in such a way that usage can be tracked.
* Either {@link ConfigKey} or {@link String} keys can be inserted;
* they will be stored internally as strings.
* It is recommended to use {@link ConfigKey} instances to access,
* although in some cases (such as setting fields from flags, or copying a map)
* it may be necessary to mark things as used, or put, when only a string key is available.
*
* @author alex
*/
public class ConfigBag {
private static final Logger log = LoggerFactory.getLogger(ConfigBag.class);
/** an immutable, empty ConfigBag */
public static final ConfigBag EMPTY = new ConfigBag().setDescription("immutable empty config bag").seal();
protected String description;
private Map<String,Object> config = new LinkedHashMap<String,Object>();
private Map<String,Object> unusedConfig = new LinkedHashMap<String,Object>();
private boolean sealed = false;
public ConfigBag setDescription(String description) {
if (sealed)
throw new IllegalStateException("Cannot set description to '"+description+"': this config bag has been sealed and is now immutable.");
this.description = description;
return this;
}
/** optional description used to provide context for operations */
public String getDescription() {
return description;
}
/** current values for all entries
* @return non-modifiable map of strings to object */
public Map<String,Object> getAllConfig() {
return Collections.unmodifiableMap(config);
}
/** internal map containing the current values for all entries;
* for use where the caller wants to modify this directly and knows it is safe to do so */
public Map<String,Object> getAllConfigRaw() {
return config;
}
/** current values for all entries which have not yet been used
* @return non-modifiable map of strings to object */
public Map<String,Object> getUnusedConfig() {
return Collections.unmodifiableMap(unusedConfig);
}
/** internal map containing the current values for all entries which have not yet been used;
* for use where the caller wants to modify this directly and knows it is safe to do so */
public Map<String,Object> getUnusedConfigRaw() {
return unusedConfig;
}
public ConfigBag putAll(Map<?,?> addlConfig) {
if (addlConfig==null) return this;
for (Map.Entry<?,?> e: addlConfig.entrySet()) {
putAsStringKey(e.getKey(), e.getValue());
}
return this;
}
@SuppressWarnings("unchecked")
public <T> T put(ConfigKey<T> key, T value) {
return (T) putStringKey(key.getName(), value);
}
public <T> void putIfNotNull(ConfigKey<T> key, T value) {
if (value!=null) put(key, value);
}
/** as {@link #put(ConfigKey, Object)} but returning this ConfigBag for fluent-style coding */
public <T> ConfigBag configure(ConfigKey<T> key, T value) {
putStringKey(key.getName(), value);
return this;
}
protected void putAsStringKey(Object key, Object value) {
if (key instanceof HasConfigKey<?>) key = ((HasConfigKey<?>)key).getConfigKey();
if (key instanceof ConfigKey<?>) key = ((ConfigKey<?>)key).getName();
if (key instanceof String) {
putStringKey((String)key, value);
} else {
String message = (key == null ? "Invalid key 'null'" : "Invalid key type "+key.getClass().getCanonicalName()+" ("+key+")") +
"being used for configuration, ignoring";
log.debug(message, new Throwable("Source of "+message));
log.warn(message);
}
}
/** recommended to use {@link #put(ConfigKey, Object)} but there are times
* (e.g. when copying a map) where we want to put a string key directly
* @return */
public Object putStringKey(String key, Object value) {
if (sealed)
throw new IllegalStateException("Cannot insert "+key+"="+value+": this config bag has been sealed and is now immutable.");
boolean isNew = !config.containsKey(key);
boolean isUsed = !isNew && !unusedConfig.containsKey(key);
Object old = config.put(key, value);
if (!isUsed)
unusedConfig.put(key, value);
//if (!isNew && !isUsed) log.debug("updating config value which has already been used");
return old;
}
public boolean containsKey(HasConfigKey<?> key) {
return config.containsKey(key.getConfigKey());
}
public boolean containsKey(ConfigKey<?> key) {
return config.containsKey(key.getName());
}
public boolean containsKey(String key) {
return config.containsKey(key);
}
/** returns the value of this config key, falling back to its default (use containsKey to see whether it was contained);
* also marks it as having been used (use peek to prevent marking as used)
*/
public <T> T get(ConfigKey<T> key) {
return get(key, true);
}
/** gets a value from a string-valued key; ConfigKey is preferred, but this is useful in some contexts (e.g. setting from flags) */
public Object getStringKey(String key) {
return getStringKey(key, true);
}
/** like get, but without marking it as used */
public <T> T peek(ConfigKey<T> key) {
return get(key, false);
}
protected <T> T get(ConfigKey<T> key, boolean remove) {
// TODO for now, no evaluation -- closure content / smart (self-extracting) keys are NOT supported
// (need a clean way to inject that behaviour, as well as desired TypeCoercions)
Object value;
if (config.containsKey(key.getName()))
value = getStringKey(key.getName(), remove);
else
value = key.getDefaultValue();
return TypeCoercions.coerce(value, key.getType());
}
protected Object getStringKey(String key, boolean remove) {
if (config.containsKey(key)) {
if (remove) markUsed(key);
return config.get(key);
}
return null;
}
/** indicates that a string key in the config map has been accessed */
public void markUsed(String key) {
unusedConfig.remove(key);
}
public ConfigBag removeAll(ConfigKey<?> ...keys) {
for (ConfigKey<?> key: keys) remove(key);
return this;
}
public void remove(ConfigKey<?> key) {
remove(key.getName());
}
public ConfigBag removeAll(Iterable<String> keys) {
for (String key: keys) remove(key);
return this;
}
public void remove(String key) {
if (sealed)
throw new IllegalStateException("Cannot remove "+key+": this config bag has been sealed and is now immutable.");
config.remove(key);
unusedConfig.remove(key);
}
public ConfigBag copy(ConfigBag other) {
if (sealed)
throw new IllegalStateException("Cannot copy "+other+" to "+this+": this config bag has been sealed and is now immutable.");
putAll(other.getAllConfig());
markAll(Sets.difference(other.getAllConfig().keySet(), other.getUnusedConfig().keySet()));
setDescription(other.getDescription());
return this;
}
public ConfigBag markAll(Iterable<String> usedFlags) {
for (String flag: usedFlags)
markUsed(flag);
return this;
}
/** creates a new ConfigBag instance, empty and ready for population */
public static ConfigBag newInstance() {
return new ConfigBag();
}
/** creates a new ConfigBag instance which includes all of the supplied ConfigBag's values,
* but which tracks usage separately (already used values are marked as such,
* but uses in the original set will not be marked here, and vice versa) */
public static ConfigBag newInstanceCopying(final ConfigBag configBag) {
return new ConfigBag().copy(configBag).setDescription(configBag.getDescription());
}
/** creates a new ConfigBag instance which includes all of the supplied ConfigBag's values,
* plus an additional set of <ConfigKey,Object> or <String,Object> pairs
* <p>
* values from the original set which are used here will be marked as used in the original set
* (note: this applies even for values which are overridden and the overridden value is used);
* however subsequent uses in the original set will not be marked here
*/
public static ConfigBag newInstanceExtending(final ConfigBag configBag, Map<?,?> flags) {
return new ConfigBag() {
@Override
public void markUsed(String key) {
super.markUsed(key);
configBag.markUsed(key);
}
}.copy(configBag).putAll(flags);
}
public boolean isUnused(ConfigKey<?> key) {
return unusedConfig.containsKey(key.getName());
}
/** makes this config bag immutable; any attempts to change subsequently
* (apart from marking fields as used) will throw an exception
* <p>
* copies will be unsealed however
* <p>
* returns this for convenience (fluent usage) */
public ConfigBag seal() {
sealed = true;
config = getAllConfig();
return this;
}
} |
package hudson.util;
import hudson.FilePath;
import hudson.Util;
import static hudson.Util.fixEmpty;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* @author Kohsuke Kawaguchi
*/
public abstract class FormFieldValidator {
protected final StaplerRequest request;
protected final StaplerResponse response;
private final boolean isAdminOnly;
protected FormFieldValidator(StaplerRequest request, StaplerResponse response, boolean adminOnly) {
this.request = request;
this.response = response;
isAdminOnly = adminOnly;
}
/**
* Runs the validation code.
*/
public final void process() throws IOException, ServletException {
if(isAdminOnly && !Hudson.adminCheck(request,response))
return; // failed check
check();
}
protected abstract void check() throws IOException, ServletException;
/**
* Gets the parameter as a file.
*/
protected final File getFileParameter(String paramName) {
return new File(Util.fixNull(request.getParameter(paramName)));
}
/**
* Sends out an HTML fragment that indicates a success.
*/
public void ok() throws IOException, ServletException {
response.setContentType("text/html");
response.getWriter().print("<div/>");
}
/**
* Sends out a string error message that indicates an error.
*
* @param message
* Human readable message to be sent. <tt>error(null)</tt>
* can be used as <tt>ok()</tt>.
*/
public void error(String message) throws IOException, ServletException {
errorWithMarkup(message==null?null:Util.escape(message));
}
/**
* Sends out an HTML fragment that indicates an error.
*
* <p>
* This method must be used with care to avoid cross-site scripting
* attack.
*
* @param message
* Human readable message to be sent. <tt>error(null)</tt>
* can be used as <tt>ok()</tt>.
*/
public void errorWithMarkup(String message) throws IOException, ServletException {
if(message==null) {
ok();
} else {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print("<div class=error>"+message+"</div>");
}
}
/**
* Convenient base class for checking the validity of URLs
*/
public static abstract class URLCheck extends FormFieldValidator {
public URLCheck(StaplerRequest request, StaplerResponse response) {
// can be used to check the existence of any file in file system
// or other HTTP URLs inside firewall, so limit this to the admin.
super(request, response, true);
}
/**
* Opens the given URL and reads text content from it.
* This method honors Content-type header.
*/
protected BufferedReader open(URL url) throws IOException {
// use HTTP content type to find out the charset.
URLConnection con = url.openConnection();
if (con == null) { // XXX is this even permitted by URL.openConnection?
throw new IOException(url.toExternalForm());
}
return new BufferedReader(
new InputStreamReader(con.getInputStream(),getCharset(con)));
}
/**
* Finds the string literal from the given reader.
* @return
* true if found, false otherwise.
*/
protected boolean findText(BufferedReader in, String literal) throws IOException {
String line;
while((line=in.readLine())!=null)
if(line.indexOf(literal)!=-1)
return true;
return false;
}
/**
* Calls the {@link #error(String)} method with a reasonable error message.
* Use this method when the {@link #open(URL)} or {@link #findText(BufferedReader, String)} fails.
*
* @param url
* Pass in the URL that was connected. Used for error diagnosis.
*/
protected void handleIOException(String url, IOException e) throws IOException, ServletException {
// any invalid URL comes here
if(e.getMessage().equals(url))
// Sun JRE (and probably others too) often return just the URL in the error.
error("Unable to connect "+url);
else
error(e.getMessage());
}
/**
* Figures out the charset from the content-type header.
*/
private String getCharset(URLConnection con) {
for( String t : con.getContentType().split(";") ) {
t = t.trim().toLowerCase();
if(t.startsWith("charset="))
return t.substring(8);
}
// couldn't find it. HTML spec says default is US-ASCII,
// but UTF-8 is a better choice since
// (1) it's compatible with US-ASCII
// (2) a well-written web applications tend to use UTF-8
return "UTF-8";
}
}
/**
* Checks the file mask (specified in the 'value' query parameter) against
* the current workspace.
* @since 1.90.
*/
public static class WorkspaceFileMask extends FormFieldValidator {
public WorkspaceFileMask(StaplerRequest request, StaplerResponse response) {
super(request, response, false);
}
protected void check() throws IOException, ServletException {
String value = fixEmpty(request.getParameter("value"));
AbstractProject<?,?> p = Hudson.getInstance().getItemByFullName(request.getParameter("job"),AbstractProject.class);
if(value==null || p==null) {
ok(); // none entered yet, or something is seriously wrong
return;
}
try {
FilePath ws = p.getWorkspace();
if(!ws.exists()) {// no workspace. can't check
ok();
return;
}
error(ws.validateAntFileMask(value));
} catch (InterruptedException e) {
ok(); // coundn't check
}
}
}
/**
* Checks a valid directory name (specified in the 'value' query parameter) against
* the current workspace.
* @since 1.116.
*/
public static class WorkspaceDirectory extends FormFieldValidator {
public WorkspaceDirectory(StaplerRequest request, StaplerResponse response) {
super(request, response, false);
}
protected void check() throws IOException, ServletException {
String value = fixEmpty(request.getParameter("value"));
AbstractProject<?,?> p = Hudson.getInstance().getItemByFullName(request.getParameter("job"),AbstractProject.class);
if(value==null || p==null) {
ok(); // none entered yet, or something is seriously wrong
return;
}
if(value.contains("*")) {
// a common mistake is to use wildcard
error("Wildcard is not allowed here");
return;
}
try {
FilePath ws = p.getWorkspace();
if(!ws.exists()) {// no workspace. can't check
ok();
return;
}
if(ws.child(value).exists()) {
if(ws.child(value).isDirectory())
ok();
else
error(value+" is not a directory");
} else
error("No such directory: "+value);
} catch (InterruptedException e) {
ok(); // coundn't check
}
}
}
/**
* Checks a valid executable binary (specified in the 'value' query parameter)
*
* @since 1.124
*/
public static class Executable extends FormFieldValidator {
public Executable(StaplerRequest request, StaplerResponse response) {
super(request, response, true);
}
protected void check() throws IOException, ServletException {
String exe = fixEmpty(request.getParameter("value"));
if(exe==null) {
ok(); // nothing entered yet
return;
}
if(exe.indexOf(File.separatorChar)>=0) {
// this is full path
if(new File(exe).exists()) {
ok();
} else {
error("There's no such file: "+exe);
}
} else {
// can't really check
ok();
}
}
}
} |
package net.time4j.format;
import net.time4j.base.ResourceLoader;
import net.time4j.engine.BridgeChronology;
import net.time4j.engine.CalendarEra;
import net.time4j.engine.ChronoElement;
import net.time4j.engine.Chronology;
import net.time4j.format.internal.ExtendedPatterns;
import net.time4j.format.internal.FormatUtils;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.chrono.IsoEra;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.IsoFields;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* <p>Source for localized calendrical informations on enum basis like month
* or weekday names. </p>
*
* <p>This class is a facade for an underlying implementation of
* {@link TextProvider} which will be loaded as SPI-interface
* by help of a {@code ServiceLoader}. If no such SPI-interface can be
* found then this class will resort to the sources of JDK (usually
* as wrapper around {@code java.text.DateFormatSymbols}). </p>
*
* <p>Furthermore, an instance of {@code CalendarText} can also access
* the UTF-8 text resources in the folder "calendar" relative to
* the class path which are not based on JDK-defaults. In this case the
* presence of the i18n-module is required. In all ISO-systems the
* "iso8601_{locale}.properties"-files will override the
* JDK-defaults unless it is the ROOT-locale. Example: </p>
*
* <p>If you wish to use the name "Sonnabend" instead of the standard
* word "Samstag" in german locale (english: Saturday) then you can
* copy the existing file "calendar/iso8601_de.properties" from the
* content of "time4j-i18n-v{version}.jar"-file into a new directory
* with the same path. Then you can insert these lines extra (all seven entries
* must be inserted, not just the sixth line): </p>
*
* <pre>
* DAY_OF_WEEK(WIDE)_1=Montag
* DAY_OF_WEEK(WIDE)_2=Dienstag
* DAY_OF_WEEK(WIDE)_3=Mittwoch
* DAY_OF_WEEK(WIDE)_4=Donnerstag
* DAY_OF_WEEK(WIDE)_5=Freitag
* DAY_OF_WEEK(WIDE)_6=Sonnabend
* DAY_OF_WEEK(WIDE)_7=Sonntag
* </pre>
*
* <p>The general format of these lines is: </p>
*
* <pre>
* {element-name}({text-width}[|STANDALONE])_{one-based-integer}={text}
* </pre>
*
* <p>STANDALONE is optional. As element name in the context of ISO-8601
* following names are supported: </p>
*
* <ul><li>MONTH_OF_YEAR</li>
* <li>QUARTER_OF_YEAR</li>
* <li>DAY_OF_WEEK</li>
* <li>ERA</li>
* <li>AM_PM_OF_DAY</li></ul>
*
* @author Meno Hochschild
* @doctags.concurrency {immutable}
*/
/*[deutsch]
* <p>Quelle für lokalisierte kalendarische Informationen auf Enum-Basis
* wie zum Beispiel Monats- oder Wochentagsnamen. </p>
*
* <p>Diese Klasse ist eine Fassade für eine dahinterstehende
* {@link TextProvider}-Implementierung, die als SPI-Interface
* über einen {@code ServiceLoader}-Mechanismus geladen wird. Gibt es
* keine solche Implementierung, wird intern auf die Quellen des JDK mittels
* der Schnittstelle {@code java.text.DateFormatSymbols} ausgewichen. </p>
*
* <p>Darüberhinaus kann eine Instanz von {@code CalendarText} auch
* auf UTF-8-Textressourcen im Verzeichnis "calendar" innerhalb des
* Klassenpfads zugreifen, die nicht auf JDK-Vorgaben beruhen. In diesem Fall
* ist das i18n-Modul notwendig. Für alle ISO-Systeme gilt, daß die
* Einträge in den Dateien "iso8601_{locale}.properties" die
* JDK-Vorgaben überschreiben, sofern es nicht die ROOT-locale ist.
* Beispiel: </p>
*
* <p>Wenn der Name "Sonnabend" anstatt der Standardvorgabe
* "Samstag" in der deutschen Variante verwendet werden soll,
* dann kann die existierende Datei "calendar/iso8601_de.properties"
* vom Inhalt der Bibliotheksdatei "time4j-i18n-v{version].jar"
* in ein neues Verzeichnis mit dem gleichen Pfad kopiert werden. Danach
* können alle folgenden Zeilen extra eingefügt werden (nicht nur
* die sechste Zeile allein): </p>
*
* <pre>
* DAY_OF_WEEK(WIDE)_1=Montag
* DAY_OF_WEEK(WIDE)_2=Dienstag
* DAY_OF_WEEK(WIDE)_3=Mittwoch
* DAY_OF_WEEK(WIDE)_4=Donnerstag
* DAY_OF_WEEK(WIDE)_5=Freitag
* DAY_OF_WEEK(WIDE)_6=Sonnabend
* DAY_OF_WEEK(WIDE)_7=Sonntag
* </pre>
*
* <p>Das allgemeine Format dieser Zeilen ist: </p>
*
* <pre>
* {element-name}({text-width}[|STANDALONE])_{eins-basierter-integer}={text}
* </pre>
*
* <p>STANDALONE ist optional. Als Elementname im Kontext von ISO-8601 werden
* folgende Namen unterstützt: </p>
*
* <ul><li>MONTH_OF_YEAR</li>
* <li>QUARTER_OF_YEAR</li>
* <li>DAY_OF_WEEK</li>
* <li>ERA</li>
* <li>AM_PM_OF_DAY</li></ul>
*
* @author Meno Hochschild
* @doctags.concurrency {immutable}
*/
public final class CalendarText {
private static final Set<String> RTL;
static {
Set<String> lang = new HashSet<>();
lang.add("ar");
lang.add("dv");
lang.add("fa");
lang.add("ha");
lang.add("he");
lang.add("iw");
lang.add("ji");
lang.add("ps");
lang.add("ur");
lang.add("yi");
RTL = Collections.unmodifiableSet(lang);
}
private static final FormatPatternProvider FORMAT_PATTERN_PROVIDER;
static {
FormatPatternProvider provider = new FormatPatterns(null);
for (FormatPatternProvider fpp : ResourceLoader.getInstance().services(FormatPatternProvider.class)) {
provider = new FormatPatterns(fpp);
if (!fpp.getClass().getName().startsWith("net.time4j.")) {
break;
}
}
FORMAT_PATTERN_PROVIDER = provider;
}
/**
* <p>Default calendar type for all ISO systems. </p>
*/
/*[deutsch]
* <p>Standard-Kalendertyp für alle ISO-Systeme. </p>
*/
public static final String ISO_CALENDAR_TYPE = "iso8601";
private static final TextProvider JDK_PROVIDER = new JDKTextProvider();
private static final TextProvider ROOT_PROVIDER = new FallbackProvider();
private static final ConcurrentMap<String, CalendarText> CACHE = new ConcurrentHashMap<>();
// Name des Provider
private final String provider;
// Standardtexte
private final Map<TextWidth, Map<OutputContext, TextAccessor>> stdMonths;
private final Map<TextWidth, Map<OutputContext, TextAccessor>> leapMonths;
private final Map<TextWidth, Map<OutputContext, TextAccessor>> quarters;
private final Map<TextWidth, Map<OutputContext, TextAccessor>> weekdays;
private final Map<TextWidth, Map<OutputContext, TextAccessor>> meridiems;
private final Map<TextWidth, TextAccessor> eras;
private final Map<String, String> textForms;
private final String calendarType;
private final Locale locale;
private final MissingResourceException mre;
private CalendarText(
String calendarType,
Locale locale,
TextProvider p
) {
super();
this.provider = p.toString();
this.stdMonths =
Collections.unmodifiableMap(
getMonths(calendarType, locale, p, false));
Map<TextWidth, Map<OutputContext, TextAccessor>> tmpLeapMonths =
getMonths(calendarType, locale, p, true);
if (tmpLeapMonths == null) {
this.leapMonths = this.stdMonths;
} else {
this.leapMonths = Collections.unmodifiableMap(tmpLeapMonths);
}
Map<TextWidth, Map<OutputContext, TextAccessor>> qt =
new EnumMap<>(TextWidth.class);
for (TextWidth tw : TextWidth.values()) {
Map<OutputContext, TextAccessor> qo =
new EnumMap<>(OutputContext.class);
for (OutputContext oc : OutputContext.values()) {
qo.put(
oc,
new TextAccessor(p.quarters(calendarType, locale, tw, oc)));
}
qt.put(tw, qo);
}
this.quarters = Collections.unmodifiableMap(qt);
Map<TextWidth, Map<OutputContext, TextAccessor>> wt =
new EnumMap<>(TextWidth.class);
for (TextWidth tw : TextWidth.values()) {
Map<OutputContext, TextAccessor> wo =
new EnumMap<>(OutputContext.class);
for (OutputContext oc : OutputContext.values()) {
wo.put(
oc,
new TextAccessor(p.weekdays(calendarType, locale, tw, oc)));
}
wt.put(tw, wo);
}
this.weekdays = Collections.unmodifiableMap(wt);
Map<TextWidth, TextAccessor> et =
new EnumMap<>(TextWidth.class);
for (TextWidth tw : TextWidth.values()) {
et.put(
tw,
new TextAccessor(p.eras(calendarType, locale, tw)));
}
this.eras = Collections.unmodifiableMap(et);
Map<TextWidth, Map<OutputContext, TextAccessor>> mt =
new EnumMap<>(TextWidth.class);
for (TextWidth tw : TextWidth.values()) {
Map<OutputContext, TextAccessor> mo =
new EnumMap<>(OutputContext.class);
for (OutputContext oc : OutputContext.values()) {
mo.put(
oc,
new TextAccessor(p.meridiems(calendarType, locale, tw, oc)));
}
mt.put(tw, mo);
}
this.meridiems = Collections.unmodifiableMap(mt);
// Allgemeine Textformen als optionales Bundle vorbereiten
// Wichtig: Letzter Schritt im Konstruktor wg. Bundle-Cache
Map<String, String> map = new HashMap<>();
MissingResourceException tmpMre = null;
try {
ResourceBundle rb =
ResourceBundle.getBundle(
"names/" + calendarType,
locale,
p.getControl());
for (String key : rb.keySet()) {
map.put(key, rb.getString(key));
}
} catch (MissingResourceException ex) {
tmpMre = ex;
}
this.textForms = Collections.unmodifiableMap(map);
this.calendarType = calendarType;
this.locale = locale;
this.mre = tmpMre;
}
/**
* <p>Returns an instance of {@code CalendarText} for ISO calendar systems and given language. </p>
*
* @param locale language
* @return {@code CalendarText} object maybe cached
* @since 3.13/4.10
*/
/*[deutsch]
* <p>Gibt eine Instanz dieser Klasse für ISO-Kalendersysteme und die angegebene
* Sprache zurück. </p>
*
* @param locale language
* @return {@code CalendarText} object maybe cached
* @since 3.13/4.10
*/
public static CalendarText getIsoInstance(Locale locale) {
return getInstance(CalendarText.ISO_CALENDAR_TYPE, locale);
}
/**
* <p>Returns an instance of {@code CalendarText} for given chronology
* and language. </p>
*
* @param chronology chronology (with calendar system)
* @param locale language
* @return {@code CalendarText} object maybe cached
*/
/*[deutsch]
* <p>Gibt eine Instanz dieser Klasse für die angegebene Chronologie
* und Sprache zurück. </p>
*
* @param chronology chronology (with calendar system)
* @param locale language
* @return {@code CalendarText} object maybe cached
*/
public static CalendarText getInstance(
Chronology<?> chronology,
Locale locale
) {
return getInstance(extractCalendarType(chronology), locale);
}
/**
* <p>Returns an instance of {@code CalendarText} for given calendar type
* and language. </p>
*
* @param calendarType name of calendar system
* @param locale language
* @return {@code CalendarText} object maybe cached
* @see CalendarType
*/
/*[deutsch]
* <p>Gibt eine Instanz dieser Klasse für Kalendertyp
* und Sprache zurück. </p>
*
* @param calendarType name of calendar system
* @param locale language
* @return {@code CalendarText} object maybe cached
* @see CalendarType
*/
public static CalendarText getInstance(
String calendarType,
Locale locale
) {
if (calendarType == null) {
throw new NullPointerException("Missing calendar type.");
}
StringBuilder sb = new StringBuilder();
sb.append(calendarType);
sb.append(':');
sb.append(locale.getLanguage());
String country = FormatUtils.getRegion(locale);
if (!country.isEmpty()) {
sb.append('-');
sb.append(country);
}
String script = locale.getScript();
if (!script.isEmpty()) {
sb.append('
sb.append(script);
}
String key = sb.toString();
CalendarText instance = CACHE.get(key);
if (instance == null) {
TextProvider p = null;
if (locale.getLanguage().isEmpty() && calendarType.equals(ISO_CALENDAR_TYPE)) {
p = ROOT_PROVIDER;
} else {
// ServiceLoader-Mechanismus (Suche nach externen Providern)
for (TextProvider tmp : ResourceLoader.getInstance().services(TextProvider.class)) {
if (tmp.supportsCalendarType(calendarType) && tmp.supportsLanguage(locale)) {
p = tmp;
break;
}
}
// Java-Ressourcen
if (p == null) {
TextProvider tmp = JDK_PROVIDER;
if (tmp.supportsCalendarType(calendarType) && tmp.supportsLanguage(locale)) {
p = tmp;
}
if (p == null) {
p = ROOT_PROVIDER; // keine-ISO-Ressource
}
}
}
instance = new CalendarText(calendarType, locale, p);
CalendarText old = CACHE.putIfAbsent(key, instance);
if (old != null) {
instance = old;
}
}
return instance;
}
/**
* <p>Yields an {@code Accessor} for all standard months. </p>
*
* <p>The underlying list is sorted such that it will obey to the
* typical order of months in given calendar system. ISO-systems
* define January as first month and at whole 12 months. Other
* calendar systems can also define for example 13 months. The order
* of element value enums must be in agreement with the order of
* the text forms contained here. </p>
*
* <p>The default implementation handles SHORT as synonym for
* ABBREVIATED in the context of ISO-8601. </p>
*
* @param textWidth text width of displayed month name
* @param outputContext output context (stand-alone?)
* @return accessor for standard month names
* @see net.time4j.Month
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Standard-Monatsnamen. </p>
*
* <p>Die Liste ist so sortiert, daß die für das jeweilige
* Kalendersystem typische Reihenfolge der Monate eingehalten wird.
* ISO-Systeme definieren den Januar als den ersten Monat und insgesamt
* 12 Monate. Andere Kalendersysteme können auch 13 Monate definieren.
* Die Reihenfolge der Elementwert-Enums muß mit der Reihenfolge der
* hier enthaltenen Textformen übereinstimmen. </p>
*
* <p>Speziell für ISO-8601 behandelt die Standardimplementierung
* die Textbreiten SHORT und ABBREVIATED gleich. </p>
*
* @param textWidth text width of displayed month name
* @param outputContext output context (stand-alone?)
* @return accessor for standard month names
* @see net.time4j.Month
*/
public TextAccessor getStdMonths(
TextWidth textWidth,
OutputContext outputContext
) {
return this.getMonths(textWidth, outputContext, false);
}
/**
* <p>Yields an {@code Accessor} for all months if a leap month
* is relevant. </p>
*
* <p>Note: Leap months are defined in some calendar systems like the
* hebrew calendar ("Adar II") else there is no difference
* between standard and leap months escpecially not in ISO-8601. </p>
*
* @param textWidth text width of displayed month name
* @param outputContext output context (stand-alone?)
* @return accessor for month names
* @see net.time4j.Month
* @see #getStdMonths(TextWidth, OutputContext)
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Monatsnamen, wenn ein Schaltmonat relevant ist. </p>
*
* <p>Hinweis: Schaltmonate sind in einigen Kalendersystemen wie dem
* hebräischen Kalender definiert ("Adar II"). Ansonsten
* gibt es keinen Unterschied zwischen Standard- und Schaltmonaten,
* insbesondere nicht im ISO-8601-Standard. </p>
*
* @param textWidth text width of displayed month name
* @param outputContext output context (stand-alone?)
* @return accessor for month names
* @see net.time4j.Month
* @see #getStdMonths(TextWidth, OutputContext)
*/
public TextAccessor getLeapMonths(
TextWidth textWidth,
OutputContext outputContext
) {
return this.getMonths(textWidth, outputContext, true);
}
/**
* <p>Yields an {@code Accessor} for all quarter years. </p>
*
* <p>The underlying list of text forms is sorted in the same order
* as the enum {@code Quarter} and uses its ordinal index as list
* index. ISO systems define the range January-March as first quarter
* etc. and at whole four quarters per calendar year. </p>
*
* <p>The default implementation handles SHORT as synonym for
* ABBREVIATED in the context of ISO-8601. </p>
*
* @param textWidth text width of displayed quarter name
* @param outputContext output context (stand-alone?)
* @return accessor for quarter names
* @see net.time4j.Quarter
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Quartalsnamen. </p>
*
* <p>Die Liste ist wie das Enum {@code Quarter} sortiert und verwendet
* dessen Ordinalindex als Listenindex. ISO-Systeme definieren den
* Zeitraum Januar-März als erstes Quartal usw. und insgesamt
* 4 Quartale pro Kalenderjahr. </p>
*
* <p>Speziell für ISO-8601 behandelt die Standardimplementierung
* die Textbreiten SHORT und ABBREVIATED gleich. </p>
*
* @param textWidth text width of displayed quarter name
* @param outputContext output context (stand-alone?)
* @return accessor for quarter names
* @see net.time4j.Quarter
*/
public TextAccessor getQuarters(
TextWidth textWidth,
OutputContext outputContext
) {
return this.quarters.get(textWidth).get(outputContext);
}
/**
* <p>Yields an {@code Accessor} for all weekday names. </p>
*
* <p>The underlying list of text forms is sorted such that the
* typical order of weekdays is used in given calendar system.
* ISO systems define Monday as first day of week and at whole
* 7 weekdays. This order is also valid for US in the context of
* this class although in US Sunday is considered as start of a
* week. The order element value enums must be in agreement with
* the order of text forms contained here. </p>
*
* @param textWidth text width of displayed weekday name
* @param outputContext output context (stand-alone?)
* @return accessor for weekday names
* @see net.time4j.Weekday
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Wochentagsnamen. </p>
*
* <p>Die Liste ist so sortiert, daß die für das jeweilige
* Kalendersystem typische Reihenfolge der Wochentage eingehalten wird.
* ISO-Systeme definieren den Montag als den ersten Wochentag und insgesamt
* 7 Wochentage. Diese Sortierung gilt im Kontext dieser Klasse auch
* für die USA, in denen der Sonntag als erster Tag der Woche gilt.
* Die Reihenfolge der Elementwert-Enums muß mit der Reihenfolge
* der hier enthaltenen Textformen übereinstimmen. </p>
*
* @param textWidth text width of displayed weekday name
* @param outputContext output context (stand-alone?)
* @return accessor for weekday names
* @see net.time4j.Weekday
*/
public TextAccessor getWeekdays(
TextWidth textWidth,
OutputContext outputContext
) {
return this.weekdays.get(textWidth).get(outputContext);
}
/**
* <p>Yields an {@code Accessor} for all era names. </p>
*
* <p>The underlying list of text forms is sorted such that the
* typical order of eras is used in given calendar system. ISO systems
* define era names based on their historical extensions (eras of
* gregorian/historic calendar) because they themselves have no internal
* concept of eras. The order of element value enums must be in agreement
* with the text forms contained here. If an era is not defined on enum
* basis then the format API will not evaluate this class but the
* {@code CalendarSystem} to get the right text forms. </p>
*
* @param textWidth text width of displayed era name
* @return accessor for era names
* @see net.time4j.engine.CalendarSystem#getEras()
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Äranamen. </p>
*
* <p>Die Liste ist so sortiert, daß die für das jeweilige
* Kalendersystem typische Reihenfolge der Äranamen eingehalten wird.
* ISO-Systeme definieren Äranamen basierend auf ihren historischen
* Erweiterungen, da sie selbst keine kennen (also die des gregorianischen
* historischen Kalenders). Die Reihenfolge der Elementwert-Enums muß
* mit der Reihenfolge der hier enthaltenen Textformen übereinstimmen.
* Wenn eine Ära nicht auf Enum-Basis definiert ist, wertet das
* Format-API nicht diese Klasse, sondern das {@code CalendarSystem} zur
* Bestimmung der Textformen aus. </p>
*
* @param textWidth text width of displayed era name
* @return accessor for era names
* @see net.time4j.engine.CalendarSystem#getEras()
*/
public TextAccessor getEras(TextWidth textWidth) {
return this.eras.get(textWidth);
}
/**
* <p>Yields an {@code Accessor} for all am/pm-names. </p>
*
* <p>The underlying list of text forms is sorted in AM-PM-order.
* The order of element value enums must be the same. </p>
*
* @param textWidth text width of displayed AM/PM name
* @return accessor for AM/PM names
* @see #getMeridiems(TextWidth, OutputContext)
* @deprecated Use {@code getMeridiems(textWidth, OutputContext.FORMAT)}
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Tagesabschnittsnamen. </p>
*
* <p>Die Liste ist in AM/PM-Reihenfolge sortiert. Die Reihenfolge der
* Elementwert-Enums muß mit der Reihenfolge der hier enthaltenen
* Textformen übereinstimmen. </p>
*
* @param textWidth text width of displayed AM/PM name
* @return accessor for AM/PM names
* @see #getMeridiems(TextWidth, OutputContext)
* @deprecated Use {@code getMeridiems(textWidth, OutputContext.FORMAT)}
*/
@Deprecated
public TextAccessor getMeridiems(TextWidth textWidth) {
return this.getMeridiems(textWidth, OutputContext.FORMAT);
}
/**
* <p>Yields an {@code Accessor} for all am/pm-names. </p>
*
* <p>The underlying list of text forms is sorted in AM-PM-order.
* The order of element value enums must be the same. </p>
*
* @param textWidth text width of displayed AM/PM name
* @param outputContext output context (stand-alone?)
* @return accessor for AM/PM names
* @see net.time4j.Meridiem
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle
* Tagesabschnittsnamen. </p>
*
* <p>Die Liste ist in AM/PM-Reihenfolge sortiert. Die Reihenfolge der
* Elementwert-Enums muß mit der Reihenfolge der hier enthaltenen
* Textformen übereinstimmen. </p>
*
* @param textWidth text width of displayed AM/PM name
* @param outputContext output context (stand-alone?)
* @return accessor for AM/PM names
* @see net.time4j.Meridiem
*/
public TextAccessor getMeridiems(
TextWidth textWidth,
OutputContext outputContext
) {
return this.meridiems.get(textWidth).get(outputContext);
}
/**
* <p>Yields all text forms in raw format. </p>
*
* @return unmodifiable map of all text forms
* @since 3.12/4.9
*/
/*[deutsch]
* <p>Liefert alle Textformen im Rohformat. </p>
*
* @return unmodifiable map of all text forms
* @since 3.12/4.9
*/
public Map<String, String> getTextForms() {
return this.textForms;
}
/**
* <p>Yields an {@code Accessor} for all text forms of given
* chronological element. </p>
*
* <p>Text forms might exist in different variations. In case of
* enum-based variants the name of the enum (example "WIDE" in
* the variant {@code TextWidth}) is to be used, in case of boolean-based
* variants the literals "true" and "false" are to be
* used. </p>
*
* <p>While the methods {@code getStdMonths()}, {@code getWeekdays()}
* etc. are mainly based on JDK-defaults, this method is escpecially
* designed for querying chronological texts which are not contained in
* JDK. Text forms will be stored internally in the resource folder
* "calendar" relative to class path in properties-files using
* UTF-8 encoding. The basic name of these resources is the calendar type.
* The combination of element name and optionally variants in the form
* "(variant1|variant2|...|variantN)" and the underscore and
* finally a numerical suffix with base 1 (for era elements base 0) serves
* as resource text key. If there is no entry for given key in the resources
* then this method will simply yield the name of enum value associated
* with given element value. </p>
*
* <p>As example, the search for abbreviated historic era {@code HistoricEra.AD} of alternative form
* looks up keys in this order (using E if there is an entry "useShortKeys=true"): </p>
*
* <ol>
* <li>value of "E(a|alt)_1"</li>
* <li>value of "E(a)_1"</li>
* <li>value of "E_1"</li>
* <li><i>fallback=>AD</i></li>
* </ol>
*
* @param <V> generic type of element values based on enums
* @param element element text forms are searched for
* @param variants text form variants (optional)
* @return accessor for any text forms
* @throws MissingResourceException if for given calendar type there are no text resource files
*/
/*[deutsch]
* <p>Liefert einen {@code Accessor} für alle Textformen des
* angegebenen chronologischen Elements. </p>
*
* <p>Textformen können unter Umständen in verschiedenen
* Varianten vorkommen. Als Variantenbezug dient bei enum-Varianten
* der Name der Enum-Ausprägung (Beispiel "WIDE" in
* der Variante {@code TextWidth}), im boolean-Fall sind die Literale
* "true" und "false" zu verwenden. </p>
*
* <p>Während {@code getStdMonths()}, {@code getWeekdays()} etc. in
* erster Linie auf JDK-Vorgaben beruhen, dient diese Methode dazu,
* chronologiespezifische Texte zu beschaffen, die nicht im JDK enthalten
* sind. Textformen werden intern im Verzeichnis "calendar"
* des Klassenpfads mit Hilfe von properties-Dateien im UTF-8-Format
* gespeichert. Der Basisname dieser Ressourcen ist der Kalendertyp. Als
* Textschluuml;ssel dient die Kombination aus Elementname, optional
* Varianten in der Form "(variant1|variant2|...|variantN)",
* dem Unterstrich und schließlich einem numerischen Suffix mit
* Basis 1 (für Ära-Elemente Basis 0). Wird in den Ressourcen zum
* angegebenen Schlüssel kein Eintrag gefunden, liefert diese Methode
* einfach den Namen des mit dem Element assoziierten enum-Werts. </p>
*
* <p>Zum Beispiel versucht die Suche nach der abgekürzten Form der historischen Ära
* {@code HistoricEra.AD} in der alternativen Form Schlüssel in dieser Reihenfolge zu finden
* (mit dem Präfix E, falls es einen Eintrag "useShortKeys=true" gibt): </p>
*
* <ol>
* <li>value of "E(a|alt)_1"</li>
* <li>value of "E(a)_1"</li>
* <li>value of "E_1"</li>
* <li><i>fallback=>AD</i></li>
* </ol>
*
* @param <V> generic type of element values based on enums
* @param element element text forms are searched for
* @param variants text form variants (optional)
* @return accessor for any text forms
* @throws MissingResourceException if for given calendar type there are no text resource files
*/
public <V extends Enum<V>> TextAccessor getTextForms(
ChronoElement<V> element,
String... variants
) {
return this.getTextForms(element.name(), element.getType(), variants);
}
/**
* <p>See {@link #getTextForms(ChronoElement, String...)}. </p>
*
* @param <V> generic type of element values based on enums
* @param name name of text entries in resource file
* @param type type of enum values
* @param variants text form variants (optional)
* @return accessor for any text forms
* @throws MissingResourceException if for given calendar type there are no text resource files
* @since 3.11/4.8
*/
/*[deutsch]
* <p>Siehe {@link #getTextForms(ChronoElement, String...)}. </p>
*
* @param <V> generic type of element values based on enums
* @param name name of text entries in resource file
* @param type type of enum values
* @param variants text form variants (optional)
* @return accessor for any text forms
* @throws MissingResourceException if for given calendar type there are no text resource files
* @since 3.11/4.8
*/
public <V extends Enum<V>> TextAccessor getTextForms(
String name,
Class<V> type,
String... variants
) {
if (this.mre != null) {
throw new MissingResourceException(
this.mre.getMessage(),
this.mre.getClassName(),
this.mre.getKey());
}
V[] enums = type.getEnumConstants();
int len = enums.length;
String[] tfs = new String[len];
String prefix = this.getKeyPrefix(name);
int baseIndex = (CalendarEra.class.isAssignableFrom(type) ? 0 : 1);
for (int i = 0; i < len; i++) {
int step = 0;
String raw = getKeyStart(prefix, 0, variants);
String key = null;
// sukzessives Reduzieren der Varianten, wenn nicht gefunden
while (raw != null) {
String test = toKey(raw, i, baseIndex);
if (this.textForms.containsKey(test)) {
key = test;
break;
}
step++;
raw = getKeyStart(prefix, step, variants);
}
if (key == null) {
tfs[i] = enums[i].name(); // fallback
} else {
tfs[i] = this.textForms.get(key);
}
}
return new TextAccessor(tfs);
}
/**
* <p>Yields the localized GMT-prefix which is used in the
* <i>localized GMT format</i> of CLDR. </p>
*
* @param locale language and country configuration
* @return localized GMT-String defaults to "GMT"
* @deprecated Use {@link net.time4j.tz.ZonalOffset#getStdFormatPattern(Locale)} instead
*/
@Deprecated
public static String getGMTPrefix(Locale locale) {
return "GMT";
}
/**
* <p>Yields the best available format patterns. </p>
*
* @return format pattern provider
* @since 3.10/4.7
* @deprecated Use one of methods {@code patternForXYZ} instead
*/
/*[deutsch]
* <p>Liefert die am besten verfügbaren Formatmuster. </p>
*
* @return format pattern provider
* @since 3.10/4.7
* @deprecated Use one of methods {@code patternForXYZ} instead
*/
@Deprecated
public static FormatPatternProvider getFormatPatterns() {
return FORMAT_PATTERN_PROVIDER;
}
/**
* <p>Yields a format pattern without any timezone symbols for plain timestamps. </p>
*
* @param dateMode display mode of date part
* @param timeMode display mode of time part
* @param locale language and country setting
* @return format pattern for plain timestamps without timezone symbols
* @since 3.10/4.7
* @deprecated Use {@code patternForTimestamp} instead
*/
/*[deutsch]
* <p>Liefert ein Formatmuster ohne Zeitzonensymbole für reine Zeitstempel. </p>
*
* @param dateMode display mode of date part
* @param timeMode display mode of time part
* @param locale language and country setting
* @return format pattern for plain timestamps without timezone symbols
* @since 3.10/4.7
* @deprecated Use {@code patternForTimestamp} instead
*/
@Deprecated
public static String getTimestampPattern(
DisplayMode dateMode,
DisplayMode timeMode,
Locale locale
) {
String pattern = FORMAT_PATTERN_PROVIDER.getDateTimePattern(dateMode, timeMode, locale);
return removeZones(pattern);
}
/**
* <p>Returns the localized date pattern suitable for formatting of objects
* of type {@code PlainDate}. </p>
*
* @param mode display mode
* @param locale language and country setting
* @return localized date pattern
* @see net.time4j.PlainDate
* @since 3.13/4.10
*/
/*[deutsch]
* <p>Liefert das lokalisierte Datumsmuster geeignet für
* die Formatierung von Instanzen des Typs{@code PlainDate}. </p>
*
* @param mode display mode
* @param locale language and country setting
* @return localized date pattern
* @see net.time4j.PlainDate
* @since 3.13/4.10
*/
public static String patternForDate(
DisplayMode mode,
Locale locale
) {
return FORMAT_PATTERN_PROVIDER.getDatePattern(mode, locale);
}
/**
* <p>Returns the localized time pattern suitable for formatting of objects
* of type {@code PlainTime}. </p>
*
* @param mode display mode
* @param locale language and country setting
* @return localized time pattern
* @see net.time4j.PlainTime
* @since 3.13/4.10
*/
/*[deutsch]
* <p>Liefert das lokalisierte Uhrzeitmuster geeignet für die
* Formatierung von Instanzen des Typs {@code PlainTime}. </p>
*
* @param mode display mode
* @param locale language and country setting
* @return localized time pattern
* @see net.time4j.PlainTime
* @since 3.13/4.10
*/
public static String patternForTime(
DisplayMode mode,
Locale locale
) {
return FORMAT_PATTERN_PROVIDER.getTimePattern(mode, locale);
}
/**
* <p>Yields a format pattern without any timezone symbols for plain timestamps. </p>
*
* @param dateMode display mode of date part
* @param timeMode display mode of time part
* @param locale language and country setting
* @return format pattern for plain timestamps without timezone symbols
* @see net.time4j.PlainTimestamp
* @since 3.13/4.10
*/
/*[deutsch]
* <p>Liefert ein Formatmuster ohne Zeitzonensymbole für reine Zeitstempel. </p>
*
* @param dateMode display mode of date part
* @param timeMode display mode of time part
* @param locale language and country setting
* @return format pattern for plain timestamps without timezone symbols
* @see net.time4j.PlainTimestamp
* @since 3.13/4.10
*/
public static String patternForTimestamp(
DisplayMode dateMode,
DisplayMode timeMode,
Locale locale
) {
String pattern = FORMAT_PATTERN_PROVIDER.getDateTimePattern(dateMode, timeMode, locale);
return removeZones(pattern);
}
/**
* <p>Returns the localized date-time pattern suitable for formatting of objects
* of type {@code Moment}. </p>
*
* @param dateMode display mode of date part
* @param timeMode display mode of time part
* @param locale language and country setting
* @return localized date-time pattern including timezone symbols
* @see net.time4j.Moment
* @since 3.13/4.10
*/
/*[deutsch]
* <p>Liefert das lokalisierte Datums- und Uhrzeitmuster geeignet
* für die Formatierung von Instanzen des Typs {@code Moment}. </p>
*
* @param dateMode display mode of date part
* @param timeMode display mode of time part
* @param locale language and country setting
* @return localized date-time pattern including timezone symbols
* @see net.time4j.Moment
* @since 3.13/4.10
*/
public static String patternForMoment(
DisplayMode dateMode,
DisplayMode timeMode,
Locale locale
) {
return FORMAT_PATTERN_PROVIDER.getDateTimePattern(dateMode, timeMode, locale);
}
/**
* <p>Returns the localized interval pattern. </p>
*
* <p>Expressions of the form "{0}" will be interpreted as the start boundary format
* and expressions of the form "{1}" will be interpreted as the end boundary format.
* All other chars of the pattern will be treated as literals. </p>
*
* @param locale language and country setting
* @return localized interval pattern
* @since 3.13/4.10
*/
/*[deutsch]
* <p>Liefert das lokalisierte Intervallmuster. </p>
*
* <p>Die Ausdrücke "{0}" und "{1}" werden als Formathalter für die
* Start- und End-Intervallgrenzen interpretiert. Alle anderen Zeichen des Musters werden wie
* Literale behandelt. </p>
*
* @param locale language and country setting
* @return localized interval pattern
* @since 3.13/4.10
*/
public static String patternForInterval(Locale locale) {
return FORMAT_PATTERN_PROVIDER.getIntervalPattern(locale);
}
/**
* <p>Yields the name of the internal {@link TextProvider} in conjunction with the configuring locale. </p>
*/
/*[deutsch]
* <p>Liefert den Namen des internen {@link TextProvider} in Verbindung mit der konfigurierenden Sprache. </p>
*/
@Override
public String toString() {
return this.provider + "(" + this.calendarType + "/" + this.locale + ")";
}
/**
* <p>Clears the internal cache. </p>
*
* <p>This method should be called if the internal text resources have
* changed and must be reloaded with a suitable {@code ClassLoader}. </p>
*/
/*[deutsch]
* <p>Löscht den internen Cache. </p>
*
* <p>Diese Methode sollte aufgerufen werden, wenn sich die internen
* Text-Ressourcen geändert haben und mit einem geeigneten
* {@code ClassLoader} neu geladen werden müssen. </p>
*/
public static void clearCache() {
CACHE.clear();
}
/**
* <p>Determines if given language is written in right-to-left direction. </p>
*
* @param locale language to be checked
* @return {@code true} if right-to-left else {@code false}
* @since 3.25/4.21
*/
/*[deutsch]
* <p>Ermittelt, ob die angegebene Sprache von rechts nach links geschrieben wird. </p>
*
* @param locale language to be checked
* @return {@code true} if right-to-left else {@code false}
* @since 3.25/4.21
*/
public static boolean isRTL(Locale locale) {
return RTL.contains(locale.getLanguage());
}
/**
* <p>Extrahiert den Kalendertyp aus der angegebenen Chronologie. </p>
*
* <p>Kann kein Kalendertyp ermittelt werden, wird {@code ISO_CALENDAR_TYPE}
* als Ausweichoption zurückgegeben. </p>
*
* @param chronology chronology to be evaluated
* @return calendar type, never {@code null}
*/
static String extractCalendarType(Chronology<?> chronology) {
while (chronology instanceof BridgeChronology) {
chronology = chronology.preparser();
}
CalendarType ft = chronology.getChronoType().getAnnotation(CalendarType.class);
return ((ft == null) ? ISO_CALENDAR_TYPE : ft.value());
}
private TextAccessor getMonths(
TextWidth textWidth,
OutputContext outputContext,
boolean leapForm
) {
if (leapForm) {
return this.leapMonths.get(textWidth).get(outputContext);
} else {
return this.stdMonths.get(textWidth).get(outputContext);
}
}
private static Map<TextWidth, Map<OutputContext, TextAccessor>> getMonths(
String calendarType,
Locale locale,
TextProvider p,
boolean leapForm
) {
Map<TextWidth, Map<OutputContext, TextAccessor>> mt = new EnumMap<>(TextWidth.class);
boolean usesDifferentLeapForm = false;
for (TextWidth tw : TextWidth.values()) {
Map<OutputContext, TextAccessor> mo =
new EnumMap<>(OutputContext.class);
for (OutputContext oc : OutputContext.values()) {
String[] ls =
p.months(calendarType, locale, tw, oc, leapForm);
if (leapForm && !usesDifferentLeapForm) {
String[] std =
p.months(calendarType, locale, tw, oc, false);
usesDifferentLeapForm = !Arrays.equals(std, ls);
}
mo.put(oc, new TextAccessor(ls));
}
mt.put(tw, mo);
}
return ((!leapForm || usesDifferentLeapForm) ? mt : null);
}
private String getKeyPrefix(String elementName) {
if (
this.textForms.containsKey("useShortKeys")
&& "true".equals(this.textForms.get("useShortKeys"))
) {
if (
(elementName.equals("MONTH_OF_YEAR") || elementName.equals("DAY_OF_WEEK")
|| elementName.equals("QUARTER_OF_YEAR") || elementName.equals("ERA"))
) {
return elementName.substring(0, 1);
} else if (elementName.equals("EVANGELIST")) { // special case: Ethiopian calendar
return "EV";
} else if (elementName.equals("SANSCULOTTIDES")) { // special case: French revolutionary calendar
return "S";
} else if (elementName.equals("DAY_OF_DECADE")) { // special case: French revolutionary calendar
return "D";
}
}
return elementName;
}
private static String getKeyStart(
String elementName,
int step,
String... variants
) {
if ((variants != null) && (variants.length > 0)) {
if (variants.length < step) {
return null;
}
StringBuilder sb = new StringBuilder(elementName);
boolean first = true;
for (int v = 0; v < variants.length - step; v++) {
if (first) {
sb.append('(');
first = false;
} else {
sb.append('|');
}
sb.append(variants[v]);
}
if (!first) {
sb.append(')');
}
return sb.toString();
} else {
return (step > 0 ? null : elementName);
}
}
private static String toKey(
String raw,
int counter,
int baseIndex
) {
StringBuilder keyBuilder = new StringBuilder(raw);
keyBuilder.append('_');
keyBuilder.append(counter + baseIndex);
return keyBuilder.toString();
}
// strip off any timezone symbols in clock time patterns,
// used by wrappers of FormatPatternProvider-objects
private static String removeZones(String pattern) {
boolean literal = false;
StringBuilder sb = new StringBuilder();
for (int i = 0, n = pattern.length(); i < n; i++) {
char c = pattern.charAt(i);
if (c == '\'') {
if (i + 1 < n && pattern.charAt(i + 1) == '\'') {
sb.append(c);
i++;
} else {
literal = !literal;
}
sb.append(c);
} else if (literal) {
sb.append(c);
} else if (c != 'z' && c != 'Z' && c != 'v' && c != 'V' && c != 'x' && c != 'X') {
sb.append(c);
}
}
for (int j = 0; j < sb.length(); j++) {
char c = sb.charAt(j);
if (c == ' ' && j + 1 < sb.length() && sb.charAt(j + 1) == ' ') {
sb.deleteCharAt(j);
j
} else if (c == '[' || c == ']' || c == '(' || c == ')') { // check locales es, fa, ps, uz
sb.deleteCharAt(j);
j
}
}
String result = sb.toString().trim();
if (result.endsWith(" '")) { // special case for de, fr_BE
result = result.substring(0, result.length() - 2) + "'";
} else if (result.endsWith(",")) { // special case for hy
result = result.substring(0, result.length() - 1);
}
return result;
}
private static class JDKTextProvider
implements TextProvider {
@Override
public boolean supportsCalendarType(String calendarType) {
return ISO_CALENDAR_TYPE.equals(calendarType);
}
@Override
public boolean supportsLanguage(Locale language) {
String lang = language.getLanguage();
for (Locale test : DateFormatSymbols.getAvailableLocales()) {
if (test.getLanguage().equals(lang)) {
return true;
}
}
return false;
}
@Override
public String[] getSupportedCalendarTypes() {
return new String[] { ISO_CALENDAR_TYPE };
}
@Override
public Locale[] getAvailableLocales() {
return DateFormatSymbols.getAvailableLocales();
}
@Override
public String[] months(
String calendarType,
Locale locale,
TextWidth tw,
OutputContext oc,
boolean leapForm
) {
TextStyle style = getStyle(tw, oc);
String[] months = new String[12];
int i = 0;
for (Month month : Month.values()) {
months[i] = month.getDisplayName(style, locale);
i++;
}
return months;
}
@Override
public String[] quarters(
String calendarType,
Locale locale,
TextWidth tw,
OutputContext oc
) {
TextStyle style = getStyle(tw, oc);
String[] quarters = new String[4];
for (int i = 0; i < 4; i++) {
LocalDate date = LocalDate.of(1970, i * 3 + 1, 1);
quarters[i] =
new DateTimeFormatterBuilder()
.appendText(IsoFields.QUARTER_OF_YEAR, style)
.toFormatter(locale)
.format(date);
}
return quarters;
}
@Override
public String[] weekdays(
String calendarType,
Locale locale,
TextWidth tw,
OutputContext oc
) {
TextStyle style = getStyle(tw, oc);
String[] weekdays = new String[7];
int i = 0;
for (DayOfWeek dow : DayOfWeek.values()) {
weekdays[i] = dow.getDisplayName(style, locale);
i++;
}
return weekdays;
}
@Override
public String[] eras(
String calendarType,
Locale locale,
TextWidth textWidth
) {
TextStyle style = getStyle(textWidth, OutputContext.FORMAT);
String[] eras = new String[2];
int i = 0;
for (IsoEra era : IsoEra.values()) {
eras[i] = era.getDisplayName(style, locale);
i++;
}
return eras;
}
@Override
public String[] meridiems(
String calendarType,
Locale locale,
TextWidth textWidth
) {
TextStyle style = getStyle(textWidth, OutputContext.FORMAT);
String[] meridiems = new String[2];
for (int i = 0; i < 2; i++) {
LocalTime time = LocalTime.of(i * 12, 0);
meridiems[i] =
new DateTimeFormatterBuilder()
.appendText(ChronoField.AMPM_OF_DAY, style)
.toFormatter(locale)
.format(time);
}
return meridiems;
}
@Override
public ResourceBundle.Control getControl() {
return ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_DEFAULT);
}
@Override
public String toString() {
return "JDKTextProvider";
}
private static TextStyle getStyle(
TextWidth tw,
OutputContext oc
) {
boolean standalone = (oc == OutputContext.STANDALONE);
switch (tw) {
case WIDE:
return (standalone ? TextStyle.FULL_STANDALONE : TextStyle.FULL);
case ABBREVIATED:
case SHORT:
return (standalone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT);
case NARROW:
return (standalone ? TextStyle.NARROW_STANDALONE : TextStyle.NARROW);
default:
throw new UnsupportedOperationException(tw.name());
}
}
}
private static class FallbackProvider
implements TextProvider {
@Override
public boolean supportsCalendarType(String calendarType) {
return true;
}
@Override
public boolean supportsLanguage(Locale language) {
return true;
}
@Override
public String[] getSupportedCalendarTypes() {
throw new UnsupportedOperationException("Never called.");
}
@Override
public Locale[] getAvailableLocales() {
throw new UnsupportedOperationException("Never called.");
}
@Override
public String[] months(
String calendarType,
Locale locale,
TextWidth textWidth,
OutputContext outputContext,
boolean leapForm
) {
if (textWidth == TextWidth.WIDE) {
return new String[] {
"01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12", "13"};
} else {
return new String[] {
"1", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "11", "12", "13"};
}
}
@Override
public String[] quarters(
String calendarType,
Locale locale,
TextWidth textWidth,
OutputContext outputContext
) {
if (textWidth == TextWidth.NARROW) {
return new String[] {"1", "2", "3", "4"};
} else {
return new String[] {"Q1", "Q2", "Q3", "Q4"};
}
}
@Override
public String[] weekdays(
String calendarType,
Locale locale,
TextWidth textWidth,
OutputContext outputContext
) {
return new String[] {"1", "2", "3", "4", "5", "6", "7"};
}
@Override
public String[] eras(
String calendarType,
Locale locale,
TextWidth textWidth
) {
if (textWidth == TextWidth.NARROW) {
return new String[] {"B", "A"};
} else {
return new String[] {"BC", "AD"};
}
}
@Override
public String[] meridiems(
String calendarType,
Locale locale,
TextWidth textWidth
) {
if (textWidth == TextWidth.NARROW) {
return new String[] {"A", "P"};
} else {
return new String[] {"AM", "PM"};
}
}
@Override
public ResourceBundle.Control getControl() {
return ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_DEFAULT);
}
@Override
public String toString() {
return "FallbackProvider";
}
}
private static class FormatPatterns
implements FormatPatternProvider {
private final FormatPatternProvider delegate;
FormatPatterns(FormatPatternProvider delegate) {
super();
this.delegate = delegate;
}
@Override
public String getDatePattern(
DisplayMode mode,
Locale locale
) {
if (this.delegate == null) {
int style = getFormatStyle(mode);
DateFormat df = DateFormat.getDateInstance(style, locale);
return getFormatPattern(df);
}
return this.delegate.getDatePattern(mode, locale);
}
@Override
public String getTimePattern(
DisplayMode mode,
Locale locale
) {
String pattern;
if (this.delegate == null) {
int style = getFormatStyle(mode);
DateFormat df = DateFormat.getTimeInstance(style, locale);
pattern = getFormatPattern(df);
} else if (this.delegate instanceof ExtendedPatterns) {
pattern = ExtendedPatterns.class.cast(this.delegate).getTimePattern(mode, locale, true);
} else {
pattern = this.delegate.getTimePattern(mode, locale);
}
return removeZones(pattern);
}
@Override
public String getDateTimePattern(
DisplayMode dateMode,
DisplayMode timeMode,
Locale locale
) {
if (this.delegate == null) {
int dateStyle = getFormatStyle(dateMode);
int timeStyle = getFormatStyle(timeMode);
DateFormat df = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
return getFormatPattern(df);
}
String time = this.delegate.getTimePattern(timeMode, locale);
String date = this.delegate.getDatePattern(dateMode, locale);
String pattern = this.delegate.getDateTimePattern(dateMode, timeMode, locale);
return pattern.replace("{1}", date).replace("{0}", time);
}
@Override
public String getIntervalPattern(Locale locale) {
if (this.delegate == null) {
if (locale.getLanguage().isEmpty() && FormatUtils.getRegion(locale).isEmpty()) {
return "{0}/{1}"; // ISO-8601-style
// } else if (isRTL(locale)) {
// return "{0} - {1}"; // based on analysis of CLDR-data
} else {
return "{0} - {1}"; // default
}
}
return this.delegate.getIntervalPattern(locale);
}
private static int getFormatStyle(DisplayMode mode) {
switch (mode) {
case FULL:
return DateFormat.FULL;
case LONG:
return DateFormat.LONG;
case MEDIUM:
return DateFormat.MEDIUM;
case SHORT:
return DateFormat.SHORT;
default:
throw new UnsupportedOperationException("Unknown: " + mode);
}
}
private static String getFormatPattern(DateFormat df) {
if (df instanceof SimpleDateFormat) {
return SimpleDateFormat.class.cast(df).toPattern();
}
throw new IllegalStateException("Cannot retrieve format pattern: " + df);
}
}
} |
package bzh.plealog.bioinfo.api.filter;
import java.util.Enumeration;
/**
* This interface defines a filterable data model. It aims at being the
* gateway between the filter engine and the filter UI.
*
* @author Patrick G. Durand
*/
public interface BDataAccessors extends BOperatorAccessors{
// Accessors used elsewhere should be declared here as static String.
// Never modify the strings; this is a design drawback issue: those
// strings are used in the Filter IO system. If you modify the strings,
// then not only the IO system will fail to reload filters from their
// XML serialization, the filtering engine will fail too!
public static final String ACC_HitAccession = "Hit Accession";
public static final String ACC_HitRank = "Hit rank";
public static final String ACC_HitHspCount = "Number of HSPs";
public static final String ACC_HitDefinition = "Hit definition";
public static final String ACC_HitIdentifier = "Hit identifier";
public static final String ACC_HitLength = "Hit Length";
public static final String ACC_HitQueryCoverage = "Hit/Global Query Coverage";
public static final String ACC_HitHitCoverage = "Hit/Global Hit Coverage";
public static final String ACC_HspRank = "HSP rank";
public static final String ACC_HspQueryCoverage = "HSP/Local Query Coverage";
public static final String ACC_HspHitCoverage = "HSP/Local Hit Coverage";
public static final String ACC_BitScore = "HSP bit score";
public static final String ACC_Score = "HSP score";
public static final String ACC_EValue = "HSP E-Value";
public static final String ACC_PctIdentity = "HSP % of identities";
public static final String ACC_PctPositive = "HSP % of positives";
public static final String ACC_PctGap = "HSP % of gaps";
public static final String ACC_AlignLength = "HSP alignment length";
public static final String ACC_HspQueryFrom = "HSP query from";
public static final String ACC_HspQueryTo = "HSP query to";
public static final String ACC_HspQueryFrame = "HSP query frame";
public static final String ACC_HspQueryGaps = "HSP query gaps";
public static final String ACC_HspQuerySequence = "Query sequence";
public static final String ACC_HspHitFrom = "HSP hit from";
public static final String ACC_HspHitTo = "HSP hit to";
public static final String ACC_HspHitFrame = "HSP hit frame";
public static final String ACC_HspHitGaps = "HSP hit gaps";
public static final String ACC_HspHitSequence = "Hit sequence";
public static final String ACC_FeatureType = "Feature: type";
public static final String ACC_QualifierName = "Feature: Qualifier name";
public static final String ACC_QualifierValue = "Feature: Qualifier value";
public static final String ACC_SeqMolType = "SeqInfo: Molecular type";
public static final String ACC_SeqTopology = "SeqInfo: Topology";
public static final String ACC_SeqDivision = "SeqInfo: Division";
public static final String ACC_SeqOrganism = "SeqInfo: Organism";
public static final String ACC_SeqTaxonomy = "SeqInfo: Taxonomy";
public static final String ACC_SeqCreationDate = "SeqInfo: Creation date";
public static final String ACC_SeqUpdateDate = "SeqInfo: Update date";
/**
* Return an enumeration over the accessor visible names of a data model.
*/
public Enumeration<String> getAccessorVisibleNames();
/**
* Return a BAccessorEntry given its visible name.
*/
public BAccessorEntry getAccessorEntry(String visibleName);
/**
* Add a BAccessorEntry.
*/
public void addAccessorEntry(BAccessorEntry entry);
} |
package ca.ualberta.cs.bkhunter_notes;
import java.io.IOException;
// This is a Singleton controller that is used to
// access the claimList and thus subsequent claims
// throughout the app
public class ClaimController {
private static ClaimList claimList = null;
// This constructor is geared towards serialization
// but at the moment I believe it just returns
// the claimlist
static public ClaimList getClaimList() {
if (claimList == null) {
try {
claimList = ClaimListManager.getManager().loadClaimList();
claimList.addListener(new Listener() {
@Override
public void update() {
saveClaimList();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("could not deserialize");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("could not deserialize");
}
claimList = new ClaimList();
}
return claimList;
}
static public void saveClaimList() {
try {
ClaimListManager.getManager().saveClaimList(getClaimList());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("could not deserialize");
}
claimList = new ClaimList();
}
public void addIt(Claim c) {
if (claimList == null) {
claimList = new ClaimList();
}
claimList.addClaim(c);
}
} |
package com.tommytony.war;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.google.common.collect.ImmutableList;
import com.tommytony.war.config.InventoryBag;
import com.tommytony.war.config.ScoreboardType;
import com.tommytony.war.config.TeamConfig;
import com.tommytony.war.config.TeamConfigBag;
import com.tommytony.war.config.TeamKind;
import com.tommytony.war.config.WarzoneConfig;
import com.tommytony.war.config.WarzoneConfigBag;
import com.tommytony.war.event.WarBattleWinEvent;
import com.tommytony.war.event.WarPlayerLeaveEvent;
import com.tommytony.war.event.WarPlayerThiefEvent;
import com.tommytony.war.event.WarScoreCapEvent;
import com.tommytony.war.job.InitZoneJob;
import com.tommytony.war.job.LoadoutResetJob;
import com.tommytony.war.job.LogKillsDeathsJob;
import com.tommytony.war.job.LogKillsDeathsJob.KillsDeathsRecord;
import com.tommytony.war.job.ScoreCapReachedJob;
import com.tommytony.war.mapper.LoadoutYmlMapper;
import com.tommytony.war.spout.SpoutDisplayer;
import com.tommytony.war.structure.Bomb;
import com.tommytony.war.structure.Cake;
import com.tommytony.war.structure.HubLobbyMaterials;
import com.tommytony.war.structure.Monument;
import com.tommytony.war.structure.WarzoneMaterials;
import com.tommytony.war.structure.ZoneLobby;
import com.tommytony.war.structure.ZoneWallGuard;
import com.tommytony.war.utility.Direction;
import com.tommytony.war.utility.Loadout;
import com.tommytony.war.utility.LoadoutSelection;
import com.tommytony.war.utility.PlayerState;
import com.tommytony.war.utility.PotionEffectHelper;
import com.tommytony.war.volume.Volume;
import com.tommytony.war.volume.ZoneVolume;
/**
*
* @author tommytony
* @package com.tommytony.war
*/
public class Warzone {
private String name;
private ZoneVolume volume;
private World world;
private final List<Team> teams = new ArrayList<Team>();
private final List<Monument> monuments = new ArrayList<Monument>();
private final List<Bomb> bombs = new ArrayList<Bomb>();
private final List<Cake> cakes = new ArrayList<Cake>();
private Location teleport;
private ZoneLobby lobby;
private Location rallyPoint;
private final List<String> authors = new ArrayList<String>();
private final int minSafeDistanceFromWall = 6;
private List<ZoneWallGuard> zoneWallGuards = new ArrayList<ZoneWallGuard>();
private HashMap<String, PlayerState> playerStates = new HashMap<String, PlayerState>();
private HashMap<String, Team> flagThieves = new HashMap<String, Team>();
private HashMap<String, Bomb> bombThieves = new HashMap<String, Bomb>();
private HashMap<String, Cake> cakeThieves = new HashMap<String, Cake>();
private HashMap<String, LoadoutSelection> loadoutSelections = new HashMap<String, LoadoutSelection>();
private HashMap<String, PlayerState> deadMenInventories = new HashMap<String, PlayerState>();
private HashMap<String, Integer> killCount = new HashMap<String, Integer>();
private final List<Player> respawn = new ArrayList<Player>();
private final List<String> reallyDeadFighters = new ArrayList<String>();
private List<LogKillsDeathsJob.KillsDeathsRecord> killsDeathsTracker = new ArrayList<KillsDeathsRecord>();
private final WarzoneConfigBag warzoneConfig;
private final TeamConfigBag teamDefaultConfig;
private InventoryBag defaultInventories = new InventoryBag();
private Scoreboard scoreboard;
private HubLobbyMaterials lobbyMaterials = null;
private WarzoneMaterials warzoneMaterials = new WarzoneMaterials(
new ItemStack(Material.OBSIDIAN), new ItemStack(Material.FENCE),
new ItemStack(Material.GLOWSTONE));
private boolean isEndOfGame = false;
private boolean isReinitializing = false;
//private final Object gameEndLock = new Object();
public Warzone(World world, String name) {
this.world = world;
this.name = name;
this.warzoneConfig = new WarzoneConfigBag(this);
this.teamDefaultConfig = new TeamConfigBag(); // don't use ctor with Warzone, as this changes config resolution
this.volume = new ZoneVolume(name, this.getWorld(), this);
this.lobbyMaterials = War.war.getWarhubMaterials().clone();
}
public static Warzone getZoneByName(String name) {
Warzone bestGuess = null;
for (Warzone warzone : War.war.getWarzones()) {
if (warzone.getName().toLowerCase().equals(name.toLowerCase())) {
// perfect match, return right away
return warzone;
} else if (warzone.getName().toLowerCase().startsWith(name.toLowerCase())) {
// perhaps there's a perfect match in the remaining zones, let's take this one aside
bestGuess = warzone;
}
}
return bestGuess;
}
public static Warzone getZoneByLocation(Location location) {
for (Warzone warzone : War.war.getWarzones()) {
if (location.getWorld().getName().equals(warzone.getWorld().getName()) && warzone.getVolume() != null && warzone.getVolume().contains(location)) {
return warzone;
}
}
return null;
}
public static Warzone getZoneByLocation(Player player) {
return Warzone.getZoneByLocation(player.getLocation());
}
public static Warzone getZoneByPlayerName(String playerName) {
for (Warzone warzone : War.war.getWarzones()) {
Team team = warzone.getPlayerTeam(playerName);
if (team != null) {
return warzone;
}
}
return null;
}
public static Warzone getZoneByTeam(Team team) {
for (Warzone warzone : War.war.getWarzones()) {
for (Team teamToCheck : warzone.getTeams()) {
if (teamToCheck.getName().equals(team.getName())) {
return warzone;
}
}
}
return null;
}
public boolean ready() {
if (this.volume.hasTwoCorners() && !this.volume.tooSmall() && !this.volume.tooBig()) {
return true;
}
return false;
}
public List<Team> getTeams() {
return this.teams;
}
public Team getPlayerTeam(String playerName) {
for (Team team : this.teams) {
for (Player player : team.getPlayers()) {
if (player.getName().equals(playerName)) {
return team;
}
}
}
return null;
}
public String getTeamInformation() {
StringBuilder teamsMessage = new StringBuilder(War.war.getString("zone.teaminfo.prefix"));
if (this.getTeams().isEmpty()) {
teamsMessage.append(War.war.getString("zone.teaminfo.none"));
} else {
for (Team team : this.getTeams()) {
teamsMessage.append('\n');
teamsMessage.append(MessageFormat.format(War.war.getString("zone.teaminfo.format"),
team.getName(), team.getPoints(), team.getRemainingLifes(),
team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL), StringUtils.join(team.getPlayerNames())));
}
}
return teamsMessage.toString();
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.getName();
}
public void setTeleport(Location location) {
this.teleport = location;
}
public Location getTeleport() {
return this.teleport;
}
public int saveState(boolean clearArtifacts) {
if (this.ready()) {
if (clearArtifacts) {
// removed everything to keep save clean
for (ZoneWallGuard guard : this.zoneWallGuards) {
guard.deactivate();
}
this.zoneWallGuards.clear();
for (Team team : this.teams) {
for (Volume teamVolume : team.getSpawnVolumes().values()) {
teamVolume.resetBlocks();
}
if (team.getTeamFlag() != null) {
team.getFlagVolume().resetBlocks();
}
}
for (Monument monument : this.monuments) {
monument.getVolume().resetBlocks();
}
if (this.lobby != null) {
this.lobby.getVolume().resetBlocks();
}
}
this.volume.saveBlocks();
if (clearArtifacts) {
this.initializeZone(); // bring back stuff
}
return this.volume.size();
}
return 0;
}
/**
* Goes back to the saved state of the warzone (resets only block types, not physics). Also teleports all players back to their respective spawns.
*
* @return
*/
public void initializeZone() {
this.initializeZone(null);
}
public void initializeZone(Player respawnExempted) {
if (this.ready() && this.volume.isSaved()) {
if (this.scoreboard != null) {
for (OfflinePlayer opl : this.scoreboard.getPlayers()) {
this.scoreboard.resetScores(opl);
}
this.scoreboard.clearSlot(DisplaySlot.SIDEBAR);
for (Objective obj : this.scoreboard.getObjectives()) {
obj.unregister();
}
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getScoreboard() == this.scoreboard) {
player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());
}
}
this.scoreboard = null;
}
// everyone back to team spawn with full health
for (Team team : this.teams) {
for (Player player : team.getPlayers()) {
if (respawnExempted == null
|| (respawnExempted != null
&& !player.getName().equals(respawnExempted.getName()))) {
this.respawnPlayer(team, player);
}
}
team.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL));
team.initializeTeamSpawns();
if (team.getTeamFlag() != null) {
team.setTeamFlag(team.getTeamFlag());
}
}
this.initZone();
if (War.war.getWarHub() != null) {
War.war.getWarHub().resetZoneSign(this);
}
}
// Don't forget to reset these to false, or we won't be able to score or empty lifepools anymore
this.isReinitializing = false;
this.isEndOfGame = false;
}
public void initializeZoneAsJob(Player respawnExempted) {
InitZoneJob job = new InitZoneJob(this, respawnExempted);
War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);
}
public void initializeZoneAsJob() {
InitZoneJob job = new InitZoneJob(this);
War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);
}
private void initZone() {
// reset monuments
for (Monument monument : this.monuments) {
monument.getVolume().resetBlocks();
monument.addMonumentBlocks();
}
// reset bombs
for (Bomb bomb : this.bombs) {
bomb.getVolume().resetBlocks();
bomb.addBombBlocks();
}
// reset cakes
for (Cake cake : this.cakes) {
cake.getVolume().resetBlocks();
cake.addCakeBlocks();
}
// reset lobby (here be demons)
if (this.lobby != null) {
if (this.lobby.getVolume() != null) {
this.lobby.getVolume().resetBlocks();
}
this.lobby.initialize();
}
this.flagThieves.clear();
this.bombThieves.clear();
this.cakeThieves.clear();
this.reallyDeadFighters.clear();
if (this.getScoreboardType() != ScoreboardType.NONE) {
this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
scoreboard.registerNewObjective(this.getScoreboardType().getDisplayName(), "dummy");
Objective obj = scoreboard.getObjective(this.getScoreboardType().getDisplayName());
Validate.isTrue(obj.isModifiable(), "Cannot modify players' scores on the " + this.name + " scoreboard.");
for (Team team : this.getTeams()) {
String teamName = team.getKind().getColor() + team.getName() + ChatColor.RESET;
if (this.getScoreboardType() == ScoreboardType.POINTS) {
obj.getScore(Bukkit.getOfflinePlayer(teamName)).setScore(team.getPoints());
} else if (this.getScoreboardType() == ScoreboardType.LIFEPOOL) {
obj.getScore(Bukkit.getOfflinePlayer(teamName)).setScore(team.getRemainingLifes());
}
}
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
for (Team team : this.getTeams()) {
for (Player player : team.getPlayers()) {
player.setScoreboard(scoreboard);
}
}
}
// nom drops
for(Entity entity : (this.getWorld().getEntities())) {
if (!(entity instanceof Item)) {
continue;
}
// validate position
if (!this.getVolume().contains(entity.getLocation())) {
continue;
}
// omnomnomnom
entity.remove();
}
}
public void endRound() {
}
public void respawnPlayer(Team team, Player player) {
this.handleRespawn(team, player);
// Teleport the player back to spawn
player.teleport(team.getRandomSpawn());
}
public void respawnPlayer(PlayerMoveEvent event, Team team, Player player) {
this.handleRespawn(team, player);
// Teleport the player back to spawn
event.setTo(team.getRandomSpawn());
}
public boolean isRespawning(Player p) {
return respawn.contains(p);
}
private void handleRespawn(final Team team, final Player player) {
// Fill hp
player.setRemainingAir(300);
player.setHealth(20);
player.setFoodLevel(20);
player.setSaturation(team.getTeamConfig().resolveInt(TeamConfig.SATURATION));
player.setExhaustion(0);
player.setFireTicks(0); //this works fine here, why put it in LoudoutResetJob...? I'll keep it over there though
player.getOpenInventory().close();
player.setLevel(0);
player.setExp(0);
player.setAllowFlight(false);
player.setFlying(false);
player.getInventory().clear();
this.setKillCount(player.getName(), 0);
if (player.getGameMode() != GameMode.SURVIVAL) {
// Players are always in survival mode in warzones
player.setGameMode(GameMode.SURVIVAL);
}
// clear potion effects
PotionEffectHelper.clearPotionEffects(player);
boolean isFirstRespawn = false;
if (!this.getLoadoutSelections().keySet().contains(player.getName())) {
isFirstRespawn = true;
this.getLoadoutSelections().put(player.getName(), new LoadoutSelection(true, 0));
} else if (this.isReinitializing) {
isFirstRespawn = true;
this.getLoadoutSelections().get(player.getName()).setStillInSpawn(true);
} else {
this.getLoadoutSelections().get(player.getName()).setStillInSpawn(true);
}
// Spout
if (War.war.isSpoutServer()) {
SpoutManager.getPlayer(player).setTitle(team.getKind().getColor() + player.getName());
}
War.war.getKillstreakReward().getAirstrikePlayers().remove(player.getName());
final LoadoutResetJob job = new LoadoutResetJob(this, team, player, isFirstRespawn, false);
if (team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER) == 0 || isFirstRespawn) {
job.run();
}
else {
// "Respawn" Timer - player will not be able to leave spawn for a few seconds
respawn.add(player);
War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, new Runnable() {
public void run() {
respawn.remove(player);
War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);
}
}, team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER) * 20L); // 20 ticks = 1 second
}
}
public void resetInventory(Team team, Player player, HashMap<Integer, ItemStack> loadout) {
// Reset inventory to loadout
PlayerInventory playerInv = player.getInventory();
playerInv.clear();
playerInv.clear(playerInv.getSize() + 0);
playerInv.clear(playerInv.getSize() + 1);
playerInv.clear(playerInv.getSize() + 2);
playerInv.clear(playerInv.getSize() + 3); // helmet/blockHead
boolean helmetIsInLoadout = false;
for (Integer slot : loadout.keySet()) {
if (slot == 100) {
playerInv.setBoots(loadout.get(slot).clone());
} else if (slot == 101) {
playerInv.setLeggings(loadout.get(slot).clone());
} else if (slot == 102) {
playerInv.setChestplate(loadout.get(slot).clone());
} else if (slot == 103) {
playerInv.setHelmet(loadout.get(slot).clone());
helmetIsInLoadout = true;
} else {
ItemStack item = loadout.get(slot);
if (item != null) {
playerInv.addItem(item.clone());
}
}
}
if (this.getWarzoneConfig().getBoolean(WarzoneConfig.BLOCKHEADS)) {
playerInv.setHelmet(team.getKind().getBlockHead());
} else {
if (!helmetIsInLoadout) {
ItemStack helmet = new ItemStack(Material.LEATHER_HELMET);
LeatherArmorMeta meta = (LeatherArmorMeta) helmet.getItemMeta();
meta.setColor(team.getKind().getBukkitColor());
helmet.setItemMeta(meta);
playerInv.setHelmet(helmet);
}
}
}
public boolean isMonumentCenterBlock(Block block) {
for (Monument monument : this.monuments) {
int x = monument.getLocation().getBlockX();
int y = monument.getLocation().getBlockY() + 1;
int z = monument.getLocation().getBlockZ();
if (x == block.getX() && y == block.getY() && z == block.getZ()) {
return true;
}
}
return false;
}
public Monument getMonumentFromCenterBlock(Block block) {
for (Monument monument : this.monuments) {
int x = monument.getLocation().getBlockX();
int y = monument.getLocation().getBlockY() + 1;
int z = monument.getLocation().getBlockZ();
if (x == block.getX() && y == block.getY() && z == block.getZ()) {
return monument;
}
}
return null;
}
public boolean nearAnyOwnedMonument(Location to, Team team) {
for (Monument monument : this.monuments) {
if (monument.isNear(to) && monument.isOwner(team)) {
return true;
}
}
return false;
}
public List<Monument> getMonuments() {
return this.monuments;
}
public boolean hasPlayerState(String playerName) {
return this.playerStates.containsKey(playerName);
}
public void keepPlayerState(Player player) {
PlayerInventory inventory = player.getInventory();
ItemStack[] contents = inventory.getContents();
String playerTitle = player.getName();
if (War.war.isSpoutServer()) {
playerTitle = SpoutManager.getPlayer(player).getTitle();
}
this.playerStates.put(
player.getName(),
new PlayerState(player.getGameMode(), contents, inventory
.getHelmet(), inventory.getChestplate(), inventory
.getLeggings(), inventory.getBoots(), player
.getHealth(), player.getExhaustion(), player
.getSaturation(), player.getFoodLevel(), player
.getActivePotionEffects(), playerTitle, player
.getLevel(), player.getExp(), player.getAllowFlight()));
}
public void restorePlayerState(Player player) {
PlayerState originalState = this.playerStates.remove(player.getName());
PlayerInventory playerInv = player.getInventory();
if (originalState != null) {
player.getOpenInventory().close();
this.playerInvFromInventoryStash(playerInv, originalState);
player.setGameMode(originalState.getGamemode());
player.setHealth(Math.max(Math.min(originalState.getHealth(), 20.0D), 0.0D));
player.setExhaustion(originalState.getExhaustion());
player.setSaturation(originalState.getSaturation());
player.setFoodLevel(originalState.getFoodLevel());
PotionEffectHelper.restorePotionEffects(player, originalState.getPotionEffects());
player.setLevel(originalState.getLevel());
player.setExp(originalState.getExp());
player.setAllowFlight(originalState.canFly());
if (War.war.isSpoutServer()) {
SpoutManager.getPlayer(player).setTitle(originalState.getPlayerTitle());
}
}
player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());
}
private void playerInvFromInventoryStash(PlayerInventory playerInv, PlayerState originalContents) {
playerInv.clear();
playerInv.clear(playerInv.getSize() + 0);
playerInv.clear(playerInv.getSize() + 1);
playerInv.clear(playerInv.getSize() + 2);
playerInv.clear(playerInv.getSize() + 3); // helmet/blockHead
int invIndex = 0;
for (ItemStack item : originalContents.getContents()) {
if (item != null && item.getType() != Material.AIR) {
playerInv.setItem(invIndex, item);
}
invIndex++;
}
if (originalContents.getHelmet() != null) {
playerInv.setHelmet(originalContents.getHelmet());
}
if (originalContents.getChest() != null) {
playerInv.setChestplate(originalContents.getChest());
}
if (originalContents.getLegs() != null) {
playerInv.setLeggings(originalContents.getLegs());
}
if (originalContents.getFeet() != null) {
playerInv.setBoots(originalContents.getFeet());
}
}
public boolean hasMonument(String monumentName) {
for (Monument monument : this.monuments) {
if (monument.getName().startsWith(monumentName)) {
return true;
}
}
return false;
}
public Monument getMonument(String monumentName) {
for (Monument monument : this.monuments) {
if (monument.getName().startsWith(monumentName)) {
return monument;
}
}
return null;
}
public boolean hasBomb(String bombName) {
for (Bomb bomb : this.bombs) {
if (bomb.getName().equals(bombName)) {
return true;
}
}
return false;
}
public Bomb getBomb(String bombName) {
for (Bomb bomb : this.bombs) {
if (bomb.getName().startsWith(bombName)) {
return bomb;
}
}
return null;
}
public boolean hasCake(String cakeName) {
for (Cake cake : this.cakes) {
if (cake.getName().equals(cakeName)) {
return true;
}
}
return false;
}
public Cake getCake(String cakeName) {
for (Cake cake : this.cakes) {
if (cake.getName().startsWith(cakeName)) {
return cake;
}
}
return null;
}
public boolean isImportantBlock(Block block) {
if (this.ready()) {
for (Monument m : this.monuments) {
if (m.getVolume().contains(block)) {
return true;
}
}
for (Bomb b : this.bombs) {
if (b.getVolume().contains(block)) {
return true;
}
}
for (Cake c : this.cakes) {
if (c.getVolume().contains(block)) {
return true;
}
}
for (Team t : this.teams) {
for (Volume tVolume : t.getSpawnVolumes().values()) {
if (tVolume.contains(block)) {
return true;
}
}
if (t.getFlagVolume() != null && t.getFlagVolume().contains(block)) {
return true;
}
}
if (this.volume.isWallBlock(block)) {
return true;
}
}
return false;
}
public World getWorld() {
return this.world;
}
public void setWorld(World world) {
this.world = world;
}
public ZoneVolume getVolume() {
return this.volume;
}
public void setVolume(ZoneVolume zoneVolume) {
this.volume = zoneVolume;
}
public Team getTeamByKind(TeamKind kind) {
for (Team t : this.teams) {
if (t.getKind() == kind) {
return t;
}
}
return null;
}
public boolean isNearWall(Location latestPlayerLocation) {
if (this.volume.hasTwoCorners()) {
if (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
return true; // near east wall
} else if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
return true; // near south wall
} else if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
return true; // near north wall
} else if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
return true; // near west wall
} else if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {
return true; // near up wall
} else if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {
return true; // near down wall
}
}
return false;
}
public List<Block> getNearestWallBlocks(Location latestPlayerLocation) {
List<Block> nearestWallBlocks = new ArrayList<Block>();
if (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near east wall
Block eastWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX() + 1, latestPlayerLocation.getBlockY() + 1, this.volume.getSoutheastZ());
nearestWallBlocks.add(eastWallBlock);
}
if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near south wall
Block southWallBlock = this.world.getBlockAt(this.volume.getSoutheastX(), latestPlayerLocation.getBlockY() + 1, latestPlayerLocation.getBlockZ());
nearestWallBlocks.add(southWallBlock);
}
if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near north wall
Block northWallBlock = this.world.getBlockAt(this.volume.getNorthwestX(), latestPlayerLocation.getBlockY() + 1, latestPlayerLocation.getBlockZ());
nearestWallBlocks.add(northWallBlock);
}
if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near west wall
Block westWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), latestPlayerLocation.getBlockY() + 1, this.volume.getNorthwestZ());
nearestWallBlocks.add(westWallBlock);
}
if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {
// near up wall
Block upWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), this.volume.getMaxY(), latestPlayerLocation.getBlockZ());
nearestWallBlocks.add(upWallBlock);
}
if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {
// near down wall
Block downWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), this.volume.getMinY(), latestPlayerLocation.getBlockZ());
nearestWallBlocks.add(downWallBlock);
}
return nearestWallBlocks;
// note: y + 1 to line up 3 sided square with player eyes
}
public List<BlockFace> getNearestWalls(Location latestPlayerLocation) {
List<BlockFace> walls = new ArrayList<BlockFace>();
if (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near east wall
walls.add(Direction.EAST());
}
if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near south wall
walls.add(Direction.SOUTH());
}
if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near north wall
walls.add(Direction.NORTH());
}
if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {
// near west wall
walls.add(Direction.WEST());
}
if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {
// near up wall
walls.add(BlockFace.UP);
}
if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {
// near down wall
walls.add(BlockFace.DOWN);
}
return walls;
}
public ZoneWallGuard getPlayerZoneWallGuard(String name, BlockFace wall) {
for (ZoneWallGuard guard : this.zoneWallGuards) {
if (guard.getPlayer().getName().equals(name) && wall == guard.getWall()) {
return guard;
}
}
return null;
}
public boolean protectZoneWallAgainstPlayer(Player player) {
List<BlockFace> nearestWalls = this.getNearestWalls(player.getLocation());
boolean protecting = false;
for (BlockFace wall : nearestWalls) {
ZoneWallGuard guard = this.getPlayerZoneWallGuard(player.getName(), wall);
if (guard != null) {
// already protected, need to move the guard
guard.updatePlayerPosition(player.getLocation());
} else {
// new guard
guard = new ZoneWallGuard(player, War.war, this, wall);
this.zoneWallGuards.add(guard);
}
protecting = true;
}
return protecting;
}
public void dropZoneWallGuardIfAny(Player player) {
List<ZoneWallGuard> playerGuards = new ArrayList<ZoneWallGuard>();
for (ZoneWallGuard guard : this.zoneWallGuards) {
if (guard.getPlayer().getName().equals(player.getName())) {
playerGuards.add(guard);
guard.deactivate();
}
}
// now remove those zone guards
for (ZoneWallGuard playerGuard : playerGuards) {
this.zoneWallGuards.remove(playerGuard);
}
playerGuards.clear();
}
public void setLobby(ZoneLobby lobby) {
this.lobby = lobby;
}
public ZoneLobby getLobby() {
return this.lobby;
}
public Team autoAssign(Player player) {
Team lowestNoOfPlayers = null;
for (Team t : this.teams) {
if (lowestNoOfPlayers == null || (lowestNoOfPlayers != null && lowestNoOfPlayers.getPlayers().size() > t.getPlayers().size())) {
if (War.war.canPlayWar(player, t)) {
lowestNoOfPlayers = t;
}
}
}
if (lowestNoOfPlayers != null) {
if (player.getWorld() != this.getWorld()) {
player.teleport(this.getWorld().getSpawnLocation());
}
lowestNoOfPlayers.addPlayer(player);
lowestNoOfPlayers.resetSign();
if (!this.hasPlayerState(player.getName())) {
this.keepPlayerState(player);
}
War.war.msg(player, "join.inventorystored");
this.respawnPlayer(lowestNoOfPlayers, player);
this.broadcast("join.broadcast", player.getName(), lowestNoOfPlayers.getName());
}
return lowestNoOfPlayers;
}
public void handleDeath(Player player) {
// THIS ISN'T THREAD SAFE
// Every death and player movement should ideally occur in sequence because
// 1) a death can cause the end of the game by emptying a lifepool causing the max score to be reached
// 2) a player movement from one block to the next (getting a flag home or causing a bomb to go off perhaps) could win the game
// Concurrent execution of these events could cause the inventory reset of the last players to die to fail as
// they get tp'ed back to the lobby, or perhaps kills to bleed into the next round.
Team playerTeam = Team.getTeamByPlayerName(player.getName());
// Make sure the player that died is still part of a team, game may have ended while waiting.
// Ignore dying players that essentially just got tp'ed to lobby and got their state restored.
// Gotta take care of restoring ReallyDeadFighters' game-end state when in onRespawn as well.
if (playerTeam != null) {
// teleport to team spawn upon fast respawn death, but not for real deaths
if (!this.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
this.respawnPlayer(playerTeam, player);
} else {
// onPlayerRespawn takes care of real deaths
//player.setHealth(0);
this.getReallyDeadFighters().add(player.getName());
}
int remaining = playerTeam.getRemainingLifes();
if (remaining == 0) { // your death caused your team to lose
if (this.isReinitializing()) {
// Prevent duplicate battle end. You died just after the battle ending death.
this.respawnPlayer(playerTeam, player);
} else {
// Handle team loss
List<Team> teams = this.getTeams();
String scores = "";
for (Team t : teams) {
if (War.war.isSpoutServer()) {
for (Player p : t.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification("Round over! " + playerTeam.getKind().getColor() + playerTeam.getName()),
SpoutDisplayer.cleanForNotification("ran out of lives."),
playerTeam.getKind().getBlockHead(),
10000);
}
}
}
t.teamcast("zone.battle.end", playerTeam.getName(), player.getName());
if (t.getPlayers().size() != 0 && !t.getTeamConfig().resolveBoolean(TeamConfig.FLAGPOINTSONLY)) {
if (!t.getName().equals(playerTeam.getName())) {
// all other teams get a point
t.addPoint();
t.resetSign();
}
scores += '\n' + t.getName() + "(" + t.getPoints() + "/" + t.getTeamConfig().resolveInt(TeamConfig.MAXSCORE) + ") ";
}
}
// whoever didn't lose, reward them
List<Team> winningTeams = new ArrayList<Team>(teams.size());
for( Team t : teams ) {
if( !t.getPlayers().contains(player)) {
winningTeams.add(t);
}
}
WarBattleWinEvent event1 = new WarBattleWinEvent(this, winningTeams);
War.war.getServer().getPluginManager().callEvent(event1);
if (!scores.equals("")) {
this.broadcast("zone.battle.newscores", scores);
}
if (War.war.getMysqlConfig().isEnabled() && War.war.getMysqlConfig().isLoggingEnabled()) {
LogKillsDeathsJob logKillsDeathsJob = new LogKillsDeathsJob(ImmutableList.copyOf(this.getKillsDeathsTracker()));
War.war.getServer().getScheduler().runTaskAsynchronously(War.war, logKillsDeathsJob);
}
this.getKillsDeathsTracker().clear();
// detect score cap
List<Team> scoreCapTeams = new ArrayList<Team>();
for (Team t : teams) {
if (t.getPoints() == t.getTeamConfig().resolveInt(TeamConfig.MAXSCORE)) {
scoreCapTeams.add(t);
}
}
if (!scoreCapTeams.isEmpty()) {
String winnersStr = "";
for (Team winner : scoreCapTeams) {
if (winner.getPlayers().size() != 0) {
winnersStr += winner.getName() + " ";
}
}
this.handleScoreCapReached(winnersStr);
} else {
// A new battle starts. Reset the zone but not the teams.
this.broadcast("zone.battle.reset");
this.reinitialize();
}
}
} else {
// player died without causing his team's demise
if (this.isFlagThief(player.getName())) {
// died while carrying flag.. dropped it
Team victim = this.getVictimTeamForFlagThief(player.getName());
victim.getFlagVolume().resetBlocks();
victim.initializeTeamFlag();
this.removeFlagThief(player.getName());
if (War.war.isSpoutServer()) {
for (Player p : victim.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification(playerTeam.getKind().getColor() + player.getName() + ChatColor.YELLOW + " dropped"),
SpoutDisplayer.cleanForNotification(ChatColor.YELLOW + "your flag."),
playerTeam.getKind().getBlockHead(),
5000);
}
}
}
this.broadcast("drop.flag.broadcast", player.getName(), victim.getName());
}
// Bomb thieves
if (this.isBombThief(player.getName())) {
// died while carrying bomb.. dropped it
Bomb bomb = this.getBombForThief(player.getName());
bomb.getVolume().resetBlocks();
bomb.addBombBlocks();
this.removeBombThief(player.getName());
for (Team t : this.getTeams()) {
t.teamcast("drop.bomb.broadcast", player.getName(), ChatColor.GREEN + bomb.getName() + ChatColor.WHITE);
if (War.war.isSpoutServer()) {
for (Player p : t.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification(playerTeam.getKind().getColor() + player.getName() + ChatColor.YELLOW + " dropped"),
SpoutDisplayer.cleanForNotification(ChatColor.YELLOW + "bomb " + ChatColor.GREEN + bomb.getName() + ChatColor.YELLOW + "."),
Material.TNT,
(short)0,
5000);
}
}
}
}
}
if (this.isCakeThief(player.getName())) {
// died while carrying cake.. dropped it
Cake cake = this.getCakeForThief(player.getName());
cake.getVolume().resetBlocks();
cake.addCakeBlocks();
this.removeCakeThief(player.getName());
for (Team t : this.getTeams()) {
t.teamcast("drop.cake.broadcast", player.getName(), ChatColor.GREEN + cake.getName() + ChatColor.WHITE);
if (War.war.isSpoutServer()) {
for (Player p : t.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification(playerTeam.getKind().getColor() + player.getName() + ChatColor.YELLOW + " dropped"),
SpoutDisplayer.cleanForNotification(ChatColor.YELLOW + "cake " + ChatColor.GREEN + cake.getName() + ChatColor.YELLOW + "."),
Material.CAKE,
(short)0,
5000);
}
}
}
}
}
// Decrement lifepool
playerTeam.setRemainingLives(remaining - 1);
// Lifepool empty warning
if (remaining - 1 == 0) {
this.broadcast("zone.lifepool.empty", playerTeam.getName());
}
}
playerTeam.resetSign();
}
}
public void reinitialize() {
this.isReinitializing = true;
this.getVolume().resetBlocksAsJob();
}
public void handlePlayerLeave(Player player, Location destination, PlayerMoveEvent event, boolean removeFromTeam) {
this.handlePlayerLeave(player, removeFromTeam);
event.setTo(destination);
}
public void handlePlayerLeave(Player player, Location destination, boolean removeFromTeam) {
this.handlePlayerLeave(player, removeFromTeam);
player.teleport(destination);
}
private void handlePlayerLeave(Player player, boolean removeFromTeam) {
Team playerTeam = Team.getTeamByPlayerName(player.getName());
if (playerTeam != null) {
if (removeFromTeam) {
playerTeam.removePlayer(player.getName());
}
this.broadcast("leave.broadcast", playerTeam.getKind().getColor() + player.getName() + ChatColor.WHITE);
playerTeam.resetSign();
if (this.getLobby() != null) {
this.getLobby().resetTeamGateSign(playerTeam);
}
if (this.hasPlayerState(player.getName())) {
this.restorePlayerState(player);
}
if (this.getLoadoutSelections().containsKey(player.getName())) {
// clear inventory selection
this.getLoadoutSelections().remove(player.getName());
}
player.setFireTicks(0);
player.setRemainingAir(300);
// To hide stats
if (War.war.isSpoutServer()) {
War.war.getSpoutDisplayer().updateStats(player);
}
War.war.msg(player, "leave.inventoryrestore");
if (War.war.getWarHub() != null) {
War.war.getWarHub().resetZoneSign(this);
}
boolean zoneEmpty = true;
for (Team team : this.getTeams()) {
if (team.getPlayers().size() > 0) {
zoneEmpty = false;
break;
}
}
if (zoneEmpty && this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETONEMPTY)) {
// reset the zone for a new game when the last player leaves
for (Team team : this.getTeams()) {
team.resetPoints();
team.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL));
}
this.getVolume().resetBlocksAsJob();
this.initializeZoneAsJob();
War.war.log("Last player left warzone " + this.getName() + ". Warzone blocks resetting automatically...", Level.INFO);
}
WarPlayerLeaveEvent event1 = new WarPlayerLeaveEvent(player.getName());
War.war.getServer().getPluginManager().callEvent(event1);
}
}
public boolean isEnemyTeamFlagBlock(Team playerTeam, Block block) {
for (Team team : this.teams) {
if (!team.getName().equals(playerTeam.getName()) && team.isTeamFlagBlock(block)) {
return true;
}
}
return false;
}
public boolean isFlagBlock(Block block) {
for (Team team : this.teams) {
if (team.isTeamFlagBlock(block)) {
return true;
}
}
return false;
}
public Team getTeamForFlagBlock(Block block) {
for (Team team : this.teams) {
if (team.isTeamFlagBlock(block)) {
return team;
}
}
return null;
}
public boolean isBombBlock(Block block) {
for (Bomb bomb : this.bombs) {
if (bomb.isBombBlock(block.getLocation())) {
return true;
}
}
return false;
}
public Bomb getBombForBlock(Block block) {
for (Bomb bomb : this.bombs) {
if (bomb.isBombBlock(block.getLocation())) {
return bomb;
}
}
return null;
}
public boolean isCakeBlock(Block block) {
for (Cake cake : this.cakes) {
if (cake.isCakeBlock(block.getLocation())) {
return true;
}
}
return false;
}
public Cake getCakeForBlock(Block block) {
for (Cake cake : this.cakes) {
if (cake.isCakeBlock(block.getLocation())) {
return cake;
}
}
return null;
}
// Flags
public void addFlagThief(Team lostFlagTeam, String flagThief) {
this.flagThieves.put(flagThief, lostFlagTeam);
WarPlayerThiefEvent event1 = new WarPlayerThiefEvent(Bukkit.getPlayerExact(flagThief), WarPlayerThiefEvent.StolenObject.FLAG);
War.war.getServer().getPluginManager().callEvent(event1);
}
public boolean isFlagThief(String suspect) {
if (this.flagThieves.containsKey(suspect)) {
return true;
}
return false;
}
public Team getVictimTeamForFlagThief(String thief) {
return this.flagThieves.get(thief);
}
public void removeFlagThief(String thief) {
this.flagThieves.remove(thief);
}
// Bomb
public void addBombThief(Bomb bomb, String bombThief) {
this.bombThieves.put(bombThief, bomb);
WarPlayerThiefEvent event1 = new WarPlayerThiefEvent(Bukkit.getPlayerExact(bombThief), WarPlayerThiefEvent.StolenObject.BOMB);
War.war.getServer().getPluginManager().callEvent(event1);
}
public boolean isBombThief(String suspect) {
if (this.bombThieves.containsKey(suspect)) {
return true;
}
return false;
}
public Bomb getBombForThief(String thief) {
return this.bombThieves.get(thief);
}
public void removeBombThief(String thief) {
this.bombThieves.remove(thief);
}
// Cake
public void addCakeThief(Cake cake, String cakeThief) {
this.cakeThieves.put(cakeThief, cake);
WarPlayerThiefEvent event1 = new WarPlayerThiefEvent(Bukkit.getPlayerExact(cakeThief), WarPlayerThiefEvent.StolenObject.CAKE);
War.war.getServer().getPluginManager().callEvent(event1);
}
public boolean isCakeThief(String suspect) {
if (this.cakeThieves.containsKey(suspect)) {
return true;
}
return false;
}
public Cake getCakeForThief(String thief) {
return this.cakeThieves.get(thief);
}
public void removeCakeThief(String thief) {
this.cakeThieves.remove(thief);
}
public void clearThieves() {
this.flagThieves.clear();
this.bombThieves.clear();
this.cakeThieves.clear();
}
public boolean isTeamFlagStolen(Team team) {
for (String playerKey : this.flagThieves.keySet()) {
if (this.flagThieves.get(playerKey).getName().equals(team.getName())) {
return true;
}
}
return false;
}
public void handleScoreCapReached(String winnersStr) {
// Score cap reached. Reset everything.
this.isEndOfGame = true;
List<Team> winningTeams = new ArrayList<Team>(teams.size());
for (String team : winnersStr.split(" ")) {
winningTeams.add(this.getTeamByKind(TeamKind.getTeam(team)));
}
WarScoreCapEvent event1 = new WarScoreCapEvent(winningTeams);
War.war.getServer().getPluginManager().callEvent(event1);
new ScoreCapReachedJob(this, winnersStr).run(); // run inventory and teleports immediately to avoid inv reset problems
this.reinitialize();
}
public boolean isDeadMan(String playerName) {
if (this.deadMenInventories.containsKey(playerName)) {
return true;
}
return false;
}
public void restoreDeadmanInventory(Player player) {
if (this.isDeadMan(player.getName())) {
this.playerInvFromInventoryStash(player.getInventory(), this.deadMenInventories.get(player.getName()));
this.deadMenInventories.remove(player.getName());
}
}
public void setRallyPoint(Location location) {
this.rallyPoint = location;
}
public Location getRallyPoint() {
return this.rallyPoint;
}
public void unload() {
War.war.log("Unloading zone " + this.getName() + "...", Level.INFO);
for (Team team : this.getTeams()) {
for (Player player : team.getPlayers()) {
this.handlePlayerLeave(player, this.getTeleport(), false);
}
team.getPlayers().clear();
}
if (this.getLobby() != null) {
this.getLobby().getVolume().resetBlocks();
}
if (this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETONUNLOAD)) {
this.getVolume().resetBlocks();
}
}
public boolean isEnoughPlayers() {
int teamsWithEnough = 0;
for (Team team : teams) {
if (team.getPlayers().size() >= this.getWarzoneConfig().getInt(WarzoneConfig.MINPLAYERS)) {
teamsWithEnough++;
}
}
if (teamsWithEnough >= this.getWarzoneConfig().getInt(WarzoneConfig.MINTEAMS)) {
return true;
}
return false;
}
public HashMap<String, LoadoutSelection> getLoadoutSelections() {
return loadoutSelections;
}
public boolean isAuthor(Player player) {
// if no authors, all zonemakers can edit the zone
return authors.size() == 0 || authors.contains(player.getName());
}
public void addAuthor(String playerName) {
authors.add(playerName);
}
public List<String> getAuthors() {
return this.authors;
}
public String getAuthorsString() {
String authors = "";
for (String author : this.getAuthors()) {
authors += author + ",";
}
return authors;
}
public void equipPlayerLoadoutSelection(Player player, Team playerTeam, boolean isFirstRespawn, boolean isToggle) {
LoadoutSelection selection = this.getLoadoutSelections().get(player.getName());
if (selection != null && !this.isRespawning(player) && playerTeam.getPlayers().contains(player)) {
// Make sure that inventory resets dont occur if player has already tp'ed out (due to game end, or somesuch)
// - repawn timer + this method is why inventories were getting wiped as players exited the warzone.
List<Loadout> loadouts = playerTeam.getInventories().resolveNewLoadouts();
List<String> sortedNames = LoadoutYmlMapper.sortNames(Loadout.toLegacyFormat(loadouts));
sortedNames.remove("first");
for (Iterator<String> it = sortedNames.iterator(); it.hasNext();) {
String loadoutName = it.next();
Loadout ldt = Loadout.getLoadout(loadouts, loadoutName);
if (ldt.requiresPermission() && !player.hasPermission(ldt.getPermission())) {
it.remove();
}
}
if (sortedNames.isEmpty()) {
// Fix for zones that mistakenly only specify a `first' loadout, but do not add any others.
this.handlePlayerLeave(player, this.getTeleport(), true);
War.war.badMsg(player, "We couldn't find a loadout for you! Please alert the warzone maker to add a `default' loadout to this warzone.");
return;
}
int currentIndex = selection.getSelectedIndex();
Loadout firstLoadout = Loadout.getLoadout(loadouts, "first");
int i = 0;
Iterator<String> it = sortedNames.iterator();
while (it.hasNext()) {
String name = (String) it.next();
if (i == currentIndex) {
if (playerTeam.getTeamConfig().resolveBoolean(TeamConfig.PLAYERLOADOUTASDEFAULT) && name.equals("default")) {
// Use player's own inventory as loadout
this.resetInventory(playerTeam, player, this.getPlayerInventoryFromSavedState(player));
} else if (isFirstRespawn && firstLoadout != null && name.equals("default")
&& (firstLoadout.requiresPermission() ? player.hasPermission(firstLoadout.getPermission()) : true)) {
// Get the loadout for the first spawn
this.resetInventory(playerTeam, player, Loadout.getLoadout(loadouts, "first").getContents());
} else {
// Use the loadout from the list in the settings
this.resetInventory(playerTeam, player, Loadout.getLoadout(loadouts, name).getContents());
}
if (isFirstRespawn && playerTeam.getInventories().resolveLoadouts().keySet().size() > 1 || isToggle) {
War.war.msg(player, "zone.loadout.equip", name);
}
}
i++;
}
}
}
private HashMap<Integer, ItemStack> getPlayerInventoryFromSavedState(Player player) {
HashMap<Integer, ItemStack> playerItems = new HashMap<Integer, ItemStack>();
PlayerState originalState = this.playerStates.get(player.getName());
if (originalState != null) {
int invIndex = 0;
playerItems = new HashMap<Integer, ItemStack>();
for (ItemStack item : originalState.getContents()) {
if (item != null && item.getType() != Material.AIR) {
playerItems.put(invIndex, item);
}
invIndex++;
}
if (originalState.getFeet() != null) {
playerItems.put(100, originalState.getFeet());
}
if (originalState.getLegs() != null) {
playerItems.put(101, originalState.getLegs());
}
if (originalState.getChest() != null) {
playerItems.put(102, originalState.getChest());
}
if (originalState.getHelmet() != null) {
playerItems.put(103, originalState.getHelmet());
}
if (War.war.isSpoutServer()) {
SpoutManager.getPlayer(player).setTitle(originalState.getPlayerTitle());
}
}
return playerItems;
}
public WarzoneConfigBag getWarzoneConfig() {
return this.warzoneConfig;
}
public TeamConfigBag getTeamDefaultConfig() {
return this.teamDefaultConfig;
}
public InventoryBag getDefaultInventories() {
return this.defaultInventories ;
}
public List<Bomb> getBombs() {
return bombs;
}
public List<Cake> getCakes() {
return cakes;
}
public List<String> getReallyDeadFighters() {
return this.reallyDeadFighters ;
}
public void gameEndTeleport(Player tp) {
if (this.getRallyPoint() != null) {
tp.teleport(this.getRallyPoint());
} else if (this.getWarzoneConfig().getBoolean(WarzoneConfig.AUTOJOIN)) {
tp.teleport(War.war.getWarHub().getLocation());
} else {
tp.teleport(this.getTeleport());
}
tp.setFireTicks(0);
tp.setRemainingAir(300);
if (this.hasPlayerState(tp.getName())) {
this.restorePlayerState(tp);
}
}
public boolean isEndOfGame() {
return this.isEndOfGame;
}
public boolean isReinitializing() {
return this.isReinitializing;
}
// public Object getGameEndLock() {
// return gameEndLock;
public void setName(String newName) {
this.name = newName;
this.volume.setName(newName);
}
public HubLobbyMaterials getLobbyMaterials() {
return this.lobbyMaterials;
}
public void setLobbyMaterials(HubLobbyMaterials lobbyMaterials) {
this.lobbyMaterials = lobbyMaterials;
}
public boolean isOpponentSpawnPeripheryBlock(Team team, Block block) {
for (Team maybeOpponent : this.getTeams()) {
if (maybeOpponent != team) {
for (Volume teamSpawnVolume : maybeOpponent.getSpawnVolumes().values()) {
Volume periphery = new Volume(new Location(
teamSpawnVolume.getWorld(),
teamSpawnVolume.getMinX() - 1,
teamSpawnVolume.getMinY() - 1,
teamSpawnVolume.getMinZ() - 1), new Location(
teamSpawnVolume.getWorld(),
teamSpawnVolume.getMaxX() + 1,
teamSpawnVolume.getMaxY() + 1,
teamSpawnVolume.getMaxZ() + 1));
if (periphery.contains(block)) {
return true;
}
}
}
}
return false;
}
public void setWarzoneMaterials(WarzoneMaterials warzoneMaterials) {
this.warzoneMaterials = warzoneMaterials;
}
public WarzoneMaterials getWarzoneMaterials() {
return warzoneMaterials;
}
public Scoreboard getScoreboard() {
return scoreboard;
}
public ScoreboardType getScoreboardType() {
return this.getWarzoneConfig().getScoreboardType(WarzoneConfig.SCOREBOARD);
}
public boolean hasKillCount(String player) {
return killCount.containsKey(player);
}
public int getKillCount(String player) {
return killCount.get(player);
}
public void setKillCount(String player, int totalKills) {
if (totalKills < 0) {
throw new IllegalArgumentException("Amount of kills to set cannot be a negative number.");
}
killCount.put(player, totalKills);
}
public void addKillCount(String player, int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount of kills to add cannot be a negative number.");
}
killCount.put(player, killCount.get(player) + amount);
}
public void addKillDeathRecord(OfflinePlayer player, int kills, int deaths) {
for (Iterator<KillsDeathsRecord> it = this.killsDeathsTracker.iterator(); it.hasNext();) {
LogKillsDeathsJob.KillsDeathsRecord kdr = it.next();
if (kdr.getPlayer().equals(player)) {
kills += kdr.getKills();
deaths += kdr.getDeaths();
it.remove();
}
}
LogKillsDeathsJob.KillsDeathsRecord kdr = new LogKillsDeathsJob.KillsDeathsRecord(player, kills, deaths);
this.killsDeathsTracker.add(kdr);
}
public List<LogKillsDeathsJob.KillsDeathsRecord> getKillsDeathsTracker() {
return killsDeathsTracker;
}
/**
* Send a message to all teams.
* @param message Message or key to translate.
*/
public void broadcast(String message) {
for (Team team : this.teams) {
team.teamcast(message);
}
}
/**
* Send a message to all teams.
* @param message Message or key to translate.
* @param args Arguments for the formatter.
*/
public void broadcast(String message, Object... args) {
for (Team team : this.teams) {
team.teamcast(message, args);
}
}
public List<Player> getPlayers() {
List<Player> players = new ArrayList<Player>();
for (Team team : this.teams) {
players.addAll(team.getPlayers());
}
return players;
}
public int getPlayerCount() {
int count = 0;
for (Team team : this.teams) {
count += team.getPlayers().size();
}
return count;
}
} |
package com.appspot.usbhidterminal.core;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
public class USBHIDService extends AbstractUSBHIDService {
private String delimiter;
private String receiveDataFormat;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onCommand(Intent intent, String action, int flags, int startId) {
// Toast.makeText(this, "Service onCommand ...",
// Toast.LENGTH_SHORT).show();
if (Consts.RECEIVE_DATA_FORMAT.equals(action)) {
receiveDataFormat = intent.getStringExtra(Consts.RECEIVE_DATA_FORMAT);
delimiter = intent.getStringExtra(Consts.DELIMITER);
}
super.onCommand(intent, action, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "Service destroyed ...",
// Toast.LENGTH_SHORT).show();
}
@Override
public void onDeviceConnected() {
mLog("device connected");
}
@Override
public void onDeviceDisconnected() {
mLog("device disconnected");
}
@Override
public void onDeviceSelected(UsbDevice device) {
mLog("Selected device VID:" + Integer.toHexString(device.getVendorId()) + " PID:" + Integer.toHexString(device.getProductId()));
}
@Override
public CharSequence onBuildingDevicesList(UsbDevice usbDevice) {
return "devID:" + usbDevice.getDeviceId() + " VID:" + Integer.toHexString(usbDevice.getVendorId()) + " PID:" + Integer.toHexString(usbDevice.getProductId()) + " " + usbDevice.getDeviceName();
}
@Override
public void onUSBDataSending(String data) {
mLog("Sending: " + data);
}
@Override
public void onUSBDataSended(int status, byte[] out) {
mLog("sended " + status + " bytes");
for (int i = 0; i < out.length && out[i] != 0; i++) {
mLogC(Consts.SPACE + USBUtils.toInt(out[i]));
}
}
@Override
public void onSendingError(Exception e) {
mLog("Please check your bytes, sent as text");
}
@Override
public void onUSBDataReceive(byte[] buffer) {
StringBuilder stringBuilder = new StringBuilder();
if (receiveDataFormat.equals(Consts.INTEGER)) {
for (int i = 0; i < buffer.length && buffer[i] != 0; i++) {
stringBuilder.append(delimiter).append(String.valueOf(USBUtils.toInt(buffer[i])));
}
} else if (receiveDataFormat.equals(Consts.HEXADECIMAL)) {
for (int i = 0; i < buffer.length && buffer[i] != 0; i++) {
stringBuilder.append(delimiter).append(Integer.toHexString(buffer[i]));
}
} else if (receiveDataFormat.equals(Consts.TEXT)) {
for (int i = 0; i < buffer.length && buffer[i] != 0; i++) {
stringBuilder.append(String.valueOf((char) buffer[i]));
}
} else if (receiveDataFormat.equals(Consts.BINARY)) {
for (int i = 0; i < buffer.length && buffer[i] != 0; i++) {
stringBuilder.append(delimiter).append("0b").append(Integer.toBinaryString(Integer.valueOf(buffer[i])));
}
}
stringBuilder.append("\nreceived ").append(buffer.length).append(" bytes");
mLog(stringBuilder.toString());
}
private void mLog(String value) {
Bundle bundle = new Bundle();
bundle.putString("log", value);
sendResultToUI(Consts.ACTION_USB_LOG, bundle);
}
private void mLogC(String value) {
Bundle bundle = new Bundle();
bundle.putString("log", value);
sendResultToUI(Consts.ACTION_USB_LOG_C, bundle);
}
} |
package com.canmeizhexue.javademo.threads;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
public class WeakMapTest {
/**
* map
* @param args
*/
public static void main(String[]args){
Map map = new WeakHashMap();
//MyKey
map.put(new MyKey("helloworld"), "12345");
//key
map.put("wekmap", "map test");
map.put(new MyKey("3f3khgf"), "3evfe3");
/**
*
* stringastringbmapstringbnull
*/
String stringa = new String("aaaaa");
map.put(stringa, "valueaaaaaaaaaaaaaaaaaaaa");
stringa=null;
String stringb = "bbbbbbbbbbbb";
map.put(stringb, "valuebbbbbbbbbbb");
stringb=null;
printMap(map);
for(int i=0;i<20/*000*/;i++){
System.gc();
/* try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
if(map.isEmpty()){
System.out.println("map is empty "+i);
System.exit(-1);
}
System.out.println("current loop is "+i);
printMap(map);
}
System.out.println("test end ");
}
public static void printMap(Map map){
Set set=map.keySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
Object key = iterator.next();
System.out.println("key is "+key+" value is "+map.get(key));
}
}
public static class MyKey{
String key;
public MyKey(String key) {
super();
this.key = key;
}
public String toString() {
return key;
}
}
} |
package com.dmdirc.ui.swing.dialogs.paste;
import com.dmdirc.Main;
import com.dmdirc.ui.swing.MainFrame;
import com.dmdirc.ui.swing.UIUtilities;
import com.dmdirc.ui.swing.components.InputTextFrame;
import com.dmdirc.ui.swing.components.StandardDialog;
import com.dmdirc.ui.swing.components.SwingInputHandler;
import com.dmdirc.ui.swing.components.TextAreaInputField;
import com.dmdirc.ui.swing.components.TextLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
/**
* Allows the user to modify global client preferences.
*/
public final class PasteDialog extends StandardDialog implements ActionListener,
KeyListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 4;
/** Number of lines Label. */
private TextLabel infoLabel;
/** Text area scrollpane. */
private JScrollPane scrollPane;
/** Text area. */
private TextAreaInputField textField;
/** Parent frame. */
private final InputTextFrame parent;
/** Edit button. */
private JButton editButton;
/**
* Creates a new instance of PreferencesDialog.
*
* @param newParent The frame that owns this dialog
* @param text text to show in the paste dialog
*/
public PasteDialog(final InputTextFrame newParent, final String text) {
super((MainFrame) Main.getUI().getMainWindow(), false);
this.parent = newParent;
initComponents(text);
initListeners();
setFocusTraversalPolicy(new PasteDialogFocusTraversalPolicy(
getCancelButton(), editButton, getOkButton()));
setFocusable(true);
getOkButton().requestFocus();
getOkButton().setSelected(true);
pack();
setLocationRelativeTo((MainFrame) Main.getUI().getMainWindow());
}
/**
* Initialises GUI components.
*
* @param text text to show in the dialog
*/
private void initComponents(final String text) {
scrollPane = new JScrollPane();
textField = new TextAreaInputField(text);
editButton = new JButton("Edit");
infoLabel = new TextLabel();
UIUtilities.addUndoManager(textField);
orderButtons(new JButton(), new JButton());
getOkButton().setText("Send");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Multi-line paste");
setResizable(false);
infoLabel.setText("This will be sent as " + parent.getContainer().getNumLines(textField.getText()) + " lines. Are you sure you want to continue?");
textField.setColumns(50);
textField.setRows(10);
new SwingInputHandler(textField, parent.getCommandParser(), parent).setTypes(false, false, true, false);
scrollPane.setViewportView(textField);
scrollPane.setVisible(false);
getContentPane().setLayout(new MigLayout("fill, hidemode 3"));
getContentPane().add(infoLabel, "wrap, growx, pushx, span 3");
getContentPane().add(scrollPane, "wrap, grow, push, span 3");
getContentPane().add(getLeftButton(), "right, sg button");
getContentPane().add(editButton, "right, sg button");
getContentPane().add(getRightButton(), "right, sg button");
}
/**
* Initialises listeners for this dialog.
*/
private void initListeners() {
getOkButton().addActionListener(this);
getCancelButton().addActionListener(this);
editButton.addActionListener(this);
textField.addKeyListener(this);
getRootPane().getActionMap().put("rightArrowAction",
new AbstractAction("rightArrowAction") {
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
final JButton button = (JButton) getFocusTraversalPolicy().
getComponentAfter(PasteDialog.this, getFocusOwner());
button.requestFocus();
button.setSelected(true);
}
});
getRootPane().getActionMap().put("leftArrowAction",
new AbstractAction("leftArrowAction") {
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
final JButton button = (JButton) getFocusTraversalPolicy().
getComponentBefore(PasteDialog.this, getFocusOwner());
button.requestFocus();
button.setSelected(true);
}
});
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "rightArrowAction");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "leftArrowAction");
textField.getActionMap().put("ctrlEnterAction",
new AbstractAction("ctrlEnterAction") {
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
getOkButton().doClick();
}
});
textField.getInputMap(JComponent.WHEN_FOCUSED).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK), "ctrlEnterAction");
}
/**
* Handles the actions for the dialog.
*
* @param actionEvent Action event
*/
@Override
public void actionPerformed(final ActionEvent actionEvent) {
if (getOkButton().equals(actionEvent.getSource())) {
if (!textField.getText().isEmpty()) {
final String[] lines = textField.getText().split("\n");
for (String line : lines) {
parent.getContainer().sendLine(line);
parent.getInputHandler().addToBuffer(line);
}
}
dispose();
} else if (editButton.equals(actionEvent.getSource())) {
editButton.setEnabled(false);
setResizable(true);
scrollPane.setVisible(true);
infoLabel.setText("This will be sent as " + parent.getContainer().getNumLines(textField.getText()) + " lines.");
pack();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
setLocationRelativeTo((MainFrame) Main.getUI().getMainWindow());
}
});
} else if (getCancelButton().equals(actionEvent.getSource())) {
dispose();
}
}
/**
* {@inheritDoc}
*
* @param e Key event
*/
@Override
public void keyTyped(final KeyEvent e) {
infoLabel.setText("This will be sent as " + parent.getContainer().getNumLines(textField.getText()) + " lines.");
}
/**
* {@inheritDoc}
*
* @param e Key event
*/
@Override
public void keyPressed(final KeyEvent e) {
//Ignore.
}
/**
* {@inheritDoc}
*
* @param e Key event
*/
@Override
public void keyReleased(final KeyEvent e) {
//Ignore.
}
} |
package com.ecyrd.jspwiki.search;
import java.io.*;
import java.util.*;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLEncoder;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
import com.ecyrd.jspwiki.attachment.AttachmentManager;
import com.ecyrd.jspwiki.providers.ProviderException;
import com.ecyrd.jspwiki.providers.WikiPageProvider;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Interface for the search providers that handle searching the Wiki
*
* @author Arent-Jan Banck for Informatica
* @since 2.2.21.
*/
public class LuceneSearchProvider implements SearchProvider
{
private static final Logger log = Logger.getLogger(LuceneSearchProvider.class);
private WikiEngine m_engine;
// Lucene properties.
/** Which analyzer to use. Default is StandardAnalyzer. */
public static final String PROP_LUCENE_ANALYZER = "jspwiki.lucene.analyzer";
private String m_analyzerClass = "org.apache.lucene.analysis.standard.StandardAnalyzer";
private static final String LUCENE_DIR = "lucene";
// Number of page updates before we optimize the index.
public static final int LUCENE_OPTIMIZE_COUNT = 10;
private static final String LUCENE_ID = "id";
private static final String LUCENE_PAGE_CONTENTS = "contents";
private static final String LUCENE_AUTHOR = "author";
private static final String LUCENE_ATTACHMENTS = "attachment";
private static final String LUCENE_PAGE_NAME = "name";
private String m_luceneDirectory = null;
private int m_updateCount = 0;
private Thread m_luceneUpdateThread = null;
private Vector m_updates = new Vector(); // Vector because multi-threaded.
/** Maximum number of fragments from search matches. */
private static final int MAX_FRAGMENTS = 3;
public void initialize(WikiEngine engine, Properties props)
throws NoRequiredPropertyException, IOException
{
m_engine = engine;
m_luceneDirectory = engine.getWorkDir()+File.separator+LUCENE_DIR;
// FIXME: Just to be simple for now, we will do full reindex
// only if no files are in lucene directory.
File dir = new File(m_luceneDirectory);
log.info("Lucene enabled, cache will be in: "+dir.getAbsolutePath());
try
{
if( !dir.exists() )
{
dir.mkdirs();
}
if( !dir.exists() || !dir.canWrite() || !dir.canRead() )
{
log.error("Cannot write to Lucene directory, disabling Lucene: "+dir.getAbsolutePath());
throw new IOException( "Invalid Lucene directory." );
}
String[] filelist = dir.list();
if( filelist == null )
{
throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath());
}
}
catch ( IOException e )
{
log.error("Problem while creating Lucene index - not using Lucene.", e);
}
startLuceneUpdateThread();
}
/**
* Performs a full Lucene reindex, if necessary.
* @throws IOException
*/
private void doFullLuceneReindex()
throws IOException
{
File dir = new File(m_luceneDirectory);
String[] filelist = dir.list();
if( filelist == null )
{
throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath());
}
try
{
if( filelist.length == 0 )
{
// No files? Reindex!
Date start = new Date();
IndexWriter writer = null;
log.info("Starting Lucene reindexing, this can take a couple minutes...");
// Do lock recovery, in case JSPWiki was shut down forcibly
Directory luceneDir = FSDirectory.getDirectory(dir,false);
if( IndexReader.isLocked(luceneDir) )
{
log.info("JSPWiki was shut down while Lucene was indexing - unlocking now.");
IndexReader.unlock( luceneDir );
}
try
{
writer = new IndexWriter( m_luceneDirectory,
getLuceneAnalyzer(),
true );
Collection allPages = m_engine.getPageManager().getAllPages();
for( Iterator iterator = allPages.iterator(); iterator.hasNext(); )
{
WikiPage page = (WikiPage) iterator.next();
String text = m_engine.getPageManager().getPageText( page.getName(),
WikiProvider.LATEST_VERSION );
luceneIndexPage( page, text, writer );
}
Collection allAttachments = m_engine.getAttachmentManager().getAllAttachments();
for( Iterator iterator = allAttachments.iterator(); iterator.hasNext(); )
{
Attachment att = (Attachment) iterator.next();
String text = getAttachmentContent( att.getName(),
WikiProvider.LATEST_VERSION );
luceneIndexPage( att, text, writer );
}
writer.optimize();
}
finally
{
try
{
if( writer != null ) writer.close();
}
catch( IOException e ) {}
}
Date end = new Date();
log.info("Full Lucene index finished in " +
(end.getTime() - start.getTime()) + " milliseconds.");
}
else
{
log.info("Files found in Lucene directory, not reindexing.");
}
}
catch( NoClassDefFoundError e )
{
log.info("Lucene libraries do not exist - not using Lucene.");
}
catch ( IOException e )
{
log.error("Problem while creating Lucene index - not using Lucene.", e);
}
catch ( ProviderException e )
{
log.error("Problem reading pages while creating Lucene index (JSPWiki won't start.)", e);
throw new IllegalArgumentException("unable to create Lucene index");
}
catch( ClassNotFoundException e )
{
log.error("Illegal Analyzer specified:",e);
}
catch( Exception e )
{
log.error("Unable to start lucene",e);
}
}
/**
* Fetches the attachment content from the repository.
* Content is flat text that can be used for indexing/searching or display
*/
private String getAttachmentContent( String attachmentName, int version )
{
AttachmentManager mgr = m_engine.getAttachmentManager();
try
{
Attachment att = mgr.getAttachmentInfo( attachmentName, version );
//FIXME: Find out why sometimes att is null
if(att != null)
{
return getAttachmentContent( att );
}
}
catch (ProviderException e)
{
log.error("Attachment cannot be loaded", e);
}
// Something was wrong, no result is returned.
return null;
}
/**
* @param att Attachment to get content for. Filename extension is used to determine the type of the attachment.
* @return String representing the content of the file.
* FIXME This is a very simple implementation of some text-based attachment, mainly used for testing.
* This should be replaced /moved to Attachment search providers or some other 'plugable' wat to search attachments
*/
private String getAttachmentContent( Attachment att )
{
AttachmentManager mgr = m_engine.getAttachmentManager();
//FIXME: Add attachment plugin structure
String filename = att.getFileName();
if(filename.endsWith(".txt") ||
filename.endsWith(".xml") ||
filename.endsWith(".ini") ||
filename.endsWith(".html"))
{
InputStream attStream;
try
{
attStream = mgr.getAttachmentStream( att );
StringWriter sout = new StringWriter();
FileUtil.copyContents( new InputStreamReader(attStream), sout );
attStream.close();
sout.close();
return sout.toString();
}
catch (ProviderException e)
{
log.error("Attachment cannot be loaded", e);
return null;
}
catch (IOException e)
{
log.error("Attachment cannot be loaded", e);
return null;
}
}
return null;
}
/**
* Waits first for a little while before starting to go through
* the Lucene "pages that need updating".
*/
private void startLuceneUpdateThread()
{
m_luceneUpdateThread = new Thread(new Runnable()
{
public void run()
{
// FIXME: This is a kludge - JSPWiki should somehow report
// that init phase is complete.
try
{
Thread.sleep( 60000L );
}
catch( InterruptedException e )
{
throw new InternalWikiException("Interrupted while waiting to start.");
}
try
{
doFullLuceneReindex();
while( true )
{
while( m_updates.size() > 0 )
{
Object[] pair = ( Object[] ) m_updates.remove(0);
WikiPage page = ( WikiPage ) pair[0];
String text = ( String ) pair[1];
updateLuceneIndex(page, text);
}
try
{
Thread.sleep(500);
}
catch ( InterruptedException e ) {}
}
}
catch( Exception e )
{
log.error("Problem with Lucene indexing - indexing shut down (no searching)",e);
}
}
});
m_luceneUpdateThread.setName("JSPWiki Lucene update thread");
m_luceneUpdateThread.setDaemon(true);
m_luceneUpdateThread.start();
}
private synchronized void updateLuceneIndex( WikiPage page, String text )
{
IndexWriter writer = null;
log.debug("Updating Lucene index for page '" + page.getName() + "'...");
try
{
pageRemoved(page);
// Now add back the new version.
writer = new IndexWriter(m_luceneDirectory, getLuceneAnalyzer(), false);
luceneIndexPage(page, text, writer);
m_updateCount++;
if( m_updateCount >= LUCENE_OPTIMIZE_COUNT )
{
writer.optimize();
m_updateCount = 0;
}
}
catch ( IOException e )
{
log.error("Unable to update page '" + page.getName() + "' from Lucene index", e);
}
catch( Exception e )
{
log.error("Unexpected Lucene exception - please check configuration!",e);
}
finally
{
try
{
if( writer != null ) writer.close();
}
catch( IOException e ) {}
}
log.debug("Done updating Lucene index for page '" + page.getName() + "'.");
}
private Analyzer getLuceneAnalyzer()
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException
{
Class clazz = ClassUtil.findClass( "", m_analyzerClass );
Analyzer analyzer = (Analyzer)clazz.newInstance();
return analyzer;
}
private void luceneIndexPage( WikiPage page, String text, IndexWriter writer )
throws IOException
{
// make a new, empty document
Document doc = new Document();
if( text == null ) return;
// Raw name is the keyword we'll use to refer to this document for updates.
doc.add(Field.Keyword(LUCENE_ID, page.getName()));
/*
// Body text is indexed, but not stored in doc. We add in the
// title text as well to make sure it gets considered.
doc.add(Field.Text(LUCENE_PAGE_CONTENTS,
new StringReader(text + " " +
page.getName()+" "+
TextUtil.beautifyString(page.getName()))));
*/
// Body text. It is stored in the doc for search contexts.
doc.add(Field.Text(LUCENE_PAGE_CONTENTS, text));
// Allow searching by page name
doc.add(Field.Text(LUCENE_PAGE_NAME, TextUtil.beautifyString(page.getName())));
// Allow searching by authorname
if( page.getAuthor() != null )
{
doc.add(Field.Text(LUCENE_AUTHOR, page.getAuthor()));
}
// Now add the names of the attachments of this page
try
{
Collection attachments = m_engine.getAttachmentManager().listAttachments(page);
String attachmentNames = "";
for( Iterator it = attachments.iterator(); it.hasNext(); )
{
Attachment att = (Attachment) it.next();
attachmentNames += att.getName() + ";";
}
doc.add(Field.Text(LUCENE_ATTACHMENTS, attachmentNames));
}
catch(ProviderException e)
{
// Unable to read attachments
log.error("Failed to get attachments for page", e);
}
writer.addDocument(doc);
}
public void pageRemoved( WikiPage page )
{
try
{
// Must first remove existing version of page.
IndexReader reader = IndexReader.open(m_luceneDirectory);
reader.delete(new Term(LUCENE_ID, page.getName()));
reader.close();
}
catch ( IOException e )
{
log.error("Unable to update page '" + page.getName() + "' from Lucene index", e);
}
}
/**
* Adds a page-text pair to the lucene update queue. Safe to call always
*/
public void reindexPage( WikiPage page )
{
if( page != null )
{
String text;
// TODO: Think if this was better done in the thread itself?
if( page instanceof Attachment )
{
text = getAttachmentContent( (Attachment) page );
}
else
{
text = m_engine.getPureText( page );
}
if( text != null )
{
// Add work item to m_updates queue.
Object[] pair = new Object[2];
pair[0] = page;
pair[1] = text;
m_updates.add(pair);
log.debug("Scheduling page " + page.getName() + " for index update");
}
}
}
public Collection findPages( String query )
throws ProviderException
{
Searcher searcher = null;
ArrayList list = null;
try
{
String[] queryfields = { LUCENE_PAGE_CONTENTS, LUCENE_PAGE_NAME, LUCENE_AUTHOR };
QueryParser qp = new MultiFieldQueryParser( queryfields, getLuceneAnalyzer() );
// QueryParser qp = new QueryParser( LUCENE_PAGE_CONTENTS, getLuceneAnalyzer() );
Query luceneQuery = qp.parse( query );
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"searchmatch\">", "</span>"),
new SimpleHTMLEncoder(),
new QueryScorer(luceneQuery));
try
{
searcher = new IndexSearcher(m_luceneDirectory);
}
catch( Exception ex )
{
log.info("Lucene not yet ready; indexing not started",ex);
return null;
}
Hits hits = searcher.search(luceneQuery);
list = new ArrayList(hits.length());
for ( int curr = 0; curr < hits.length(); curr++ )
{
Document doc = hits.doc(curr);
String pageName = doc.get(LUCENE_ID);
WikiPage page = m_engine.getPage(pageName, WikiPageProvider.LATEST_VERSION);
if(page != null)
{
if(page instanceof Attachment)
{
// Currently attachments don't look nice on the search-results page
// When the search-results are cleaned up this can be enabled again.
}
int score = (int)(hits.score(curr) * 100);
// Get highlighted search contexts
String text = doc.get(LUCENE_PAGE_CONTENTS);
String fragments[] = new String[0];
if (text != null)
{
TokenStream tokenStream = getLuceneAnalyzer()
.tokenStream(LUCENE_PAGE_CONTENTS, new StringReader(text));
fragments = highlighter.getBestFragments(tokenStream,
text, MAX_FRAGMENTS);
}
SearchResult result = new SearchResultImpl( page, score, fragments ); list.add(result);
}
else
{
log.error("Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache");
pageRemoved(new WikiPage( m_engine, pageName ));
}
}
}
catch( IOException e )
{
log.error("Failed during lucene search",e);
}
catch( InstantiationException e )
{
log.error("Unable to get a Lucene analyzer",e);
}
catch( IllegalAccessException e )
{
log.error("Unable to get a Lucene analyzer",e);
}
catch( ClassNotFoundException e )
{
log.error("Specified Lucene analyzer does not exist",e);
}
catch( ParseException e )
{
log.info("Broken query; cannot parse",e);
throw new ProviderException("You have entered a query Lucene cannot process: "+e.getMessage());
}
finally
{
if( searcher != null ) try { searcher.close(); } catch( IOException e ) {}
}
return list;
}
public String getProviderInfo()
{
return "LuceneSearchProvider";
}
// FIXME: This class is dumb; needs to have a better implementation
private class SearchResultImpl
implements SearchResult
{
private WikiPage m_page;
private int m_score;
private String[] m_contexts;
public SearchResultImpl( WikiPage page, int score, String[] contexts )
{
m_page = page;
m_score = score;
m_contexts = contexts;
}
public WikiPage getPage()
{
return m_page;
}
/* (non-Javadoc)
* @see com.ecyrd.jspwiki.SearchResult#getScore()
*/
public int getScore()
{
return m_score;
}
public String[] getContexts()
{
return m_contexts;
}
}
} |
package com.example.aperture.core;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
public class AerialFaithActivity extends ListActivity {
private final static int REQUEST_SPEECH = 1;
private final static int REQUEST_IMAGE = 2;
private final static int REQUEST_VIDEO = 4;
private Set<ComponentName> mModules = new TreeSet<ComponentName>();
private RelativeLayout header = null;
private SearchView polybox = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeHeaderView();
}
@Override
protected void onResume() {
super.onResume();
loadModuleListFromPreferences();
}
@Override
public boolean onCreateOptionsMenu(Menu m) {
getMenuInflater().inflate(R.menu.main, m);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem mi) {
if(mi.getItemId() == R.id.resolve_stalemates) {
Intent resolveStalematesIntent = new Intent(
this, StalemateResolutionActivity.class);
startActivity(resolveStalematesIntent);
return true;
}
return super.onOptionsItemSelected(mi);
}
@Override
protected void onActivityResult(int request, int response, Intent data) {
if(response != Activity.RESULT_OK) {
return;
}
if(request == REQUEST_SPEECH) {
ArrayList<String> results = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
if(results == null || results.size() == 0) {
return;
}
String bestMatch = results.get(0);
polybox.setQuery(bestMatch, false);
}
else if(request == REQUEST_IMAGE) {
android.widget.Toast.makeText(this, "NotImplemented (img)",
android.widget.Toast.LENGTH_SHORT).show();
}
else if(request == REQUEST_VIDEO) {
android.widget.Toast.makeText(this, "NotImplemented (vid)",
android.widget.Toast.LENGTH_SHORT).show();
}
}
private void loadModuleListFromPreferences() {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
Set<String> modules = prefs.getStringSet(
ModuleManagement.LAST_ALL_MODULES, new TreeSet<String>());
ArrayList<String> components = new ArrayList<String>();
for(String name: modules) {
if(prefs.getBoolean(name, false))
components.add(name);
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
components));
}
private void initializeHeaderView() {
header = (RelativeLayout)getLayoutInflater().inflate(
R.layout.main, getListView(), false);
getListView().addHeaderView(header);
polybox = (SearchView)header.findViewById(android.R.id.text1);
polybox.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_URI);
// @android:id/button1
// @android:id/button2
// keyboard type
RadioGroup grp = (RadioGroup)header.findViewById(R.id.text1_inputtype);
grp.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup rg, int id) {
if(id == android.R.id.button1) {
AerialFaithActivity.this.polybox.setInputType(
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_URI);
}
else if(id == android.R.id.button2) {
AerialFaithActivity.this.polybox.setInputType(
InputType.TYPE_CLASS_PHONE);
}
}
});
// @id/button3 : speech recognition
Button b3 = (Button)header.findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent speechIntent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
startActivityForResult(speechIntent, REQUEST_SPEECH);
}
});
// @id/button4 : image
Button b4 = (Button)header.findViewById(R.id.button4);
b4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE);
}
});
// @id/button5 : video
Button b5 = (Button)header.findViewById(R.id.button5);
b5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_VIDEO);
}
});
}
} |
package com.jmex.model.XMLparser.Converters;
import java.io.DataInput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.jme.image.Texture;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Controller;
import com.jme.scene.Node;
import com.jme.scene.TriMesh;
import com.jme.scene.state.CullState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.system.JmeException;
import com.jme.util.LittleEndien;
import com.jme.util.geom.BufferUtils;
import com.jmex.model.JointMesh;
import com.jmex.model.XMLparser.JmeBinaryWriter;
import com.jmex.model.animation.JointController;
public class MilkToJme extends FormatConverter{
private DataInput inFile;
private byte[] tempChar=new byte[128];
private int nNumVertices;
private int nNumTriangles;
private MilkTriangle[] myTris;
private MilkVertex[] myVerts;
private int[] materialIndexes;
/**
* Converts a MS3D file to jME format. The syntax is: "MilkToJme runner.ms3d out.jme".
* @param args The array of parameters
*/
public static void main(String[] args){
new DummyDisplaySystem();
new MilkToJme().attemptFileConvert(args);
}
/**
* The node that represents the .ms3d file. It's chidren are MS meshes
*/
private Node finalNode;
/**
* This class's only public function. It creates a node from a .ms3d stream and then writes that node to the given
* OutputStream in binary format
* @param MSFile An inputStream that is the .ms3d file
* @param o The Stream to write it's jME binary equivalent to
* @throws IOException If anything funky goes wrong with reading information
*/
public void convert(InputStream MSFile,OutputStream o) throws IOException {
inFile=new LittleEndien(MSFile);
finalNode=new Node("ms3d file");
CullState CS=DisplaySystem.getDisplaySystem().getRenderer().createCullState();
CS.setCullMode(CullState.CS_BACK);
CS.setEnabled(true);
finalNode.setRenderState(CS);
checkHeader();
readVerts();
readTriangles();
readGroups();
readMats();
JmeBinaryWriter jbw=new JmeBinaryWriter();
if (!readJoints()){
jbw.setProperty("jointmesh","astrimesh");
}
jbw.writeScene(finalNode,o);
nullAll();
}
private void nullAll() {
myTris=null;
myVerts=null;
finalNode=null;
}
private boolean readJoints() throws IOException {
float fAnimationFPS=inFile.readFloat();
float curTime=inFile.readFloat(); // Ignore currentTime
int iTotalFrames=inFile.readInt(); // Ignore total Frames
int nNumJoints=inFile.readUnsignedShort();
if (nNumJoints==0) return false;
String[] jointNames=new String[nNumJoints];
String[] parentNames=new String[nNumJoints];
JointController jc=new JointController(nNumJoints);
jc.FPS=fAnimationFPS;
for (int i=0;i<nNumJoints;i++){
inFile.readByte(); // Ignore flags
inFile.readFully(tempChar,0,32);
jointNames[i]=cutAtNull(tempChar);
inFile.readFully(tempChar,0,32);
parentNames[i]=cutAtNull(tempChar);
jc.localRefMatrix[i].setEulerRot(inFile.readFloat(),inFile.readFloat(),inFile.readFloat());
jc.localRefMatrix[i].setTranslation(inFile.readFloat(),inFile.readFloat(),inFile.readFloat());
int numKeyFramesRot=inFile.readUnsignedShort();
int numKeyFramesTrans=inFile.readUnsignedShort();
for (int j=0;j<numKeyFramesRot;j++)
jc.setRotation(i,inFile.readFloat(),inFile.readFloat(),inFile.readFloat(),inFile.readFloat());
for (int j=0;j<numKeyFramesTrans;j++)
jc.setTranslation(i,inFile.readFloat(),inFile.readFloat(),inFile.readFloat(),inFile.readFloat());
}
for (int i=0;i<nNumJoints;i++){
jc.parentIndex[i]=-1;
for (int j=0;j<nNumJoints;j++){
if (parentNames[i].equals(jointNames[j])) jc.parentIndex[i]=j;
}
}
jc.setRepeatType(Controller.RT_WRAP);
finalNode.addController(jc);
return true;
}
private void readMats() throws IOException {
int nNumMaterials=inFile.readUnsignedShort();
for (int i=0;i<nNumMaterials;i++){
inFile.skipBytes(32); // Skip the name, unused
MaterialState matState=new MaterialState(){
private static final long serialVersionUID = 1L;
public void apply() {throw new JmeException("I am not to be used in a real graph");}
};
matState.setAmbient(getNextColor());
matState.setDiffuse(getNextColor());
matState.setSpecular(getNextColor());
matState.setEmissive(getNextColor());
matState.setShininess(inFile.readFloat());
matState.setAlpha(inFile.readFloat());
inFile.readByte(); // Mode is ignored
inFile.readFully(tempChar,0,128);
TextureState texState=null;
String texFile=cutAtNull(tempChar);
if (texFile.length()!=0){
texState=DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
Texture tempTex=new Texture();
tempTex.setImageLocation("file:/"+texFile);
tempTex.setWrap(Texture.WM_WRAP_S_WRAP_T);
texState.setTexture(tempTex);
}
inFile.readFully(tempChar,0,128); // Alpha map, but it is ignored
//TODO: Implement Alpha Maps
applyStates(matState,texState,i);
}
}
/**
* Every child of finalNode (IE the .ms3d file) whos materialIndex is the given index, gets the two RenderStates applied
* @param matState A Material state to apply
* @param texState A TextureState to apply
* @param index The index that a TriMesh should have from <code>materialIndex</code> to get the given
* states
*/
private void applyStates(MaterialState matState, TextureState texState,int index) {
for (int i=0;i<finalNode.getQuantity();i++){
if (materialIndexes[i]==index){
if (matState!=null) ((TriMesh)finalNode.getChild(i)).setRenderState(matState);
if (texState!=null) ((TriMesh)finalNode.getChild(i)).setRenderState(texState);
}
}
}
private ColorRGBA getNextColor() throws IOException {
return new ColorRGBA(
inFile.readFloat(),
inFile.readFloat(),
inFile.readFloat(),
inFile.readFloat()
);
}
private void readGroups() throws IOException {
int nNumGroups=inFile.readUnsignedShort();
materialIndexes=new int[nNumGroups];
for (int i=0;i<nNumGroups;i++){
inFile.readByte(); // Ignore flags
inFile.readFully(tempChar,0,32); // Name
int numTriLocal=inFile.readUnsignedShort();
Vector3f[] meshVerts=new Vector3f[numTriLocal*3],meshNormals=new Vector3f[numTriLocal*3];
Vector3f[] origVerts=new Vector3f[numTriLocal*3],origNormals=new Vector3f[numTriLocal*3];
Vector2f[] meshTexCoords=new Vector2f[numTriLocal*3];
int[] meshIndex=new int[numTriLocal*3];
int[] jointIndex=new int[numTriLocal*3];
JointMesh theMesh=new JointMesh(cutAtNull(tempChar));
for (int j=0;j<numTriLocal;j++){
int triIndex=inFile.readUnsignedShort();
for (int k=0;k<3;k++){
meshVerts [j*3+k]=myVerts[myTris[triIndex].vertIndicies[k]].vertex;
meshNormals [j*3+k]=myTris[triIndex].vertNormals[k];
meshTexCoords [j*3+k]=myTris[triIndex].vertTexCoords[k];
meshIndex [j*3+k]=j*3+k;
origVerts [j*3+k]=meshVerts[j*3+k];
origNormals [j*3+k]=meshNormals[j*3+k];
jointIndex [j*3+k]=myVerts[myTris[triIndex].vertIndicies[k]].boneID;
}
}
theMesh.reconstruct(BufferUtils.createFloatBuffer(meshVerts),
BufferUtils.createFloatBuffer(meshNormals), null,
BufferUtils.createFloatBuffer(meshTexCoords),
BufferUtils.createIntBuffer(meshIndex));
theMesh.originalNormal=origNormals;
theMesh.originalVertex=origVerts;
theMesh.jointIndex=jointIndex;
finalNode.attachChild(theMesh);
materialIndexes[i]=inFile.readByte();
}
}
private void readTriangles() throws IOException {
nNumTriangles=inFile.readUnsignedShort();
myTris=new MilkTriangle[nNumTriangles];
for (int i=0;i<nNumTriangles;i++){
int j;
myTris[i]=new MilkTriangle();
inFile.readUnsignedShort(); // Ignore flags
for (j=0;j<3;j++)
myTris[i].vertIndicies[j]=inFile.readUnsignedShort();
for (j=0;j<3;j++){
myTris[i].vertNormals[j]=new Vector3f(
inFile.readFloat(),
inFile.readFloat(),
inFile.readFloat()
);
}
for (j=0;j<3;j++){
myTris[i].vertTexCoords[j]=new Vector2f();
myTris[i].vertTexCoords[j].x=inFile.readFloat();
}
for (j=0;j<3;j++)
myTris[i].vertTexCoords[j].y=1-inFile.readFloat();
inFile.readByte(); // Ignore smoothingGroup
inFile.readByte(); // Ignore groupIndex
}
}
private void readVerts() throws IOException {
nNumVertices=inFile.readUnsignedShort();
myVerts=new MilkVertex[nNumVertices];
for (int i=0;i<nNumVertices;i++){
myVerts[i]=new MilkVertex();
inFile.readByte(); // Ignore flags
myVerts[i].vertex=new Vector3f(
inFile.readFloat(),
inFile.readFloat(),
inFile.readFloat()
);
myVerts[i].boneID=inFile.readByte();
inFile.readByte(); // Ignore referenceCount
}
}
private void checkHeader() throws IOException {
inFile.readFully(tempChar,0,10);
if (!"MS3D000000".equals(new String(tempChar,0,10))) throw new JmeException("Wrong File type: not Milkshape file??");
if (inFile.readInt()!=4) throw new JmeException("Wrong file version: Not 4"); // version
}
private static class MilkVertex{
Vector3f vertex;
byte boneID;
}
private static class MilkTriangle{
int[] vertIndicies=new int[3]; // 3 ints
Vector3f[] vertNormals=new Vector3f[3]; // 3 Vector3fs
Vector2f[] vertTexCoords=new Vector2f[3]; // 3 Texture Coords
}
private static String cutAtNull(byte[] inString) {
for (int i=0;i<inString.length;i++)
if (inString[i]==0) return new String(inString,0,i);
return new String(inString);
}
/**
* This function returns the controller of a loaded Milkshape3D model. Will return
* null if a correct JointController could not be found, or if one does not exist.
* @param model The model that was loaded.
* @return The controller for that milkshape model.
*/
public static JointController findController(Node model){
if (model.getQuantity()==0 ||
model.getChild(0).getControllers().size()==0 ||
!(model.getChild(0).getController(0) instanceof JointController))
return null;
return (JointController) (model.getChild(0)).getController(0);
}
} |
package com.leontg77.timebomb.listeners;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import com.leontg77.timebomb.Main;
import com.leontg77.timebomb.Settings;
/**
* Death listener class.
*
* @author LeonTG77
*/
public class DeathListener implements Listener {
private final Settings settings;
private final Main plugin;
public DeathListener(Main plugin, Settings settings) {
this.settings = settings;
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void on(PlayerDeathEvent event) {
final Player player = event.getEntity();
final Location loc = player.getLocation().clone();
if (settings.getConfig().getStringList("safe worlds").contains(loc.getWorld().getName())) {
return;
}
Block block = loc.getBlock();
block = block.getRelative(BlockFace.DOWN);
block.setType(Material.CHEST);
Chest chest = (Chest) block.getState();
block = block.getRelative(BlockFace.NORTH);
block.setType(Material.CHEST);
for (ItemStack item : event.getDrops()) {
if (item == null || item.getType() == Material.AIR) {
continue;
}
chest.getInventory().addItem(item);
}
event.getDrops().clear();
final ArmorStand stand = player.getWorld().spawn(chest.getLocation().clone().add(0.5, 1, 0), ArmorStand.class);
stand.setCustomNameVisible(true);
stand.setSmall(true);
stand.setGravity(false);
stand.setVisible(false);
stand.setMarker(true);
new BukkitRunnable() {
private int time = settings.getConfig().getInt("time", 30) + 1; // add one for countdown.
public void run() {
time
if (time == 0) {
plugin.broadcast(Main.PREFIX + "§a" + player.getName() + "'s §fcorpse has exploded!");
loc.getBlock().setType(Material.AIR);
loc.getWorld().createExplosion(loc.getBlockX() + 0.5, loc.getBlockY() + 0.5, loc.getBlockZ() + 0.5, settings.getConfig().getInt("explosion force", 10), false, true);
loc.getWorld().strikeLightning(loc); // Using actual lightning to kill the items.
stand.remove();
cancel();
return;
}
else if (time == 1) {
stand.setCustomName("§4" + time + "s");
}
else if (time == 2) {
stand.setCustomName("§c" + time + "s");
}
else if (time == 3) {
stand.setCustomName("§6" + time + "s");
}
else if (time <= 15) {
stand.setCustomName("§e" + time + "s");
}
else {
stand.setCustomName("§a" + time + "s");
}
}
}.runTaskTimer(plugin, 0, 20);
}
} |
package com.opencms.file.genericSql;
import javax.servlet.http.*;
import java.util.*;
import java.net.*;
import java.io.*;
import source.org.apache.java.io.*;
import source.org.apache.java.util.*;
import com.opencms.boot.CmsClassLoader;
import com.opencms.boot.CmsBase;
import com.opencms.core.*;
import com.opencms.file.*;
import com.opencms.template.*;
import java.sql.SQLException;
public class CmsResourceBroker implements I_CmsResourceBroker, I_CmsConstants {
//create a compare class to be used in the vector.
class Resource {
private String path = null;
public Resource(String path) {
this.path = path;
}
public boolean equals(Object obj) {
return ( (obj instanceof CmsResource) && path.equals( ((CmsResource) obj).getAbsolutePath() ));
}
}
/**
* Constant to count the file-system changes.
*/
protected long m_fileSystemChanges = 0;
/**
* Constant to count the file-system changes if Folders are involved.
*/
protected long m_fileSystemFolderChanges = 0;
/**
* Hashtable with resource-types.
*/
protected Hashtable m_resourceTypes = null;
/**
* The configuration of the property-file.
*/
protected Configurations m_configuration = null;
/**
* The access-module.
*/
protected CmsDbAccess m_dbAccess = null;
/**
* The Registry
*/
protected I_CmsRegistry m_registry = null;
/**
* Define the caches
*/
protected CmsCache m_userCache = null;
protected CmsCache m_groupCache = null;
protected CmsCache m_usergroupsCache = null;
//protected CmsCache m_resourceCache = null;
protected CmsResourceCache m_resourceCache = null;
protected CmsCache m_subresCache = null;
protected CmsCache m_projectCache = null;
protected CmsCache m_onlineProjectCache = null;
protected CmsCache m_propertyCache = null;
protected CmsCache m_propertyDefCache = null;
protected CmsCache m_propertyDefVectorCache = null;
protected CmsCache m_accessCache = null;
protected int m_cachelimit = 0;
protected String m_refresh = null;
/**
* backup published resources for history
*/
protected boolean m_enableHistory = true;
/**
* Accept a task from the Cms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task to accept.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void acceptTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException
{
CmsTask task = m_dbAccess.readTask(taskId);
task.setPercentage(1);
task = m_dbAccess.writeTask(task);
m_dbAccess.writeSystemTaskLog(taskId, "Task was accepted from " + currentUser.getFirstname() + " " + currentUser.getLastname() + ".");
}
/**
* Checks, if the user may create this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user has access, or not.
*/
public boolean accessCreate(CmsUser currentUser, CmsProject currentProject,
CmsResource resource) throws CmsException {
// check, if this is the onlineproject
if(onlineProject(currentUser, currentProject).equals(currentProject)){
// the online-project is not writeable!
return(false);
}
// check the access to the project
if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) {
// no access to the project!
return(false);
}
// check if the resource belongs to the current project
if(resource.getProjectId() != currentProject.getId()) {
return false;
}
// check the rights for the current resource
if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) ||
accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) ||
accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) {
// no write access to this resource!
return false;
}
// read the parent folder
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
} else {
// no parent folder!
return true;
}
// check the rights and if the resource is not locked
do {
if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) ||
accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) ||
accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) {
// is the resource locked?
if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) {
// resource locked by anopther user, no creation allowed
return(false);
}
// read next resource
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
}
} else {
// last check was negative
return(false);
}
} while(resource.getParent() != null);
// all checks are done positive
return(true);
}
/**
* Checks, if the user may create this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user has access, or not.
*/
public boolean accessCreate(CmsUser currentUser, CmsProject currentProject,
String resourceName) throws CmsException {
CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName);
return accessCreate(currentUser, currentProject, resource);
}
/**
* Checks, if the group may access this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
* @param flags The flags to check.
*
* @return wether the user has access, or not.
*/
protected boolean accessGroup(CmsUser currentUser, CmsProject currentProject,
CmsResource resource, int flags)
throws CmsException {
// is the user in the group for the resource?
if(userInGroup(currentUser, currentProject, currentUser.getName(),
readGroup(currentUser, currentProject,
resource).getName())) {
if( (resource.getAccessFlags() & flags) == flags ) {
return true;
}
}
// the resource isn't accesible by the user.
return false;
}
/**
* Checks, if the user may lock this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user may lock this resource, or not.
*/
public boolean accessLock(CmsUser currentUser, CmsProject currentProject,
CmsResource resource) throws CmsException {
// check, if this is the onlineproject
if(onlineProject(currentUser, currentProject).equals(currentProject)){
// the online-project is not writeable!
return(false);
}
// check the access to the project
if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) {
// no access to the project!
return(false);
}
// check if the resource belongs to the current project
if(resource.getProjectId() != currentProject.getId()) {
return false;
}
// read the parent folder
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
} else {
// no parent folder!
return true;
}
// check the rights and if the resource is not locked
do {
// is the resource locked?
if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ||
resource.getLockedInProject() != currentProject.getId()) ) {
// resource locked by anopther user, no creation allowed
return(false);
}
// read next resource
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
}
} while(resource.getParent() != null);
// all checks are done positive
return(true);
}
/**
* Checks, if the user may lock this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user may lock this resource, or not.
*/
public boolean accessLock(CmsUser currentUser, CmsProject currentProject,
String resourceName) throws CmsException {
CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName);
return accessLock(currentUser,currentProject,resource);
}
/**
* Checks, if others may access this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
* @param flags The flags to check.
*
* @return wether the user has access, or not.
*/
protected boolean accessOther(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException
{
if ((resource.getAccessFlags() & flags) == flags)
{
return true;
}
else
{
return false;
}
}
/**
* Checks, if the owner may access this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
* @param flags The flags to check.
*
* @return wether the user has access, or not.
*/
protected boolean accessOwner(CmsUser currentUser, CmsProject currentProject,
CmsResource resource, int flags)
throws CmsException {
// The Admin has always access
if( isAdmin(currentUser, currentProject) ) {
return(true);
}
// is the resource owned by this user?
if(resource.getOwnerId() == currentUser.getId()) {
if( (resource.getAccessFlags() & flags) == flags ) {
return true ;
}
}
// the resource isn't accesible by the user.
return false;
}
// Methods working with projects
/**
* Tests if the user can access the project.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId the id of the project.
* @return true, if the user has access, else returns false.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public boolean accessProject(CmsUser currentUser, CmsProject currentProject,
int projectId)
throws CmsException {
CmsProject testProject = readProject(currentUser, currentProject, projectId);
if (projectId==C_PROJECT_ONLINE_ID) {
return true;
}
// is the project unlocked?
if( testProject.getFlags() != C_PROJECT_STATE_UNLOCKED ) {
return(false);
}
// is the current-user admin, or the owner of the project?
if( (currentProject.getOwnerId() == currentUser.getId()) ||
isAdmin(currentUser, currentProject) ) {
return(true);
}
// get all groups of the user
Vector groups = getGroupsOfUser(currentUser, currentProject,
currentUser.getName());
// test, if the user is in the same groups like the project.
for(int i = 0; i < groups.size(); i++) {
int groupId = ((CmsGroup) groups.elementAt(i)).getId();
if( ( groupId == testProject.getGroupId() ) ||
( groupId == testProject.getManagerGroupId() ) ) {
return( true );
}
}
return( false );
}
/**
* Checks, if the user may read this resource.
* NOTE: If the ressource is in the project you never have to fallback.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return weather the user has access, or not.
*/
public boolean accessRead(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException
{
Boolean access=(Boolean)m_accessCache.get(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName());
if (access != null) {
return access.booleanValue();
} else {
if ((resource == null) || !accessProject(currentUser, currentProject, resource.getProjectId()) ||
(!accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ))) {
m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName(),new Boolean(false));
return false;
}
// check the rights for all
CmsResource res = resource; // save the original resource name to be used if an error occurs.
while (res.getParent() != null)
{
// readFolder without checking access
res = m_dbAccess.readFolder(currentProject.getId(), res.getParent());
if (res == null)
{
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(A_OpenCms.C_OPENCMS_DEBUG, "Resource has no parent: " + resource.getAbsolutePath());
}
throw new CmsException(this.getClass().getName() + ".accessRead(): Cannot find \'" + resource.getName(), CmsException.C_NOT_FOUND);
}
if (!accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ)) {
m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName(),new Boolean(false));
return false;
}
}
m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName(),new Boolean(true));
return true;
}
}
/**
* Checks, if the user may read this resource.
* NOTE: If the ressource is in the project you never have to fallback.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return weather the user has access, or not.
*/
public boolean accessRead(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException {
CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName);
return accessRead(currentUser, currentProject, resource);
}
/**
* Checks, if the user may unlock this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user may unlock this resource, or not.
*/
public boolean accessUnlock(CmsUser currentUser, CmsProject currentProject,
CmsResource resource)
throws CmsException {
// check, if this is the onlineproject
if(onlineProject(currentUser, currentProject).equals(currentProject)){
// the online-project is not writeable!
return(false);
}
// check the access to the project
if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) {
// no access to the project!
return(false);
}
// check if the resource belongs to the current project
if(resource.getProjectId() != currentProject.getId()) {
return false;
}
// read the parent folder
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
} else {
// no parent folder!
return true;
}
// check if the resource is not locked
do {
// is the resource locked?
if( resource.isLocked() ) {
// resource locked by anopther user, no creation allowed
return(false);
}
// read next resource
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
}
} while(resource.getParent() != null);
// all checks are done positive
return(true);
}
/**
* Checks, if the user may write this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user has access, or not.
*/
public boolean accessWrite(CmsUser currentUser, CmsProject currentProject,
CmsResource resource) throws CmsException {
// check, if this is the onlineproject
if(onlineProject(currentUser, currentProject).equals(currentProject)){
// the online-project is not writeable!
return(false);
}
// check the access to the project
if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) {
// no access to the project!
return(false);
}
// check if the resource belongs to the current project
if(resource.getProjectId() != currentProject.getId()) {
return false;
}
// check, if the resource is locked by the current user
if(resource.isLockedBy() != currentUser.getId()) {
// resource is not locked by the current user, no writing allowed
return(false);
} else {
//check if the project that has locked the resource is the current project
if((resource.getLockedInProject() != currentProject.getId())){
return (false);
}
}
// check the rights for the current resource
if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) ||
accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) ||
accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) {
// no write access to this resource!
return false;
}
// read the parent folder
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
} else {
// no parent folder!
return true;
}
// check the rights and if the resource is not locked
// for parent folders only read access is needed
do {
if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) ||
accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) ||
accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) {
// is the resource locked?
if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) {
// resource locked by anopther user, no creation allowed
return(false);
}
// read next resource
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
}
} else {
// last check was negative
return(false);
}
} while(resource.getParent() != null);
// all checks are done positive
return(true);
}
/**
* Checks, if the user may write this resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user has access, or not.
*/
public boolean accessWrite(CmsUser currentUser, CmsProject currentProject,
String resourceName) throws CmsException {
CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName);
return accessWrite(currentUser,currentProject,resource);
}
/**
* Checks, if the user may write the unlocked resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The resource to check.
*
* @return wether the user has access, or not.
*/
public boolean accessWriteUnlocked(CmsUser currentUser, CmsProject currentProject,
CmsResource resource) throws CmsException {
// check, if this is the onlineproject
if(onlineProject(currentUser, currentProject).equals(currentProject)){
// the online-project is not writeable!
return(false);
}
// check the access to the project
if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) {
// no access to the project!
return(false);
}
// check if the resource belongs to the current project
if(resource.getProjectId() != currentProject.getId()) {
return false;
}
// check the rights for the current resource
if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) ||
accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) ||
accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) {
// no write access to this resource!
return false;
}
// read the parent folder
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
} else {
// no parent folder!
return true;
}
// check the rights and if the resource is not locked
// for parent folders only read access is needed
do {
if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) ||
accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) ||
accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ) ) {
// is the resource locked?
if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) {
// resource locked by anopther user, no creation allowed
return(false);
}
// read next resource
if(resource.getParent() != null) {
// readFolder without checking access
resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent());
}
} else {
// last check was negative
return(false);
}
} while(resource.getParent() != null);
// all checks are done positive
return(true);
}
/**
* adds a file extension to the list of known file extensions
*
* <B>Security:</B>
* Users, which are in the group "administrators" are granted.<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param extension a file extension like 'html'
* @param resTypeName name of the resource type associated to the extension
*/
public void addFileExtension(CmsUser currentUser, CmsProject currentProject,
String extension, String resTypeName)
throws CmsException {
if (extension != null && resTypeName != null) {
if (isAdmin(currentUser, currentProject)) {
Hashtable suffixes=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS);
if (suffixes == null) {
suffixes = new Hashtable();
suffixes.put(extension, resTypeName);
m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes);
} else {
suffixes.put(extension, resTypeName);
m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + extension,
CmsException.C_NO_ACCESS);
}
}
}
/**
* Add a new group to the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the new group.
* @param description The description for the new group.
* @int flags The flags for the new group.
* @param name The name of the parent group (or null).
*
* @return Group
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public CmsGroup addGroup(CmsUser currentUser, CmsProject currentProject,
String name, String description, int flags, String parent)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
name = name.trim();
validFilename(name);
// check the lenght of the groupname
if(name.length() > 1) {
return( m_dbAccess.createGroup(name, description, flags, parent) );
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NO_ACCESS);
}
}
/**
* Adds a user to the Cms.
*
* Only a adminstrator can add users to the cms.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The new name for the user.
* @param password The new password for the user.
* @param group The default groupname for the user.
* @param description The description for the user.
* @param additionalInfos A Hashtable with additional infos for the user. These
* Infos may be stored into the Usertables (depending on the implementation).
* @param flags The flags for a user (e.g. C_FLAG_ENABLED)
*
* @return user The added user will be returned.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public CmsUser addUser(CmsUser currentUser, CmsProject currentProject, String name,
String password, String group, String description,
Hashtable additionalInfos, int flags)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password minimumsize
if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) {
CmsGroup defaultGroup = readGroup(currentUser, currentProject, group);
CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_SYSTEMUSER);
addUserToGroup(currentUser, currentProject, newUser.getName(),defaultGroup.getName());
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_SHORT_PASSWORD);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NO_ACCESS);
}
}
/**
* Adds a user to the Cms.
*
* Only a adminstrator can add users to the cms.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name for the user.
* @param password The password for the user.
* @param recoveryPassword The recoveryPassword for the user.
* @param description The description for the user.
* @param firstname The firstname of the user.
* @param lastname The lastname of the user.
* @param email The email of the user.
* @param flags The flags for a user (e.g. C_FLAG_ENABLED)
* @param additionalInfos A Hashtable with additional infos for the user. These
* Infos may be stored into the Usertables (depending on the implementation).
* @param defaultGroup The default groupname for the user.
* @param address The address of the user
* @param section The section of the user
* @param type The type of the user
*
* @return user The added user will be returned.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public CmsUser addImportUser(CmsUser currentUser, CmsProject currentProject,
String name, String password, String recoveryPassword, String description,
String firstname, String lastname, String email, int flags, Hashtable additionalInfos,
String defaultGroup, String address, String section, int type)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
CmsGroup group = readGroup(currentUser, currentProject, defaultGroup);
CmsUser newUser = m_dbAccess.addImportUser(name, password, recoveryPassword, description, firstname, lastname, email, 0, 0, flags, additionalInfos, group, address, section, type);
addUserToGroup(currentUser, currentProject, newUser.getName(), group.getName());
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NO_ACCESS);
}
}
/**
* Adds a user to a group.<BR/>
*
* Only the admin can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user that is to be added to the group.
* @param groupname The name of the group.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void addUserToGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException {
if (!userInGroup(currentUser, currentProject, username, groupname)) {
// Check the security
if (isAdmin(currentUser, currentProject)) {
CmsUser user;
CmsGroup group;
user = readUser(currentUser, currentProject, username);
//check if the user exists
if (user != null) {
group = readGroup(currentUser, currentProject, groupname);
//check if group exists
if (group != null) {
//add this user to the group
m_dbAccess.addUserToGroup(user.getId(), group.getId());
// update the cache
m_usergroupsCache.clear();
} else {
throw new CmsException("[" + this.getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "]" + username, CmsException.C_NO_USER);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS);
}
}
}
/**
* Adds a web user to the Cms. <br>
*
* A web user has no access to the workplace but is able to access personalized
* functions controlled by the OpenCms.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The new name for the user.
* @param password The new password for the user.
* @param group The default groupname for the user.
* @param description The description for the user.
* @param additionalInfos A Hashtable with additional infos for the user. These
* Infos may be stored into the Usertables (depending on the implementation).
* @param flags The flags for a user (e.g. C_FLAG_ENABLED)
*
* @return user The added user will be returned.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public CmsUser addWebUser(CmsUser currentUser, CmsProject currentProject,
String name, String password,
String group, String description,
Hashtable additionalInfos, int flags)
throws CmsException {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password minimumsize
if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) {
CmsGroup defaultGroup = readGroup(currentUser, currentProject, group);
CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_WEBUSER);
CmsUser user;
CmsGroup usergroup;
user=m_dbAccess.readUser(newUser.getName(),C_USER_TYPE_WEBUSER);
//check if the user exists
if (user != null) {
usergroup=readGroup(currentUser,currentProject,group);
//check if group exists
if (usergroup != null){
//add this user to the group
m_dbAccess.addUserToGroup(user.getId(),usergroup.getId());
// update the cache
m_usergroupsCache.clear();
} else {
throw new CmsException("["+this.getClass().getName()+"]"+group,CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER);
}
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_SHORT_PASSWORD);
}
}
/**
* Returns the anonymous user object.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return the anonymous user object.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser anonymousUser(CmsUser currentUser, CmsProject currentProject) throws CmsException
{
return readUser(currentUser, currentProject, C_USER_GUEST);
}
/**
* Changes the group for this resource<br>
*
* Only the group of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The complete path to the resource.
* @param newGroup The name of the new group for this resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void chgrp(CmsUser currentUser, CmsProject currentProject,
String filename, String newGroup)
throws CmsException {
CmsResource resource=null;
// read the resource to check the access
if (filename.endsWith("/")) {
resource = readFolder(currentUser,currentProject,filename);
} else {
resource = (CmsFile)readFileHeader(currentUser,currentProject,filename);
}
// has the user write-access? and is he owner or admin?
if( accessWrite(currentUser, currentProject, resource) &&
( (resource.getOwnerId() == currentUser.getId()) ||
isAdmin(currentUser, currentProject))) {
CmsGroup group = readGroup(currentUser, currentProject, newGroup);
resource.setGroupId(group.getId());
// write-acces was granted - write the file.
if (filename.endsWith("/")) {
if (resource.getState()==C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true);
// update the cache
m_resourceCache.remove(filename);
} else {
m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true);
if (resource.getState()==C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
// update the cache
m_resourceCache.remove(filename);
}
m_subresCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the flags for this resource.<br>
*
* Only the flags of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change the flags, if he is admin of the resource <br>.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The complete path to the resource.
* @param flags The new accessflags for the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void chmod(CmsUser currentUser, CmsProject currentProject,
String filename, int flags)
throws CmsException {
CmsResource resource=null;
// read the resource to check the access
if (filename.endsWith("/")) {
resource = readFolder(currentUser,currentProject,filename);
} else {
resource = (CmsFile)readFileHeader(currentUser,currentProject,filename);
}
// has the user write-access?
if( accessWrite(currentUser, currentProject, resource)||
((resource.isLockedBy() == currentUser.getId() &&
resource.getLockedInProject() == currentProject.getId()) &&
(resource.getOwnerId() == currentUser.getId()||isAdmin(currentUser, currentProject))) ) {
// write-acces was granted - write the file.
//set the flags
resource.setAccessFlags(flags);
//update file
if (filename.endsWith("/")) {
if (resource.getState()==C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true);
// update the cache
m_resourceCache.remove(filename);
} else {
m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true);
if (resource.getState()==C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
// update the cache
m_resourceCache.remove(filename);
}
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the owner for this resource.<br>
*
* Only the owner of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource. <br>
*
* <B>Security:</B>
* Access is cranted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or the user is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The complete path to the resource.
* @param newOwner The name of the new owner for this resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void chown(CmsUser currentUser, CmsProject currentProject, String filename, String newOwner) throws CmsException {
CmsResource resource = null;
// read the resource to check the access
if (filename.endsWith("/")) {
resource = readFolder(currentUser, currentProject, filename);
} else {
resource = (CmsFile) readFileHeader(currentUser, currentProject, filename);
}
// has the user write-access? and is he owner or admin?
if (((resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject)) &&
(resource.isLockedBy() == currentUser.getId() &&
resource.getLockedInProject() == currentProject.getId())) {
CmsUser owner = readUser(currentUser, currentProject, newOwner);
resource.setUserId(owner.getId());
// write-acces was granted - write the file.
if (filename.endsWith("/")) {
if (resource.getState() == C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
m_dbAccess.writeFolder(currentProject, (CmsFolder) resource, true);
// update the cache
m_resourceCache.remove(filename);
} else {
m_dbAccess.writeFileHeader(currentProject, (CmsFile) resource, true);
if (resource.getState() == C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
// update the cache
m_resourceCache.remove(filename);
}
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS);
}
}
/**
* Changes the state for this resource<BR/>
*
* The user may change this, if he is admin of the resource.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param filename The complete path to the resource.
* @param state The new state of this resource.
*
* @exception CmsException will be thrown, if the user has not the rights
* for this resource.
*/
public void chstate(CmsUser currentUser, CmsProject currentProject,
String filename, int state)
throws CmsException {
boolean isFolder=false;
CmsResource resource=null;
// read the resource to check the access
if (filename.endsWith("/")) {
isFolder=true;
resource = readFolder(currentUser,currentProject,filename);
} else {
resource = (CmsFile)readFileHeader(currentUser,currentProject,filename);
}
// has the user write-access?
if( accessWrite(currentUser, currentProject, resource)) {
resource.setState(state);
// write-acces was granted - write the file.
if (filename.endsWith("/")) {
m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false);
// update the cache
m_resourceCache.remove(filename);
} else {
m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false);
// update the cache
m_resourceCache.remove(filename);
}
m_subresCache.clear();
// inform about the file-system-change
fileSystemChanged(isFolder);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the resourcetype for this resource<br>
*
* Only the resourcetype of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The complete path to the resource.
* @param newType The name of the new resourcetype for this resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void chtype(CmsUser currentUser, CmsProject currentProject,
String filename, String newType)
throws CmsException {
I_CmsResourceType type = getResourceType(currentUser, currentProject, newType);
// read the resource to check the access
CmsResource resource = readFileHeader(currentUser,currentProject, filename);
// has the user write-access? and is he owner or admin?
if( accessWrite(currentUser, currentProject, resource) &&
( (resource.getOwnerId() == currentUser.getId()) ||
isAdmin(currentUser, currentProject))) {
// write-acces was granted - write the file.
resource.setType(type.getResourceType());
resource.setLauncherType(type.getLauncherType());
m_dbAccess.writeFileHeader(currentProject, (CmsFile)resource,true);
if (resource.getState()==C_STATE_UNCHANGED) {
resource.setState(C_STATE_CHANGED);
}
// update the cache
m_resourceCache.remove(filename);
m_subresCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Clears all internal DB-Caches.
*/
public void clearcache() {
m_userCache.clear();
m_groupCache.clear();
m_usergroupsCache.clear();
m_projectCache.clear();
m_resourceCache.clear();
m_subresCache.clear();
m_propertyCache.clear();
m_propertyDefCache.clear();
m_propertyDefVectorCache.clear();
m_onlineProjectCache.clear();
m_accessCache.clear();
CmsTemplateClassManager.clearCache();
}
/**
* Copies a file in the Cms. <br>
*
* <B>Security:</B>
* Access is cranted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the sourceresource</li>
* <li>the user can create the destinationresource</li>
* <li>the destinationresource dosn't exists</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param source The complete path of the sourcefile.
* @param destination The complete path to the destination.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyFile(CmsUser currentUser, CmsProject currentProject,
String source, String destination)
throws CmsException {
// the name of the new file.
String filename;
// the name of the folder.
String foldername;
// checks, if the destinateion is valid, if not it throws a exception
validFilename(destination.replace('/', 'a'));
// read the source-file, to check readaccess
CmsResource file = readFileHeader(currentUser, currentProject, source);
// split the destination into file and foldername
if (destination.endsWith("/")) {
filename = file.getName();
foldername = destination;
}else{
foldername = destination.substring(0, destination.lastIndexOf("/")+1);
filename = destination.substring(destination.lastIndexOf("/")+1,
destination.length());
}
CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername);
if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) {
if(( accessOther(currentUser, currentProject, file, C_ACCESS_PUBLIC_WRITE) ||
accessOwner(currentUser, currentProject, file, C_ACCESS_OWNER_WRITE) ||
accessGroup(currentUser, currentProject, file, C_ACCESS_GROUP_WRITE) )){
// write-acces was granted - copy the file and the metainfos
m_dbAccess.copyFile(currentProject, onlineProject(currentUser, currentProject),
currentUser.getId(),source,cmsFolder.getResourceId(), foldername + filename);
// copy the metainfos
lockResource(currentUser, currentProject, destination, true);
writeProperties(currentUser,currentProject, destination,
readAllProperties(currentUser,currentProject,file.getAbsolutePath()));
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(file.isFolder());
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + source,
CmsException.C_NO_ACCESS);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + destination,
CmsException.C_NO_ACCESS);
}
}
/**
* Copies a folder in the Cms. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the sourceresource</li>
* <li>the user can create the destinationresource</li>
* <li>the destinationresource dosn't exists</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param source The complete path of the sourcefolder.
* @param destination The complete path to the destination.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyFolder(CmsUser currentUser, CmsProject currentProject,
String source, String destination)
throws CmsException {
// the name of the new file.
String filename;
// the name of the folder.
String foldername;
// checks, if the destinateion is valid, if not it throws a exception
validFilename(destination.replace('/', 'a'));
foldername = destination.substring(0, destination.substring(0,destination.length()-1).lastIndexOf("/")+1);
CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername);
if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) {
// write-acces was granted - copy the folder and the properties
CmsFolder folder=readFolder(currentUser,currentProject,source);
// check write access to the folder that has to be copied
if(( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_WRITE) ||
accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_WRITE) ||
accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_WRITE) )){
m_dbAccess.createFolder(currentUser,currentProject,onlineProject(currentUser, currentProject),folder,cmsFolder.getResourceId(),destination);
// copy the properties
lockResource(currentUser, currentProject, destination, true);
writeProperties(currentUser,currentProject, destination,
readAllProperties(currentUser,currentProject,folder.getAbsolutePath()));
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(true);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + source,
CmsException.C_ACCESS_DENIED);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + destination,
CmsException.C_ACCESS_DENIED);
}
}
/**
* Copies a resource from the online project to a new, specified project.<br>
* Copying a resource will copy the file header or folder into the specified
* offline project and set its state to UNCHANGED.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user is the owner of the project</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyResourceToProject(CmsUser currentUser,
CmsProject currentProject,
String resource)
throws CmsException {
// read the onlineproject
CmsProject online = onlineProject(currentUser, currentProject);
// is the current project the onlineproject?
// and is the current user the owner of the project?
// and is the current project state UNLOCKED?
if ((!currentProject.equals(online)) && (currentProject.getOwnerId() == currentUser.getId()) && (currentProject.getFlags() == C_PROJECT_STATE_UNLOCKED)) {
// is offlineproject and is owner
// try to read the resource from the offline project, include deleted
CmsResource offlineRes = null;
try{
if(resource.endsWith("/")){
m_resourceCache.remove(resource);
} else {
m_resourceCache.remove(resource);
}
offlineRes = readFileHeader(currentUser, currentProject, currentProject.getId(),resource);
} catch (CmsException exc){
// if the resource does not exist in the offlineProject - it's ok
}
// create the projectresource only if the resource is not in the current project
if ((offlineRes == null) || (offlineRes.getProjectId() != currentProject.getId())){
// check if there are already any subfolders of this resource
if(resource.endsWith("/")){
Vector projectResources = m_dbAccess.readAllProjectResources(currentProject.getId());
for(int i=0; i<projectResources.size(); i++){
String resname = (String)projectResources.elementAt(i);
if(resname.startsWith(resource)){
// delete the existing project resource first
m_dbAccess.deleteProjectResource(currentProject.getId(), resname);
}
}
}
try {
m_dbAccess.createProjectResource(currentProject.getId(), resource);
} catch (CmsException exc) {
// if the subfolder exists already - all is ok
}
}
} else {
// no changes on the onlineproject!
throw new CmsException("[" + this.getClass().getName() + "] " + currentProject.getName(), CmsException.C_NO_ACCESS);
}
}
/**
* Counts the locked resources in this project.
*
* <B>Security</B>
* Only the admin or the owner of the project can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id of the project
* @return the amount of locked resources in this project.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public int countLockedResources(CmsUser currentUser, CmsProject currentProject, int id)
throws CmsException {
// read the project.
CmsProject project = readProject(currentUser, currentProject, id);
// check the security
if( isAdmin(currentUser, currentProject) ||
isManagerOfProject(currentUser, project) ||
(project.getFlags() == C_PROJECT_STATE_UNLOCKED )) {
// count locks
return m_dbAccess.countLockedResources(project);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + id,
CmsException.C_NO_ACCESS);
}
}
public com.opencms.file.genericSql.CmsDbAccess createDbAccess(Configurations configurations) throws CmsException
{
return new com.opencms.file.genericSql.CmsDbAccess(configurations);
}
/**
* Creates a new file with the given content and resourcetype. <br>
*
* Files can only be created in an offline project, the state of the new file
* is set to NEW (2). <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the folder-resource is not locked by another user</li>
* <li>the file dosn't exists</li>
* </ul>
*
* @param currentUser The user who owns this file.
* @param currentGroup The group who owns this file.
* @param currentProject The project in which the resource will be used.
* @param folder The complete path to the folder in which the new folder will
* be created.
* @param file The name of the new file (No pathinformation allowed).
* @param contents The contents of the new file.
* @param type The name of the resourcetype of the new file.
* @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder.
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos.
* @return file The created file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFile createFile(CmsUser currentUser, CmsGroup currentGroup,
CmsProject currentProject, String folder,
String filename, byte[] contents, String type,
Hashtable propertyinfos)
throws CmsException {
// checks, if the filename is valid, if not it throws a exception
validFilename(filename);
CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder);
if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) {
// write-access was granted - create and return the file.
CmsFile file = m_dbAccess.createFile(currentUser, currentProject,
onlineProject(currentUser, currentProject),
folder + filename, 0, cmsFolder.getResourceId(),
contents,
getResourceType(currentUser, currentProject, type));
// update the access flags
Hashtable startSettings=null;
Integer accessFlags=null;
startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS);
if (startSettings != null) {
accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS);
if (accessFlags != null) {
file.setAccessFlags(accessFlags.intValue());
}
}
if(currentGroup != null) {
file.setGroupId(currentGroup.getId());
}
m_dbAccess.writeFileHeader(currentProject, file,false);
m_subresCache.clear();
// write the metainfos
m_dbAccess.writeProperties(propertyinfos, currentProject.getId(),file, file.getType());
// inform about the file-system-change
fileSystemChanged(false);
return file ;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + folder + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Creates a new folder.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is not locked by another user</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentGroup The group who requested this method.
* @param currentProject The current project of the user.
* @param folder The complete path to the folder in which the new folder will
* be created.
* @param newFolderName The name of the new folder (No pathinformation allowed).
* @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder.
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos.
*
* @return file The created file.
*
* @exception CmsException will be thrown for missing propertyinfos, for worng propertydefs
* or if the filename is not valid. The CmsException will also be thrown, if the
* user has not the rights for this resource.
*/
public CmsFolder createFolder(CmsUser currentUser, CmsGroup currentGroup,
CmsProject currentProject,
String folder, String newFolderName,
Hashtable propertyinfos)
throws CmsException {
// checks, if the filename is valid, if not it throws a exception
validFilename(newFolderName);
CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder);
if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) {
// write-acces was granted - create the folder.
CmsFolder newFolder = m_dbAccess.createFolder(currentUser, currentProject,
cmsFolder.getResourceId(),
C_UNKNOWN_ID,
folder + newFolderName +
C_FOLDER_SEPERATOR,
0);
// update the access flags
Hashtable startSettings=null;
Integer accessFlags=null;
startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS);
if (startSettings != null) {
accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS);
if (accessFlags != null) {
newFolder.setAccessFlags(accessFlags.intValue());
}
}
if(currentGroup != null) {
newFolder.setGroupId(currentGroup.getId());
}
newFolder.setState(C_STATE_NEW);
m_dbAccess.writeFolder(currentProject, newFolder, false);
m_subresCache.clear();
// write metainfos for the folder
m_dbAccess.writeProperties(propertyinfos, currentProject.getId(), newFolder, newFolder.getType());
// inform about the file-system-change
fileSystemChanged(true);
// return the folder
return newFolder ;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + folder + newFolderName,
CmsException.C_NO_ACCESS);
}
}
/**
* Creates a project.
*
* <B>Security</B>
* Only the users which are in the admin or projectleader-group are granted.
*
* Changed: added the parent id
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the project to read.
* @param description The description for the new project.
* @param group the group to be set.
* @param managergroup the managergroup to be set.
* @param parentId the parent project
* @exception CmsException Throws CmsException if something goes wrong.
* @author Martin Langelund
*/
public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname) throws CmsException
{
if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject))
{
if (C_PROJECT_ONLINE.equals(name)){
throw new CmsException ("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// read the needed groups from the cms
CmsGroup group = readGroup(currentUser, currentProject, groupname);
CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname);
// create a new task for the project
CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL);
return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, C_PROJECT_TYPE_NORMAL);
}
else
{
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS);
}
}
/**
* Creates a project.
*
* <B>Security</B>
* Only the users which are in the admin or projectleader-group are granted.
*
* Changed: added the project type
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the project to read.
* @param description The description for the new project.
* @param group the group to be set.
* @param managergroup the managergroup to be set.
* @param project type the type of the project
* @exception CmsException Throws CmsException if something goes wrong.
* @author Edna Falkenhan
*/
public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException
{
if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject))
{
if (C_PROJECT_ONLINE.equals(name)){
throw new CmsException ("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// read the needed groups from the cms
CmsGroup group = readGroup(currentUser, currentProject, groupname);
CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname);
// create a new task for the project
CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL);
return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, projecttype);
}
else
{
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS);
}
}
/**
* Creates a new project for task handling.
*
* @param currentUser User who creates the project
* @param projectName Name of the project
* @param projectType Type of the Project
* @param role Usergroup for the project
* @param timeout Time when the Project must finished
* @param priority Priority for the Project
*
* @return The new task project
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask createProject(CmsUser currentUser, String projectName,
int projectType, String roleName,
long timeout, int priority)
throws CmsException {
CmsGroup role = null;
// read the role
if(roleName!=null && !roleName.equals("")) {
role = readGroup(currentUser, null, roleName);
}
// create the timestamp
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
return m_dbAccess.createTask(0,0,
1, // standart project type,
currentUser.getId(),
currentUser.getId(),
role.getId(),
projectName,
now,
timestamp,
priority);
}
// Methods working with properties and propertydefinitions
/**
* Creates the propertydefinition for the resource type.<BR/>
*
* <B>Security</B>
* Only the admin can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the propertydefinition to overwrite.
* @param resourcetype The name of the resource-type for the propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition createPropertydefinition(CmsUser currentUser,
CmsProject currentProject,
String name,
String resourcetype)
throws CmsException {
// check the security
if( isAdmin(currentUser, currentProject) ) {
// no space before or after the name
name = name.trim();
// check the name
validFilename(name);
m_propertyDefVectorCache.clear();
return( m_dbAccess.createPropertydefinition(name,
getResourceType(currentUser,
currentProject,
resourcetype)) );
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NO_ACCESS);
}
}
public void createResource(CmsProject project, CmsProject onlineProject, CmsResource resource) throws com.opencms.core.CmsException
{
m_dbAccess.createResource(project, onlineProject, resource);
}
/**
* Creates a new task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param projectid The Id of the current project task of the user.
* @param agentName User who will edit the task
* @param roleName Usergroup for the task
* @param taskName Name of the task
* @param taskType Type of the task
* @param taskComment Description of the task
* @param timeout Time when the task must finished
* @param priority Id for the priority
*
* @return A new Task Object
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask createTask(CmsUser currentUser, int projectid,
String agentName, String roleName,
String taskName, String taskComment,
int taskType, long timeout, int priority)
throws CmsException {
CmsUser agent = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER);
CmsGroup role = m_dbAccess.readGroup(roleName);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
validTaskname(taskName); // check for valid Filename
CmsTask task = m_dbAccess.createTask(projectid,
projectid,
taskType,
currentUser.getId(),
agent.getId(),
role.getId(),
taskName, now, timestamp, priority);
if(taskComment!=null && !taskComment.equals("")) {
m_dbAccess.writeTaskLog(task.getId(), currentUser.getId(),
new java.sql.Timestamp(System.currentTimeMillis()),
taskComment, C_TASKLOG_USER);
}
return task;
}
/**
* Creates a new task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param agent Username who will edit the task
* @param role Usergroupname for the task
* @param taskname Name of the task
* @param taskcomment Description of the task.
* @param timeout Time when the task must finished
* @param priority Id for the priority
*
* @return A new Task Object
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask createTask(CmsUser currentUser, CmsProject currentProject,
String agentName, String roleName,
String taskname, String taskcomment,
long timeout, int priority)
throws CmsException {
CmsGroup role = m_dbAccess.readGroup(roleName);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
int agentId = C_UNKNOWN_ID;
validTaskname(taskname); // check for valid Filename
try {
agentId = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER).getId();
} catch (Exception e) {
// ignore that this user doesn't exist and create a task for the role
}
return m_dbAccess.createTask(currentProject.getTaskId(),
currentProject.getTaskId(),
1, // standart Task Type
currentUser.getId(),
agentId,
role.getId(),
taskname, now, timestamp, priority);
}
/**
* Deletes all propertyinformation for a file or folder.
*
* <B>Security</B>
* Only the user is granted, who has the right to write the resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource of which the propertyinformations
* have to be deleted.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteAllProperties(CmsUser currentUser,
CmsProject currentProject,
String resource)
throws CmsException {
// read the resource
CmsResource res = readFileHeader(currentUser,currentProject, resource);
// check the security
if( ! accessWrite(currentUser, currentProject, res) ) {
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_NO_ACCESS);
}
//delete all Properties
m_dbAccess.deleteAllProperties(currentProject.getId(),res);
m_propertyCache.clear();
}
/**
* Deletes a file in the Cms.<br>
*
* A file can only be deleteed in an offline project.
* A file is deleted by setting its state to DELETED (3). <br>
*
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callinUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The complete path of the file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFile(CmsUser currentUser, CmsProject currentProject,
String filename)
throws CmsException {
// read the file
CmsResource onlineFile;
CmsResource file = readFileHeader(currentUser,currentProject, filename);
try {
onlineFile = readFileHeader(currentUser,onlineProject(currentUser, currentProject), filename);
} catch (CmsException exc) {
// the file dosent exist
onlineFile = null;
}
// has the user write-access?
if( accessWrite(currentUser, currentProject, file) ) {
// write-acces was granted - delete the file.
// and the metainfos
if(onlineFile == null) {
// the onlinefile dosent exist => remove the file realy!
deleteAllProperties(currentUser,currentProject,file.getAbsolutePath());
m_dbAccess.removeFile(currentProject.getId(), filename);
} else {
m_dbAccess.deleteFile(currentProject, filename);
}
// update the cache
m_resourceCache.remove(filename);
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Deletes a folder in the Cms.<br>
*
* Only folders in an offline Project can be deleted. A folder is deleted by
* setting its state to DELETED (3). <br>
*
* In its current implmentation, this method can ONLY delete empty folders.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read and write this resource and all subresources</li>
* <li>the resource is not locked</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername The complete path of the folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFolder(CmsUser currentUser, CmsProject currentProject,
String foldername)
throws CmsException {
CmsResource onlineFolder;
// read the folder, that shold be deleted
CmsFolder cmsFolder = readFolder(currentUser,currentProject,foldername);
try {
onlineFolder = readFolder(currentUser,onlineProject(currentUser, currentProject), foldername);
} catch (CmsException exc) {
// the file dosent exist
onlineFolder = null;
}
// check, if the user may delete the resource
if( accessWrite(currentUser, currentProject, cmsFolder) ) {
// write-acces was granted - delete the folder and metainfos.
if(onlineFolder == null) {
// the onlinefile dosent exist => remove the file realy!
deleteAllProperties(currentUser,currentProject, cmsFolder.getAbsolutePath());
m_dbAccess.removeFolder(currentProject.getId(),cmsFolder);
} else {
m_dbAccess.deleteFolder(currentProject,cmsFolder, false);
}
// update cache
m_resourceCache.remove(foldername);
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(true);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + foldername,
CmsException.C_NO_ACCESS);
}
}
/**
* Undeletes a file in the Cms.<br>
*
* A file can only be undeleted in an offline project.
* A file is undeleted by setting its state to CHANGED (1). <br>
*
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callinUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The complete path of the file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void undeleteResource(CmsUser currentUser, CmsProject currentProject,
String filename)
throws CmsException {
boolean isFolder=false;
CmsResource resource=null;
int state = C_STATE_CHANGED;
// read the resource to check the access
if (filename.endsWith("/")) {
isFolder=true;
resource = m_dbAccess.readFolder(currentProject.getId(),filename);
} else {
resource = (CmsFile)m_dbAccess.readFileHeader(currentProject.getId(),filename, true);
}
// has the user write-access?
if( accessWriteUnlocked(currentUser, currentProject, resource)) {
resource.setState(state);
resource.setLocked(currentUser.getId());
// write-access was granted - write the file.
if (filename.endsWith("/")) {
m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false);
// update the cache
m_resourceCache.remove(filename);
} else {
m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false);
// update the cache
m_resourceCache.remove(filename);
}
m_subresCache.clear();
// inform about the file-system-change
fileSystemChanged(isFolder);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_NO_ACCESS);
}
}
/**
* Delete a group from the Cms.<BR/>
* Only groups that contain no subgroups can be deleted.
*
* Only the admin can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param delgroup The name of the group that is to be deleted.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void deleteGroup(CmsUser currentUser, CmsProject currentProject,
String delgroup)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
Vector childs=null;
Vector users=null;
// get all child groups of the group
childs=getChild(currentUser,currentProject,delgroup);
// get all users in this group
users=getUsersOfGroup(currentUser,currentProject,delgroup);
// delete group only if it has no childs and there are no users in this group.
if ((childs == null) && ((users == null) || (users.size() == 0))) {
m_dbAccess.deleteGroup(delgroup);
m_groupCache.remove(delgroup);
} else {
throw new CmsException(delgroup, CmsException.C_GROUP_NOT_EMPTY);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + delgroup,
CmsException.C_NO_ACCESS);
}
}
/**
* Deletes a project.
*
* <B>Security</B>
* Only the admin or the owner of the project can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id of the project to be published.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deleteProject(CmsUser currentUser, CmsProject currentProject,
int id)
throws CmsException {
Vector deletedFolders = new Vector();
// read the project that should be deleted.
CmsProject deleteProject = readProject(currentUser, currentProject, id);
if(isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, deleteProject)) {
Vector allFiles = m_dbAccess.readFiles(deleteProject.getId(), false, true);
Vector allFolders = m_dbAccess.readFolders(deleteProject.getId(), false, true);
// first delete files or undo changes in files
for(int i=0; i<allFiles.size();i++){
CmsFile currentFile = (CmsFile)allFiles.elementAt(i);
if(currentFile.getState() == C_STATE_NEW){
// delete the properties
m_dbAccess.deleteAllProperties(id, currentFile.getResourceId());
// delete the file
m_dbAccess.removeFile(id, currentFile.getAbsolutePath());
} else if (currentFile.getState() == C_STATE_CHANGED){
if(!currentFile.isLocked()){
// lock the resource
lockResource(currentUser,deleteProject,currentFile.getAbsolutePath(),true);
}
// undo all changes in the file
undoChanges(currentUser, deleteProject, currentFile.getAbsolutePath());
} else if (currentFile.getState() == C_STATE_DELETED){
// first undelete the file
undeleteResource(currentUser, deleteProject, currentFile.getAbsolutePath());
if(!currentFile.isLocked()){
// lock the resource
lockResource(currentUser,deleteProject,currentFile.getAbsolutePath(),true);
}
// then undo all changes in the file
undoChanges(currentUser, deleteProject, currentFile.getAbsolutePath());
}
}
// now delete folders or undo changes in folders
for(int i=0; i<allFolders.size();i++){
CmsFolder currentFolder = (CmsFolder)allFolders.elementAt(i);
if(currentFolder.getState() == C_STATE_NEW){
// delete the properties
m_dbAccess.deleteAllProperties(id, currentFolder.getResourceId());
// add the folder to the vector of folders that has to be deleted
deletedFolders.addElement(currentFolder);
} else if (currentFolder.getState() == C_STATE_CHANGED){
if(!currentFolder.isLocked()){
// lock the resource
lockResource(currentUser,deleteProject,currentFolder.getAbsolutePath(),true);
}
// undo all changes in the folder
undoChanges(currentUser, deleteProject, currentFolder.getAbsolutePath());
} else if (currentFolder.getState() == C_STATE_DELETED){
// undelete the folder
undeleteResource(currentUser, deleteProject, currentFolder.getAbsolutePath());
if(!currentFolder.isLocked()){
// lock the resource
lockResource(currentUser,deleteProject,currentFolder.getAbsolutePath(),true);
}
// then undo all changes in the folder
undoChanges(currentUser, deleteProject, currentFolder.getAbsolutePath());
}
}
// now delete the folders in the vector
for (int i = deletedFolders.size() - 1; i > -1; i
CmsFolder delFolder = ((CmsFolder) deletedFolders.elementAt(i));
m_dbAccess.removeFolder(id, delFolder);
}
// unlock all resources in the project
m_dbAccess.unlockProject(deleteProject);
m_resourceCache.clear();
//m_projectCache.clear();
// delete the project
m_dbAccess.deleteProject(deleteProject);
m_projectCache.remove(id);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + id,
CmsException.C_NO_ACCESS);
}
}
/**
* Deletes a propertyinformation for a file or folder.
*
* <B>Security</B>
* Only the user is granted, who has the right to write the resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource of which the propertyinformation
* has to be read.
* @param property The propertydefinition-name of which the propertyinformation has to be set.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteProperty(CmsUser currentUser, CmsProject currentProject,
String resource, String property)
throws CmsException {
// read the resource
CmsResource res = readFileHeader(currentUser,currentProject, resource);
// check the security
if( ! accessWrite(currentUser, currentProject, res) ) {
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_NO_ACCESS);
}
// read the metadefinition
I_CmsResourceType resType = getResourceType(currentUser,currentProject,res.getType());
CmsPropertydefinition metadef = readPropertydefinition(currentUser,currentProject,property, resType.getResourceTypeName());
if( (metadef != null) ) {
m_dbAccess.deleteProperty(property,currentProject.getId(),res,res.getType());
// set the file-state to changed
if(res.isFile()){
m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true);
if (res.getState()==C_STATE_UNCHANGED) {
res.setState(C_STATE_CHANGED);
}
// update the cache
//m_resourceCache.put(currentProject.getId()+C_FILE+resource,res);
m_resourceCache.remove(resource);
} else {
if (res.getState()==C_STATE_UNCHANGED) {
res.setState(C_STATE_CHANGED);
}
m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true);
// update the cache
//m_resourceCache.put(currentProject.getId()+C_FOLDER+resource,(CmsFolder)res);
m_resourceCache.remove(resource);
}
m_subresCache.clear();
m_propertyCache.clear();
} else {
// yes - throw exception
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_UNKNOWN_EXCEPTION);
}
}
/**
* Delete the propertydefinition for the resource type.<BR/>
*
* <B>Security</B>
* Only the admin can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the propertydefinition to read.
* @param resourcetype The name of the resource type for which the
* propertydefinition is valid.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deletePropertydefinition(CmsUser currentUser, CmsProject currentProject,
String name, String resourcetype)
throws CmsException {
// check the security
if( isAdmin(currentUser, currentProject) ) {
// first read and then delete the metadefinition.
m_propertyDefVectorCache.clear();
m_propertyDefCache.remove(name + (getResourceType(currentUser,currentProject,resourcetype)).getResourceType());
m_dbAccess.deletePropertydefinition(
readPropertydefinition(currentUser,currentProject,name,resourcetype));
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NO_ACCESS);
}
}
/**
* Deletes a user from the Cms.
*
* Only a adminstrator can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param userId The Id of the user to be deleted.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void deleteUser(CmsUser currentUser, CmsProject currentProject,
int userId)
throws CmsException {
CmsUser user = readUser(currentUser,currentProject,userId);
deleteUser(currentUser,currentProject,user.getName());
}
/**
* Deletes a user from the Cms.
*
* Only a adminstrator can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the user to be deleted.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void deleteUser(CmsUser currentUser, CmsProject currentProject,
String username)
throws CmsException {
// Test is this user is existing
CmsUser user=readUser(currentUser,currentProject,username);
// Check the security
// Avoid to delete admin or guest-user
if( isAdmin(currentUser, currentProject) &&
!(username.equals(C_USER_ADMIN) || username.equals(C_USER_GUEST))) {
m_dbAccess.deleteUser(username);
// delete user from cache
m_userCache.remove(username+user.getType());
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS);
}
}
/**
* Deletes a web user from the Cms.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param userId The Id of the user to be deleted.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void deleteWebUser(CmsUser currentUser, CmsProject currentProject,
int userId)
throws CmsException {
CmsUser user = readUser(currentUser,currentProject,userId);
m_dbAccess.deleteUser(user.getName());
// delete user from cache
m_userCache.remove(user.getName()+user.getType());
}
/**
* Destroys the resource broker and required modules and connections.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void destroy()
throws CmsException {
// destroy the db-access.
m_dbAccess.destroy();
}
/**
* Ends a task from the Cms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The ID of the task to end.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void endTask(CmsUser currentUser, CmsProject currentProject, int taskid)
throws CmsException {
m_dbAccess.endTask(taskid);
if(currentUser == null) {
m_dbAccess.writeSystemTaskLog(taskid, "Task finished.");
} else {
m_dbAccess.writeSystemTaskLog(taskid,
"Task finished by " +
currentUser.getFirstname() + " " +
currentUser.getLastname() + ".");
}
}
/**
* Exports cms-resources to zip.
*
* <B>Security:</B>
* only Administrators can do this;
*
* @param currentUser user who requestd themethod
* @param currentProject current project of the user
* @param exportFile the name (absolute Path) of the export resource (zip)
* @param exportPath the names (absolute Path) of folders and files which should be exported
* @param cms the cms-object to use for the export.
*
* @exception Throws CmsException if something goes wrong.
*/
public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms)
throws CmsException {
if(isAdmin(currentUser, currentProject)) {
new CmsExport(exportFile, exportPaths, cms);
} else {
throw new CmsException("[" + this.getClass().getName() + "] exportResources",
CmsException.C_NO_ACCESS);
}
}
/**
* Exports cms-resources to zip.
*
* <B>Security:</B>
* only Administrators can do this;
*
* @param currentUser user who requestd themethod
* @param currentProject current project of the user
* @param exportFile the name (absolute Path) of the export resource (zip)
* @param exportPath the name (absolute Path) of folder from which should be exported
* @param excludeSystem, decides whether to exclude the system
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded.
* @param cms the cms-object to use for the export.
*
* @exception Throws CmsException if something goes wrong.
*/
public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged)
throws CmsException {
if(isAdmin(currentUser, currentProject)) {
new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged);
} else {
throw new CmsException("[" + this.getClass().getName() + "] exportResources",
CmsException.C_NO_ACCESS);
}
}
/**
* Exports cms-resources to zip.
*
* <B>Security:</B>
* only Administrators can do this;
*
* @param currentUser user who requestd themethod
* @param currentProject current project of the user
* @param exportFile the name (absolute Path) of the export resource (zip)
* @param exportPath the name (absolute Path) of folder from which should be exported
* @param excludeSystem, decides whether to exclude the system
* @param excludeUnchanged <code>true</code>, if unchanged files should be excluded.
* @param cms the cms-object to use for the export.
*
* @exception Throws CmsException if something goes wrong.
*/
public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged, boolean exportUserdata)
throws CmsException {
if(isAdmin(currentUser, currentProject)) {
new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged, null, exportUserdata);
} else {
throw new CmsException("[" + this.getClass().getName() + "] exportResources",
CmsException.C_NO_ACCESS);
}
}
// now private stuff
/**
* This method is called, when a resource was changed. Currently it counts the
* changes.
*/
protected void fileSystemChanged(boolean folderChanged) {
// count only the changes - do nothing else!
// in the future here will maybe a event-story be added
m_fileSystemChanges++;
if(folderChanged){
m_fileSystemFolderChanges++;
}
}
/**
* Forwards a task to a new user.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task to forward.
* @param newRole The new Group for the task
* @param newUser The new user who gets the task. if its "" the a new agent will automatic selected
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void forwardTask(CmsUser currentUser, CmsProject currentProject, int taskid,
String newRoleName, String newUserName)
throws CmsException {
CmsGroup newRole = m_dbAccess.readGroup(newRoleName);
CmsUser newUser = null;
if(newUserName.equals("")) {
newUser = m_dbAccess.readUser(m_dbAccess.findAgent(newRole.getId()));
} else {
newUser = m_dbAccess.readUser(newUserName, C_USER_TYPE_SYSTEMUSER);
}
m_dbAccess.forwardTask(taskid, newRole.getId(), newUser.getId());
m_dbAccess.writeSystemTaskLog(taskid,
"Task fowarded from " +
currentUser.getFirstname() + " " +
currentUser.getLastname() + " to " +
newUser.getFirstname() + " " +
newUser.getLastname() + ".");
}
/**
* Returns all projects, which are owned by the user or which are accessible
* for the group of the user.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjects(CmsUser currentUser,
CmsProject currentProject)
throws CmsException {
// get all groups of the user
Vector groups = getGroupsOfUser(currentUser, currentProject,
currentUser.getName());
// get all projects which are owned by the user.
Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser);
// get all projects, that the user can access with his groups.
for(int i = 0; i < groups.size(); i++) {
Vector projectsByGroup;
// is this the admin-group?
if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) {
// yes - all unlocked projects are accessible for him
projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED);
} else {
// no - get all projects, which can be accessed by the current group
projectsByGroup = m_dbAccess.getAllAccessibleProjectsByGroup((CmsGroup) groups.elementAt(i));
}
// merge the projects to the vector
for(int j = 0; j < projectsByGroup.size(); j++) {
// add only projects, which are new
if(!projects.contains(projectsByGroup.elementAt(j))) {
projects.addElement(projectsByGroup.elementAt(j));
}
}
}
// return the vector of projects
return(projects);
}
/**
* Returns all projects, which are owned by the user or which are manageable
* for the group of the user.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* @return a Vector of projects.
*/
public Vector getAllManageableProjects(CmsUser currentUser,
CmsProject currentProject)
throws CmsException {
// get all groups of the user
Vector groups = getGroupsOfUser(currentUser, currentProject,
currentUser.getName());
// get all projects which are owned by the user.
Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser);
// get all projects, that the user can manage with his groups.
for(int i = 0; i < groups.size(); i++) {
// get all projects, which can be managed by the current group
Vector projectsByGroup;
// is this the admin-group?
if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) {
// yes - all unlocked projects are accessible for him
projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED);
} else {
// no - get all projects, which can be accessed by the current group
projectsByGroup = m_dbAccess.getAllAccessibleProjectsByManagerGroup((CmsGroup)groups.elementAt(i));
}
// merge the projects to the vector
for(int j = 0; j < projectsByGroup.size(); j++) {
// add only projects, which are new
if(!projects.contains(projectsByGroup.elementAt(j))) {
projects.addElement(projectsByGroup.elementAt(j));
}
}
}
// remove the online-project, it is not manageable!
projects.removeElement(onlineProject(currentUser, currentProject));
// return the vector of projects
return(projects);
}
/**
* Returns a Vector with all I_CmsResourceTypes.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* Returns a Hashtable with all I_CmsResourceTypes.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Hashtable getAllResourceTypes(CmsUser currentUser,
CmsProject currentProject)
throws CmsException {
// check, if the resourceTypes were read bevore
if(m_resourceTypes == null) {
// get the resourceTypes from the registry
m_resourceTypes = new Hashtable();
Vector resTypeNames = new Vector();
Vector launcherTypes = new Vector();
Vector launcherClass = new Vector();
Vector resourceClass = new Vector();
int resTypeCount = m_registry.getResourceTypes(resTypeNames, launcherTypes, launcherClass, resourceClass);
for (int i = 0; i < resTypeCount; i++){
// add the resource-type
try{
Class c = Class.forName((String)resourceClass.elementAt(i));
I_CmsResourceType resTypeClass = (I_CmsResourceType) c.newInstance();
resTypeClass.init(i, Integer.parseInt((String)launcherTypes.elementAt(i)),
(String)resTypeNames.elementAt(i),
(String)launcherClass.elementAt(i));
m_resourceTypes.put((String)resTypeNames.elementAt(i), resTypeClass);
}catch(Exception e){
e.printStackTrace();
throw new CmsException("[" + this.getClass().getName() + "] Error while getting ResourceType: " + (String)resTypeNames.elementAt(i) + " from registry ", CmsException.C_UNKNOWN_EXCEPTION );
}
}
}
// return the resource-types.
return(m_resourceTypes);
}
/**
* Returns informations about the cache<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @return A hashtable with informations about the cache.
*/
public Hashtable getCacheInfo() {
Hashtable info = new Hashtable();
info.put("UserCache",""+m_userCache.size());
info.put("GroupCache",""+m_groupCache.size());
info.put("UserGroupCache",""+m_usergroupsCache.size());
info.put("ResourceCache",""+m_resourceCache.size());
info.put("SubResourceCache",""+m_subresCache.size());
info.put("ProjectCache",""+m_projectCache.size());
info.put("PropertyCache",""+m_propertyCache.size());
info.put("PropertyDefinitionCache",""+m_propertyDefCache.size());
info.put("PropertyDefinitionVectorCache",""+m_propertyDefVectorCache.size());
info.put("AccessCache",""+m_accessCache.size());
return info;
}
/**
* Returns all child groups of a group<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param groupname The name of the group.
* @return groups A Vector of all child groups or null.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getChild(CmsUser currentUser, CmsProject currentProject,
String groupname)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
return m_dbAccess.getChild(groupname);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + groupname,
CmsException.C_NO_ACCESS);
}
}
/**
* Returns all child groups of a group<P/>
* This method also returns all sub-child groups of the current group.
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param groupname The name of the group.
* @return groups A Vector of all child groups or null.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getChilds(CmsUser currentUser, CmsProject currentProject,
String groupname)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
Vector childs=new Vector();
Vector allChilds=new Vector();
Vector subchilds=new Vector();
CmsGroup group=null;
// get all child groups if the user group
childs=m_dbAccess.getChild(groupname);
if (childs!=null) {
allChilds=childs;
// now get all subchilds for each group
Enumeration enu=childs.elements();
while (enu.hasMoreElements()) {
group=(CmsGroup)enu.nextElement();
subchilds=getChilds(currentUser,currentProject,group.getName());
//add the subchilds to the already existing groups
Enumeration enusub=subchilds.elements();
while (enusub.hasMoreElements()) {
group=(CmsGroup)enusub.nextElement();
allChilds.addElement(group);
}
}
}
return allChilds;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + groupname,
CmsException.C_NO_ACCESS);
}
}
// Method to access the configuration
/**
* Method to access the configurations of the properties-file.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The Configurations of the properties-file.
*/
public Configurations getConfigurations(CmsUser currentUser, CmsProject currentProject) {
return m_configuration;
}
/**
* Returns the list of groups to which the user directly belongs to<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user.
* @return Vector of groups
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector getDirectGroupsOfUser(CmsUser currentUser, CmsProject currentProject,
String username)
throws CmsException {
return m_dbAccess.getGroupsOfUser(username);
}
/**
* Returns a Vector with all files of a folder.<br>
*
* Files of a folder can be read from an offline Project and the online Project.<br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read this resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername the complete path to the folder.
*
* @return A Vector with all subfiles for the overgiven folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException
{
return getFilesInFolder(currentUser, currentProject, foldername, false);
}
/**
* Returns a Vector with all files of a folder.<br>
*
* Files of a folder can be read from an offline Project and the online Project.<br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read this resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername the complete path to the folder.
* @param includeDeleted Include the folder if it is deleted
*
* @return A Vector with all subfiles for the overgiven folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername, boolean includeDeleted) throws CmsException
{
Vector files;
// Todo: add caching for getFilesInFolder
//files=(Vector)m_subresCache.get(C_FILE+currentProject.getId()+foldername);
//if ((files==null) || (files.size()==0)) {
// try to get the files in the current project
try
{
files = helperGetFilesInFolder(currentUser, currentProject, foldername, includeDeleted);
}
catch (CmsException e)
{
//if access is denied to the folder, dont try to read them from the online project.)
if (e.getType() == CmsException.C_ACCESS_DENIED)
return new Vector(); //an empty vector.
else
//can't handle it here.
throw e;
}
if (files == null)
{
//we are not allowed to read the folder (folder deleted)
return new Vector();
}
Vector onlineFiles = null;
if (!currentProject.equals(onlineProject(currentUser, currentProject)))
{
// this is not the onlineproject, get the files
// from the onlineproject, too
try
{
onlineFiles = helperGetFilesInFolder(currentUser, onlineProject(currentUser, currentProject), foldername,includeDeleted);
// merge the resources
}
catch (CmsException exc)
{
if (exc.getType() != CmsException.C_ACCESS_DENIED)
//cant handle it.
throw exc;
else
//access denied.
return files;
}
}
//m_subresCache.put(C_FILE+currentProject.getId()+foldername,files);
if(onlineFiles == null) //if it was null, the folder was marked deleted -> no files in online project.
return files;
//m_subresCache.put(C_FILE+currentProject.getId()+foldername,files);
return files = mergeResources(files, onlineFiles);
}
/**
* Returns a Vector with all resource-names that have set the given property to the given value.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername the complete path to the folder.
* @param propertydef, the name of the propertydefinition to check.
* @param property, the value of the property for the resource.
*
* @return Vector with all names of resources.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesWithProperty(CmsUser currentUser, CmsProject currentProject, String propertyDefinition, String propertyValue) throws CmsException {
return m_dbAccess.getFilesWithProperty(currentProject.getId(), propertyDefinition, propertyValue);
}
/**
* This method can be called, to determine if the file-system was changed
* in the past. A module can compare its previosly stored number with this
* returned number. If they differ, a change was made.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* @return the number of file-system-changes.
*/
public long getFileSystemChanges(CmsUser currentUser, CmsProject currentProject) {
return m_fileSystemChanges;
}
/**
* This method can be called, to determine if the file-system was changed
* in the past. A module can compare its previosly stored number with this
* returned number. If they differ, a change was made.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* @return the number of file-system-changes.
*/
public long getFileSystemFolderChanges(CmsUser currentUser, CmsProject currentProject) {
return m_fileSystemFolderChanges;
}
/**
* Returns a Vector with the complete folder-tree for this project.<br>
*
* Subfolders can be read from an offline project and the online project. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read this resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* @return subfolders A Vector with the complete folder-tree for this project.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFolderTree(CmsUser currentUser, CmsProject currentProject) throws CmsException {
Vector resources = m_dbAccess.getFolderTree(currentProject.getId());
Vector retValue = new Vector(resources.size());
String lastcheck = "#"; // just a char that is not valid in a filename
//make sure that we have access to all these.
for (Enumeration e = resources.elements(); e.hasMoreElements();) {
CmsResource res = (CmsResource) e.nextElement();
if (!res.getAbsolutePath().startsWith(lastcheck)) {
if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) ||
accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) ||
accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) {
retValue.addElement(res);
} else {
lastcheck = res.getAbsolutePath();
}
}
}
return retValue;
}
/**
* Returns all groups<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return users A Vector of all existing groups.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getGroups(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
return m_dbAccess.getGroups();
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Returns a list of groups of a user.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user.
* @return Vector of groups
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(CmsUser currentUser, CmsProject currentProject,
String username)
throws CmsException {
Vector allGroups;
allGroups=(Vector)m_usergroupsCache.get(C_USER+username);
if ((allGroups==null) || (allGroups.size()==0)) {
CmsGroup subGroup;
CmsGroup group;
// get all groups of the user
Vector groups=m_dbAccess.getGroupsOfUser(username);
allGroups=groups;
// now get all childs of the groups
Enumeration enu = groups.elements();
while (enu.hasMoreElements()) {
group=(CmsGroup)enu.nextElement();
subGroup=getParent(currentUser, currentProject,group.getName());
while(subGroup != null) {
// is the subGroup already in the vector?
if(!allGroups.contains(subGroup)) {
// no! add it
allGroups.addElement(subGroup);
}
// read next sub group
subGroup = getParent(currentUser, currentProject,subGroup.getName());
}
}
m_usergroupsCache.put(C_USER+username,allGroups);
}
return allGroups;
}
public String getReadingpermittedGroup(int projectId, String resource) throws CmsException {
return m_dbAccess.getReadingpermittedGroup(projectId, resource);
}
/**
* Returns the parent group of a group<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param groupname The name of the group.
* @return group The parent group or null.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsGroup getParent(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException
{
CmsGroup group = readGroup(currentUser, currentProject, groupname);
if (group.getParentId() == C_UNKNOWN_ID)
{
return null;
}
// try to read from cache
CmsGroup parent = (CmsGroup) m_groupCache.get(group.getParentId());
if (parent == null)
{
parent = m_dbAccess.readGroup(group.getParentId());
m_groupCache.put(group.getParentId(), parent);
}
return parent;
}
/**
* Returns the parent resource of a resouce.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsResource getParentResource(CmsUser currentUser, CmsProject currentProject,
String resourcename)
throws CmsException {
// TODO: this can maybe done via the new parent id'd
String parentresourceName = readFileHeader(currentUser, currentProject, resourcename).getParent();
return readFileHeader(currentUser, currentProject, parentresourceName);
}
/**
* Gets the Registry.<BR/>
*
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param cms The actual CmsObject
* @exception Throws CmsException if access is not allowed.
*/
public I_CmsRegistry getRegistry(CmsUser currentUser, CmsProject currentProject, CmsObject cms)
throws CmsException {
return m_registry.clone(cms);
}
/**
* Returns a Vector with the subresources for a folder.<br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read and view this resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param folder The name of the folder to get the subresources from.
*
* @return subfolders A Vector with resources.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getResourcesInFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException {
CmsFolder offlineFolder = null;
Vector resources = new Vector();
try {
offlineFolder = readFolder(currentUser, currentProject, folder);
if (offlineFolder.getState() == C_STATE_DELETED) {
offlineFolder = null;
}
} catch (CmsException exc) {
// ignore the exception - folder was not found in this project
}
if (offlineFolder == null) {
// the folder is not existent
throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_NOT_FOUND);
} else
resources = m_dbAccess.getResourcesInFolder(currentProject.getId(), offlineFolder);
Vector retValue = new Vector(resources.size());
//make sure that we have access to all these.
for (Enumeration e = resources.elements(); e.hasMoreElements();) {
CmsResource res = (CmsResource) e.nextElement();
if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) ||
accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) ||
accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) {
retValue.addElement(res);
}
}
return retValue;
}
/**
* Returns a I_CmsResourceType.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resourceType the id of the resourceType to get.
*
* Returns a I_CmsResourceType.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public I_CmsResourceType getResourceType(CmsUser currentUser,
CmsProject currentProject,
int resourceType)
throws CmsException {
// try to get the resource-type
Hashtable types = getAllResourceTypes(currentUser, currentProject);
Enumeration keys = types.keys();
I_CmsResourceType currentType;
while(keys.hasMoreElements()) {
currentType = (I_CmsResourceType) types.get(keys.nextElement());
if(currentType.getResourceType() == resourceType) {
return(currentType);
}
}
// was not found - throw exception
throw new CmsException("[" + this.getClass().getName() + "] " + resourceType,
CmsException.C_NOT_FOUND);
}
/**
* Returns a I_CmsResourceType.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resourceType the name of the resource to get.
*
* Returns a I_CmsResourceType.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public I_CmsResourceType getResourceType(CmsUser currentUser,
CmsProject currentProject,
String resourceType)
throws CmsException {
// try to get the resource-type
try {
I_CmsResourceType type = (I_CmsResourceType)getAllResourceTypes(currentUser, currentProject).get(resourceType);
if(type == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + resourceType,
CmsException.C_NOT_FOUND);
}
return type;
} catch(NullPointerException exc) {
// was not found - throw exception
throw new CmsException("[" + this.getClass().getName() + "] " + resourceType,
CmsException.C_NOT_FOUND);
}
}
/**
* Returns a Vector with all subfolders.<br>
*
* Subfolders can be read from an offline project and the online project. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read this resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername the complete path to the folder.
*
* @return subfolders A Vector with all subfolders for the given folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject,
String foldername) throws CmsException {
return getSubFolders(currentUser, currentProject, foldername, false);
}
/**
* Returns a Vector with all subfolders.<br>
*
* Subfolders can be read from an offline project and the online project. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read this resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername the complete path to the folder.
* @param includeDeleted Include the folder if it is deleted
*
* @return subfolders A Vector with all subfolders for the given folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject,
String foldername, boolean includeDeleted)
throws CmsException {
Vector folders = new Vector();
// Todo: add caching for getSubFolders
//folders=(Vector)m_subresCache.get(C_FOLDER+currentProject.getId()+foldername);
if ((folders==null) || (folders.size()==0)){
folders=new Vector();
// try to get the folders in the current project
try {
folders = helperGetSubFolders(currentUser, currentProject, foldername);
} catch (CmsException exc) {
// no folders, ignoring them
}
if( !currentProject.equals(onlineProject(currentUser, currentProject))) {
// this is not the onlineproject, get the files
// from the onlineproject, too
try {
Vector onlineFolders =
helperGetSubFolders(currentUser,
onlineProject(currentUser, currentProject),
foldername);
// merge the resources
folders = mergeResources(folders, onlineFolders);
} catch(CmsException exc) {
// no onlinefolders, ignoring them
}
}
//m_subresCache.put(C_FOLDER+currentProject.getId()+foldername,folders);
}
// return the folders
return(folders);
}
/**
* Get a parameter value for a task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskId The Id of the task.
* @param parName Name of the parameter.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public String getTaskPar(CmsUser currentUser, CmsProject currentProject,
int taskId, String parName)
throws CmsException {
return m_dbAccess.getTaskPar(taskId, parName);
}
/**
* Get the template task id fo a given taskname.
*
* @param taskName Name of the Task
*
* @return id from the task template
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public int getTaskType(String taskName)
throws CmsException {
return m_dbAccess.getTaskType(taskName);
}
/**
* Returns all users<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return users A Vector of all existing users.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getUsers(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
return m_dbAccess.getUsers(C_USER_TYPE_SYSTEMUSER);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Returns all users from a given type<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param type The type of the users.
* @return users A Vector of all existing users.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
return m_dbAccess.getUsers(type);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Returns all users from a given type that start with a specified string<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param type The type of the users.
* @param namestart The filter for the username
* @return users A Vector of all existing users.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type, String namestart)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
return m_dbAccess.getUsers(type,namestart);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Returns a list of users in a group.<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param groupname The name of the group to list users from.
* @return Vector of users.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getUsersOfGroup(CmsUser currentUser, CmsProject currentProject,
String groupname)
throws CmsException {
// check the security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) {
return m_dbAccess.getUsersOfGroup(groupname, C_USER_TYPE_SYSTEMUSER);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + groupname,
CmsException.C_NO_ACCESS);
}
}
/**
* Gets all users with a certain Lastname.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param Lastname the start of the users lastname
* @param UserType webuser or systemuser
* @param UserStatus enabled, disabled
* @param wasLoggedIn was the user ever locked in?
* @param nMax max number of results
*
* @return the users.
*
* @exception CmsException if operation was not successful.
*/
public Vector getUsersByLastname(CmsUser currentUser,
CmsProject currentProject, String Lastname,
int UserType, int UserStatus,
int wasLoggedIn, int nMax)
throws CmsException {
// check security
if( ! anonymousUser(currentUser, currentProject).equals( currentUser )){
return m_dbAccess.getUsersByLastname(Lastname, UserType, UserStatus,
wasLoggedIn, nMax);
} else {
throw new CmsException(
"[" + this.getClass().getName() + "] " + currentUser.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* A helper method for this resource-broker.
* Returns a Vector with all files of a folder.
* The method does not read any files from the parrent folder,
* and do also return deleted files.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername the complete path to the folder.
*
* @return subfiles A Vector with all subfiles for the overgiven folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
protected Vector helperGetFilesInFolder(CmsUser currentUser,
CmsProject currentProject,
String foldername, boolean includeDeleted)
throws CmsException {
// get the folder
CmsFolder cmsFolder = null;
try {
cmsFolder = m_dbAccess.readFolder(currentProject.getId(), foldername);
} catch(CmsException exc) {
if(exc.getType() == exc.C_NOT_FOUND) {
// ignore the exception - file dosen't exist in this project
return new Vector(); //just an empty vector.
} else {
throw exc;
}
}
if ((cmsFolder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted))
{
//indicate that the folder was found, but deleted, and resources are not avaiable.
return null;
}
Vector _files = m_dbAccess.getFilesInFolder(currentProject.getId(),cmsFolder);
Vector files = new Vector(_files.size());
//make sure that we have access to all these.
for (Enumeration e = _files.elements();e.hasMoreElements();)
{
CmsFile file = (CmsFile) e.nextElement();
if( accessOther(currentUser, currentProject, (CmsResource)file, C_ACCESS_PUBLIC_READ) ||
accessOwner(currentUser, currentProject, (CmsResource)file, C_ACCESS_OWNER_READ) ||
accessGroup(currentUser, currentProject, (CmsResource)file, C_ACCESS_GROUP_READ) )
{
files.addElement(file);
}
}
return files;
}
/**
* A helper method for this resource-broker.
* Returns a Hashtable with all subfolders.<br>
*
* Subfolders can be read from an offline project and the online project. <br>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project to read the folders from.
* @param foldername the complete path to the folder.
*
* @return subfolders A Hashtable with all subfolders for the given folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
protected Vector helperGetSubFolders(CmsUser currentUser,
CmsProject currentProject,
String foldername)
throws CmsException{
CmsFolder cmsFolder = m_dbAccess.readFolder(currentProject.getId(),foldername);
if( accessRead(currentUser, currentProject, (CmsResource)cmsFolder) ) {
// acces to all subfolders was granted - return the sub-folders.
Vector folders = m_dbAccess.getSubFolders(currentProject.getId(),cmsFolder);
CmsFolder folder;
for(int z=0 ; z < folders.size() ; z++) {
// read the current folder
folder = (CmsFolder)folders.elementAt(z);
// check the readability for the folder
if( !( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_READ) ||
accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_READ) ||
accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_READ) ) ) {
// access to the folder was not granted delete him
folders.removeElementAt(z);
// correct the index
z
}
}
return folders;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + foldername,
CmsException.C_ACCESS_DENIED);
}
}
/**
* Imports a import-resource (folder or zipfile) to the cms.
*
* <B>Security:</B>
* only Administrators can do this;
*
* @param currentUser user who requestd themethod
* @param currentProject current project of the user
* @param importFile the name (absolute Path) of the import resource (zip or folder)
* @param importPath the name (absolute Path) of folder in which should be imported
* @param cms the cms-object to use for the import.
*
* @exception Throws CmsException if something goes wrong.
*/
public void importFolder(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms)
throws CmsException {
if(isAdmin(currentUser, currentProject)) {
new CmsImportFolder(importFile, importPath, cms);
} else {
throw new CmsException("[" + this.getClass().getName() + "] importResources",
CmsException.C_NO_ACCESS);
}
}
// Methods working with database import and export
/**
* Imports a import-resource (folder or zipfile) to the cms.
*
* <B>Security:</B>
* only Administrators can do this;
*
* @param currentUser user who requestd themethod
* @param currentProject current project of the user
* @param importFile the name (absolute Path) of the import resource (zip or folder)
* @param importPath the name (absolute Path) of folder in which should be imported
* @param cms the cms-object to use for the import.
*
* @exception Throws CmsException if something goes wrong.
*/
public void importResources(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms)
throws CmsException {
if(isAdmin(currentUser, currentProject)) {
CmsImport imp = new CmsImport(importFile, importPath, cms);
imp.importResources();
} else {
throw new CmsException("[" + this.getClass().getName() + "] importResources",
CmsException.C_NO_ACCESS);
}
}
// Internal ResourceBroker methods
/**
* Initializes the resource broker and sets up all required modules and connections.
* @param config The OpenCms configuration.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void init(Configurations config)
throws CmsException {
// Store the configuration.
m_configuration = config;
if (config.getString("history.enabled", "true").toLowerCase().equals("false")) {
m_enableHistory = false;
}
// initialize the access-module.
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init the dbaccess-module.");
}
m_dbAccess = createDbAccess(config);
// initalize the caches
m_userCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".user", 50));
m_groupCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".group", 50));
m_usergroupsCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".usergroups", 50));
m_projectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".project", 50));
m_onlineProjectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".onlineproject", 50));
//m_resourceCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000));
m_resourceCache=new CmsResourceCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000));
m_subresCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".subres", 100));
m_propertyCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".property", 1000));
m_propertyDefCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertydef", 100));
m_propertyDefVectorCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertyvectordef", 100));
m_accessCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".access", 1000));
m_cachelimit = config.getInteger(C_CONFIGURATION_CACHE + ".maxsize", 20000);
m_refresh=config.getString(C_CONFIGURATION_CACHE + ".refresh", "");
// initialize the registry
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init registry.");
}
try {
m_registry= new CmsRegistry(CmsBase.getAbsolutePath(config.getString(C_CONFIGURATION_REGISTRY)));
}
catch (CmsException ex) {
throw ex;
}
catch(Exception ex) {
// init of registry failed - throw exception
throw new CmsException("Init of registry failed", CmsException.C_REGISTRY_ERROR, ex);
}
}
/**
* Determines, if the users current group is the admin-group.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return true, if the users current group is the admin-group,
* else it returns false.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public boolean isAdmin(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_ADMIN);
}
/**
* Determines, if the users may manage a project.<BR/>
* Only the manager of a project may publish it.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return true, if the may manage this project.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public boolean isManagerOfProject(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
// is the user owner of the project?
if( currentUser.getId() == currentProject.getOwnerId() ) {
// YES
return true;
}
// get all groups of the user
Vector groups = getGroupsOfUser(currentUser, currentProject,
currentUser.getName());
for(int i = 0; i < groups.size(); i++) {
// is this a managergroup for this project?
if( ((CmsGroup)groups.elementAt(i)).getId() ==
currentProject.getManagerGroupId() ) {
// this group is manager of the project
return true;
}
}
// this user is not manager of this project
return false;
}
/**
* Determines, if the users current group is the projectleader-group.<BR/>
* All projectleaders can create new projects, or close their own projects.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return true, if the users current group is the projectleader-group,
* else it returns false.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public boolean isProjectManager(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_PROJECTLEADER);
}
/**
* Returns the user, who had locked the resource.<BR/>
*
* A user can lock a resource, so he is the only one who can write this
* resource. This methods checks, if a resource was locked.
*
* @param user The user who wants to lock the file.
* @param project The project in which the resource will be used.
* @param resource The resource.
*
* @return the user, who had locked the resource.
*
* @exception CmsException will be thrown, if the user has not the rights
* for this resource.
*/
public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject,
CmsResource resource)
throws CmsException {
return readUser(currentUser,currentProject,resource.isLockedBy() ) ;
}
/**
* Returns the user, who had locked the resource.<BR/>
*
* A user can lock a resource, so he is the only one who can write this
* resource. This methods checks, if a resource was locked.
*
* @param user The user who wants to lock the file.
* @param project The project in which the resource will be used.
* @param resource The complete path to the resource.
*
* @return the user, who had locked the resource.
*
* @exception CmsException will be thrown, if the user has not the rights
* for this resource.
*/
public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject,
String resource)
throws CmsException {
return readUser(currentUser,currentProject,readFileHeader(currentUser, currentProject, resource).isLockedBy() ) ;
}
/**
* Locks a resource.<br>
*
* Only a resource in an offline project can be locked. The state of the resource
* is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* A user can lock a resource, so he is the only one who can write this
* resource. <br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is not locked by another user</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The complete path to the resource to lock.
* @param force If force is true, a existing locking will be oberwritten.
*
* @exception CmsException Throws CmsException if operation was not succesful.
* It will also be thrown, if there is a existing lock
* and force was set to false.
*/
public void lockResource(CmsUser currentUser, CmsProject currentProject,
String resourcename, boolean force)
throws CmsException {
CmsResource cmsResource=null;
// read the resource, that should be locked
if (resourcename.endsWith("/")) {
cmsResource = (CmsFolder)readFolder(currentUser,currentProject,resourcename);
} else {
cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename);
}
// Can't lock what isn't there
if (cmsResource == null) throw new CmsException(CmsException.C_NOT_FOUND);
// check, if the resource is in the offline-project
if(cmsResource.getProjectId() != currentProject.getId()) {
// the resource is not in the current project and can't be locked - so ignore.
return;
}
// check, if the user may lock the resource
if( accessLock(currentUser, currentProject, cmsResource) ) {
if(cmsResource.isLocked()) {
// if the force switch is not set, throw an exception
if (force==false) {
throw new CmsException("["+this.getClass().getName()+"] "+resourcename,CmsException.C_LOCKED);
}
}
// lock the resource
cmsResource.setLocked(currentUser.getId());
cmsResource.setLockedInProject(currentProject.getId());
//update resource
m_dbAccess.updateLockstate(cmsResource, currentProject.getId());
// update the cache
if (resourcename.endsWith("/")) {
m_resourceCache.remove(resourcename);
//m_resourceCache.put(currentProject.getId()+C_FOLDER+resourcename,(CmsFolder)cmsResource);
} else {
m_resourceCache.remove(resourcename);
//m_resourceCache.put(currentProject.getId()+C_FILE+resourcename,(CmsFile)cmsResource);
}
m_subresCache.clear();
// if this resource is a folder -> lock all subresources, too
if(cmsResource.isFolder()) {
Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getAbsolutePath());
Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getAbsolutePath());
CmsResource currentResource;
// lock all files in this folder
for(int i = 0; i < files.size(); i++ ) {
currentResource = (CmsResource)files.elementAt(i);
if (currentResource.getState() != C_STATE_DELETED) {
lockResource(currentUser, currentProject, currentResource.getAbsolutePath(), true);
}
}
// lock all files in this folder
for(int i = 0; i < folders.size(); i++) {
currentResource = (CmsResource)folders.elementAt(i);
if (currentResource.getState() != C_STATE_DELETED) {
lockResource(currentUser, currentProject, currentResource.getAbsolutePath(), true);
}
}
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + resourcename,
CmsException.C_NO_ACCESS);
}
}
// Methods working with user and groups
/**
* Logs a user into the Cms, if the password is correct.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user to be returned.
* @param password The password of the user to be returned.
* @return the logged in user.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser loginUser(CmsUser currentUser, CmsProject currentProject,
String username, String password)
throws CmsException {
// we must read the user from the dbAccess to avoid the cache
CmsUser newUser = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER);
// is the user enabled?
if( newUser.getFlags() == C_FLAG_ENABLED ) {
// Yes - log him in!
// first write the lastlogin-time.
newUser.setLastlogin(new Date().getTime());
// write the user back to the cms.
m_dbAccess.writeUser(newUser);
// update cache
m_userCache.put(newUser.getName()+newUser.getType(),newUser);
return(newUser);
} else {
// No Access!
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS );
}
}
/**
* Logs a web user into the Cms, if the password is correct.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user to be returned.
* @param password The password of the user to be returned.
* @return the logged in user.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser loginWebUser(CmsUser currentUser, CmsProject currentProject,
String username, String password)
throws CmsException {
// we must read the user from the dbAccess to avoid the cache
CmsUser newUser = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER);
// is the user enabled?
if( newUser.getFlags() == C_FLAG_ENABLED ) {
// Yes - log him in!
// first write the lastlogin-time.
newUser.setLastlogin(new Date().getTime());
// write the user back to the cms.
m_dbAccess.writeUser(newUser);
// update cache
m_userCache.put(newUser.getName()+newUser.getType(),newUser);
return(newUser);
} else {
// No Access!
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS );
}
}
/**
* Merges two resource-vectors into one vector.
* All offline-resources will be putted to the return-vector. All additional
* online-resources will be putted to the return-vector, too. All online resources,
* which are present in the offline-vector will be ignored.
*
*
* @param offline The vector with the offline resources.
* @param online The vector with the online resources.
* @return The merged vector.
*/
protected Vector mergeResources(Vector offline, Vector online) {
//dont do anything if any of the given vectors are empty or null.
if ((offline == null) || (offline.size() == 0)) return (online!=null)?online:new Vector();
if ((online == null) || (online.size() == 0)) return (offline!=null)?offline:new Vector();
// create a vector for the merged offline
//remove all objects in the online vector that are present in the offline vector.
for (Enumeration e=offline.elements();e.hasMoreElements();)
{
CmsResource cr = (CmsResource) e.nextElement();
Resource r = new Resource(cr.getAbsolutePath());
online.removeElement(r);
}
//merge the two vectors. If both vectors were sorted, the mereged vector will remain sorted.
Vector merged = new Vector(offline.size() + online.size());
int offIndex = 0;
int onIndex = 0;
while ((offIndex < offline.size()) || (onIndex < online.size()))
{
if (offIndex >= offline.size())
{
merged.addElement(online.elementAt(onIndex++));
continue;
}
if (onIndex >= online.size())
{
merged.addElement(offline.elementAt(offIndex++));
continue;
}
String on = ((CmsResource)online.elementAt(onIndex)).getAbsolutePath();
String off = ((CmsResource)offline.elementAt(offIndex)).getAbsolutePath();
if (on.compareTo(off) < 0)
merged.addElement(online.elementAt(onIndex++));
else
merged.addElement(offline.elementAt(offIndex++));
}
return(merged);
}
/**
* Moves the file.
*
* This operation includes a copy and a delete operation. These operations
* are done with their security-checks.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param source The complete path of the sourcefile.
* @param destination The complete path of the destinationfile.
*
* @exception CmsException will be thrown, if the file couldn't be moved.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public void moveFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException {
// read the file to check access
CmsResource file = readFileHeader(currentUser,currentProject, source);
// has the user write-access?
if (accessWrite(currentUser, currentProject, file)) {
// first copy the file, this may ends with an exception
copyFile(currentUser, currentProject, source, destination);
// then delete the source-file, this may end with an exception
// => the file was only copied, not moved!
deleteFile(currentUser, currentProject, source);
// inform about the file-system-change
fileSystemChanged(file.isFolder());
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_NO_ACCESS);
}
}
/**
* Returns the onlineproject. All anonymous
* (CmsUser callingUser, or guest) users will see the resources of this project.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return the onlineproject object.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject onlineProject(CmsUser currentUser, CmsProject currentProject) throws CmsException {
CmsProject project = null;
// try to get the online project for this offline project from cache
project = (CmsProject) m_onlineProjectCache.get(currentProject.getId());
if (project == null) {
// the project was not in the cache
// lookup the currentProject in the CMS_SITE_PROJECT table, and in the same call return it.
project = m_dbAccess.getOnlineProject(currentProject.getId());
// store the project into the cache
m_onlineProjectCache.put(currentProject.getId(), project);
}
return project;
}
/**
* Creates a static export of a Cmsresource in the filesystem
*
* @param exportTo The Directory to where the files should be exported.
* @param exportFile .
*
* @exception CmsException if operation was not successful.
*/
public void exportStaticResources(String exportTo, CmsFile file) throws CmsException {
m_dbAccess.exportStaticResources(exportTo, file);
}
/**
* Creates a static export to the filesystem
*
* @param exportTo The Directory to where the files should be exported.
* @param res The compleate path of the folder or the resource to be exported ..
* @param projectId The id of the current project.
* @param onlineId The id of the online project.
*
* @exception CmsException if operation was not successful.
*/
public void exportStaticResources(String exportTo, String res, int projectId, int onlineId) throws CmsException {
m_dbAccess.exportStaticResources(exportTo, res, projectId, onlineId);
}
/**
* Sets a special CmsObject for the static export in the dbAccess.
*
* @param cms The CmsObject created for the export.
*/
public void setCmsObjectForStaticExport(CmsObject cms){
m_dbAccess.setCmsObjectForStaticExport(cms);
}
/**
* Publishes a project.
*
* <B>Security</B>
* Only the admin or the owner of the project can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id of the project to be published.
* @return a vector of changed resources.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public synchronized Vector publishProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException {
CmsProject publishProject = readProject(currentUser, currentProject, id);
Vector changedResources = null;
// check the security
if ((isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, publishProject)) &&
(publishProject.getFlags() == C_PROJECT_STATE_UNLOCKED)) {
// check, if we update class-files with this publishing
ClassLoader loader = getClass().getClassLoader();
boolean shouldReload = false;
// check if we are using our own classloader
// e.g. the cms-shell uses the default classloader
if(loader instanceof CmsClassLoader) {
// yes we have our own classloader
Vector classFiles = ((CmsClassLoader)loader).getFilenames();
shouldReload = shouldReloadClasses(id, classFiles);
}
changedResources = m_dbAccess.publishProject(currentUser, id, onlineProject(currentUser, currentProject), m_enableHistory);
m_resourceCache.clear();
m_subresCache.clear();
// inform about the file-system-change
fileSystemChanged(true);
// the project was stored in the backuptables for history
//new projectmechanism: the project can be still used after publishing
// it will be deleted if the project_flag = C_PROJECT_STATE_TEMP
if (publishProject.getType() == C_PROJECT_TYPE_TEMPORARY) {
m_dbAccess.deleteProject(publishProject);
m_projectCache.remove(id);
//deleteProject(currentUser, currentProject, id);
}
// finally set the refrish signal to another server if nescessary
if (m_refresh.length() > 0) {
try {
URL url = new URL(m_refresh);
URLConnection con = url.openConnection();
con.connect();
InputStream in = con.getInputStream();
in.close();
//System.err.println(in.toString());
} catch (Exception ex) {
throw new CmsException(0, ex);
}
}
// inform about the reload classes
if(loader instanceof CmsClassLoader) {
((CmsClassLoader)loader).setShouldReload(shouldReload);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] could not publish project " + id, CmsException.C_NO_ACCESS);
}
return changedResources;
}
/**
* This method checks, if there is a classFile marked as changed or deleted.
* If that is so, we have to reload all classes and instances to get rid of old versions.
*/
public boolean shouldReloadClasses(int projectId, Vector classFiles) {
for(int i = 0; i < classFiles.size(); i++) {
try {
CmsFile file = m_dbAccess.readFileHeader(projectId, (String)classFiles.elementAt(i));
if( (file.getState() == C_STATE_CHANGED) || (file.getState() == C_STATE_DELETED) ) {
// this class-file was changed or deleted - we have to reload
return true;
}
} catch(CmsException exc) {
// the file couldn't be read - it is not in our project - ignore this file
}
}
// no modified class-files are found - we can use the old classes
return false;
}
/**
* Reads the agent of a task from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param task The task to read the agent from.
* @return The owner of a task.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsUser readAgent(CmsUser currentUser, CmsProject currentProject,
CmsTask task)
throws CmsException {
return readUser(currentUser,currentProject,task.getAgentUser());
}
/**
* Reads all file headers of a file in the OpenCms.<BR>
* This method returns a vector with all file headers, i.e.
* the file headers of a file, independent of the project they were attached to.<br>
*
* The reading excludes the filecontent.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The name of the file to be read.
*
* @return Vector of file headers read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector readAllFileHeaders(CmsUser currentUser, CmsProject currentProject,
String filename)
throws CmsException {
CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename);
if( accessRead(currentUser, currentProject, cmsFile) ) {
// access to all subfolders was granted - return the file-history.
return(m_dbAccess.readAllFileHeaders(currentProject.getId(), filename));
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_ACCESS_DENIED);
}
}
/**
* Reads all file headers of a file in the OpenCms.<BR>
* This method returns a vector with the histroy of all file headers, i.e.
* the file headers of a file, independent of the project they were attached to.<br>
*
* The reading excludes the filecontent.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The name of the file to be read.
*
* @return Vector of file headers read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector readAllFileHeadersForHist(CmsUser currentUser, CmsProject currentProject,
String filename)
throws CmsException {
CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename);
if( accessRead(currentUser, currentProject, cmsFile) ) {
// access to all subfolders was granted - return the file-history.
return(m_dbAccess.readAllFileHeadersForHist(currentProject.getId(), filename));
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_ACCESS_DENIED);
}
}
/**
* select all projectResources from an given project
*
* @param project The project in which the resource is used.
*
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readAllProjectResources(int projectId) throws CmsException {
return m_dbAccess.readAllProjectResources(projectId);
}
/**
* Returns a list of all propertyinformations of a file or folder.
*
* <B>Security</B>
* Only the user is granted, who has the right to view the resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource of which the propertyinformation has to be
* read.
*
* @return Vector of propertyinformation as Strings.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Hashtable readAllProperties(CmsUser currentUser, CmsProject currentProject,
String resource)
throws CmsException {
CmsResource res;
// read the resource from the currentProject, or the online-project
try {
res = readFileHeader(currentUser,currentProject, resource);
} catch(CmsException exc) {
// the resource was not readable
if(currentProject.equals(onlineProject(currentUser, currentProject))) {
// this IS the onlineproject - throw the exception
throw exc;
} else {
// try to read the resource in the onlineproject
res = readFileHeader(currentUser,onlineProject(currentUser, currentProject),
resource);
}
}
// check the security
if( ! accessRead(currentUser, currentProject, res) ) {
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_NO_ACCESS);
}
Hashtable returnValue = null;
returnValue = (Hashtable)m_propertyCache.get(currentProject.getId()+"_"+Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType()));
if (returnValue == null){
returnValue = m_dbAccess.readAllProperties(currentProject.getId(),res,res.getType());
m_propertyCache.put(currentProject.getId()+"_"+Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType()),returnValue);
}
return returnValue;
}
/**
* Reads all propertydefinitions for the given resource type.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resourceType The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject,
int resourceType)
throws CmsException {
Vector returnValue = null;
returnValue = (Vector) m_propertyDefVectorCache.get(Integer.toString(resourceType));
if (returnValue == null){
returnValue = m_dbAccess.readAllPropertydefinitions(resourceType);
m_propertyDefVectorCache.put(Integer.toString(resourceType), returnValue);
}
return returnValue;
}
/**
* Reads all propertydefinitions for the given resource type.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resourcetype The name of the resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject,
String resourcetype)
throws CmsException {
Vector returnValue = null;
I_CmsResourceType resType = getResourceType(currentUser, currentProject, resourcetype);
returnValue = (Vector)m_propertyDefVectorCache.get(resType.getResourceTypeName());
if (returnValue == null){
returnValue = m_dbAccess.readAllPropertydefinitions(resType);
m_propertyDefVectorCache.put(resType.getResourceTypeName(), returnValue);
}
return returnValue;
}
// Methods working with system properties
/**
* Reads the export-path for the system.
* This path is used for db-export and db-import.
*
* <B>Security:</B>
* All users are granted.<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return the exportpath.
*/
public String readExportPath(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
return (String) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH);
}
/**
* Reads a file from a previous project of the Cms.<BR/>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the project to read the file from.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
* */
public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException
{
CmsFile cmsFile = null;
// read the resource from the projectId,
try
{
//cmsFile=(CmsFile)m_resourceCache.get(projectId+C_FILECONTENT+filename);
if (cmsFile == null) {
cmsFile = m_dbAccess.readFileInProject(projectId, onlineProject(currentUser, currentProject).getId(), filename);
// only put it in thecache until the size is below the max site
/*if (cmsFile.getContents().length <m_cachelimit) {
m_resourceCache.put(projectId+C_FILECONTENT+filename,cmsFile);
} else {
}*/
}
if (accessRead(currentUser, currentProject, (CmsResource) cmsFile))
{
// acces to all subfolders was granted - return the file.
return cmsFile;
}
else
{
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED);
}
}
catch (CmsException exc)
{
throw exc;
}
}
/**
* Reads a file from the Cms.<BR/>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
* */
public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException
{
CmsFile cmsFile = null;
// read the resource from the currentProject, or the online-project
try
{
//cmsFile=(CmsFile)m_resourceCache.get(currentProject.getId()+C_FILECONTENT+filename);
if (cmsFile == null) {
cmsFile = m_dbAccess.readFile(currentProject.getId(), onlineProject(currentUser, currentProject).getId(), filename);
// only put it in thecache until the size is below the max site
/*if (cmsFile.getContents().length <m_cachelimit) {
m_resourceCache.put(currentProject.getId()+C_FILECONTENT+filename,cmsFile);
} else {
}*/
}
}
catch (CmsException exc)
{
// the resource was not readable
if (exc.getType() == CmsException.C_RESOURCE_DELETED)
{
//resource deleted
throw exc;
}
else
// NO NEED TO READ FROM ONLINE PROJECT
// if (currentProject.equals(onlineProject(currentUser, currentProject)))
// this IS the onlineproject - throw the exception
throw exc;
/* }
else
{
// try to read the resource in the onlineproject
cmsFile = m_dbAccess.readFile(onlineProject(currentUser, currentProject).getId(), onlineProject(currentUser, currentProject).getId(), filename);
} */
}
if (accessRead(currentUser, currentProject, (CmsResource) cmsFile))
{
// acces to all subfolders was granted - return the file.
return cmsFile;
}
else
{
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED);
}
}
/**
* Gets the known file extensions (=suffixes)
*
* <B>Security:</B>
* All users are granted access<BR/>
*
* @param currentUser The user who requested this method, not used here
* @param currentProject The current project of the user, not used here
*
* @return Hashtable with file extensions as Strings
*/
public Hashtable readFileExtensions(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
Hashtable res=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS);
return ( (res!=null)? res : new Hashtable());
}
/**
* Reads a file header a previous project of the Cms.<BR/>
* The reading excludes the filecontent. <br>
*
* A file header can be read from an offline project or the online project.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the project to read the file from.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsResource readFileHeader(CmsUser currentUser,
CmsProject currentProject,
int projectId,
String filename)
throws CmsException {
CmsResource cmsFile = null;
// check if this method is misused to read a folder
if (filename.endsWith("/")) {
return (CmsResource) readFolder(currentUser, currentProject, projectId,filename);
}
// read the resource from the currentProject
try {
cmsFile=(CmsResource)m_resourceCache.get(filename, projectId);
if (cmsFile==null) {
cmsFile = m_dbAccess.readFileHeaderInProject(projectId, filename);
m_resourceCache.put(filename,projectId,cmsFile);
}
if( accessRead(currentUser, currentProject, cmsFile) ) {
// acces to all subfolders was granted - return the file-header.
return cmsFile;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_ACCESS_DENIED);
}
} catch(CmsException exc) {
throw exc;
}
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent. <br>
*
* A file header can be read from an offline project or the online project.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsResource readFileHeader(CmsUser currentUser,
CmsProject currentProject, String filename)
throws CmsException {
CmsResource cmsFile = null;
// check if this method is misused to read a folder
if (filename.endsWith("/")) {
return (CmsResource) readFolder(currentUser,currentProject,filename);
}
// read the resource from the currentProject, or the online-project
try {
// try to read form cache first
cmsFile=(CmsResource)m_resourceCache.get(filename, currentProject.getId());
if (cmsFile==null) {
cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename);
m_resourceCache.put(filename,currentProject.getId(),cmsFile);
}
} catch(CmsException exc) {
// the resource was not readable
throw exc;
}
if( accessRead(currentUser, currentProject, cmsFile) ) {
// acces to all subfolders was granted - return the file-header.
return cmsFile;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_ACCESS_DENIED);
}
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent. <br>
*
* A file header can be read from an offline project or the online project.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsResource readFileHeader(CmsUser currentUser,
CmsProject currentProject, String filename,
boolean includeDeleted)
throws CmsException {
CmsResource cmsFile = null;
// check if this method is misused to read a folder
if (filename.endsWith("/")) {
return (CmsResource) readFolder(currentUser,currentProject,filename, includeDeleted);
}
// read the resource from the currentProject, or the online-project
try {
// try to read form cache first
cmsFile=(CmsResource)m_resourceCache.get(filename,currentProject.getId());
if (cmsFile==null) {
cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename, includeDeleted);
m_resourceCache.put(filename,currentProject.getId(),cmsFile);
}
} catch(CmsException exc) {
// the resource was not readable
throw exc;
}
if( accessRead(currentUser, currentProject, cmsFile) ) {
// acces to all subfolders was granted - return the file-header.
return cmsFile;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_ACCESS_DENIED);
}
}
/**
* Reads a file header from the history of the Cms.<BR/>
* The reading excludes the filecontent. <br>
*
* A file header is read from the backup resources.
*
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param versionId The id of the version of the file.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsBackupResource readFileHeaderForHist(CmsUser currentUser,
CmsProject currentProject,
int versionId,
String filename)
throws CmsException {
CmsBackupResource resource;
// read the resource from the backup resources
try {
resource = m_dbAccess.readFileHeaderForHist(versionId, filename);
} catch(CmsException exc) {
throw exc;
}
return resource;
}
/**
* Reads a file from the history of the Cms.<BR/>
* The reading includes the filecontent. <br>
*
* A file is read from the backup resources.
*
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param versionId The id of the version of the file.
* @param filename The name of the file to be read.
*
* @return The file read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsBackupResource readFileForHist(CmsUser currentUser,
CmsProject currentProject,
int versionId,
String filename)
throws CmsException {
CmsBackupResource resource;
// read the resource from the backup resources
try {
resource = m_dbAccess.readFileForHist(versionId, filename);
} catch(CmsException exc) {
throw exc;
}
return resource;
}
/**
* Reads all file headers for a project from the Cms.<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the project to read the resources for.
*
* @return a Vector of resources.
*
* @exception CmsException will be thrown, if the file couldn't be read.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public Vector readFileHeaders(CmsUser currentUser, CmsProject currentProject,
int projectId)
throws CmsException {
CmsProject project = readProject(currentUser, currentProject, projectId);
Vector resources = m_dbAccess.readResources(project);
Vector retValue = new Vector();
// check the security
for(int i = 0; i < resources.size(); i++) {
if( accessRead(currentUser, currentProject, (CmsResource) resources.elementAt(i)) ) {
retValue.addElement(resources.elementAt(i));
}
}
return retValue;
}
/**
* Reads a folder from the Cms.<BR/>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param project the project to read the folder from.
* @param foldername The complete path of the folder to be read.
*
* @return folder The read folder.
*
* @exception CmsException will be thrown, if the folder couldn't be read.
* The CmsException will also be thrown, if the user has not the rights
* for this resource
*/
protected CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, int project, String folder) throws CmsException {
if (folder == null) return null;
CmsFolder cmsFolder = (CmsFolder) m_resourceCache.get(folder,currentProject.getId());
if (cmsFolder == null) {
cmsFolder = m_dbAccess.readFolderInProject(project, folder);
if (cmsFolder != null){
m_resourceCache.put(folder, currentProject.getId(), (CmsFolder) cmsFolder);
}
}
if (cmsFolder != null) {
if (!accessRead(currentUser, currentProject, (CmsResource) cmsFolder))
throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED);
}
return cmsFolder;
}
/**
* Reads a folder from the Cms.<BR/>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername The complete path of the folder to be read.
*
* @return folder The read folder.
*
* @exception CmsException will be thrown, if the folder couldn't be read.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException {
return readFolder(currentUser, currentProject, folder, false);
}
/**
* Reads a folder from the Cms.<BR/>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param foldername The complete path of the folder to be read.
* @param includeDeleted Include the folder it it is marked as deleted
*
* @return folder The read folder.
*
* @exception CmsException will be thrown, if the folder couldn't be read.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, boolean includeDeleted) throws CmsException {
CmsFolder cmsFolder = null;
// read the resource from the currentProject, or the online-project
try {
cmsFolder = (CmsFolder) m_resourceCache.get(folder, currentProject.getId());
if (cmsFolder == null) {
cmsFolder = m_dbAccess.readFolder(currentProject.getId(), folder);
if (cmsFolder.getState() != C_STATE_DELETED) {
m_resourceCache.put(folder, currentProject.getId(), (CmsFolder) cmsFolder);
}
}
} catch (CmsException exc) {
throw exc;
}
if (accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) {
// acces to all subfolders was granted - return the folder.
if ((cmsFolder.getState() == C_STATE_DELETED) && (!includeDeleted)) {
throw new CmsException("[" + this.getClass().getName() + "]" + cmsFolder.getAbsolutePath(), CmsException.C_RESOURCE_DELETED);
} else {
return cmsFolder;
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED);
}
}
/**
* Reads a folder from the Cms.<BR/>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param folder The complete path to the folder from which the folder will be
* read.
* @param foldername The name of the folder to be read.
*
* @return folder The read folder.
*
* @exception CmsException will be thrown, if the folder couldn't be read.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*
* @see #readFolder(CmsUser, CmsProject, String)
*/
public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, String folderName) throws CmsException {
return readFolder(currentUser, currentProject, folder + folderName);
}
/**
* Reads all given tasks from a user for a project.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the Project in which the tasks are defined.
* @param owner Owner of the task.
* @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW.
* @param orderBy Chooses, how to order the tasks.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readGivenTasks(CmsUser currentUser, CmsProject currentProject,
int projectId, String ownerName, int taskType,
String orderBy, String sort)
throws CmsException {
CmsProject project = null;
CmsUser owner = null;
if(ownerName != null) {
owner = readUser(currentUser, currentProject, ownerName);
}
if(projectId != C_UNKNOWN_ID) {
project = readProject(currentUser, currentProject, projectId);
}
return m_dbAccess.readTasks(project,null, owner, null, taskType, orderBy, sort);
}
/**
* Reads the group of a project from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The group of a resource.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject,
CmsProject project)
throws CmsException {
CmsGroup group=null;
// try to read group form cache
group=(CmsGroup)m_groupCache.get(project.getGroupId());
if (group== null) {
group=m_dbAccess.readGroup(project.getGroupId()) ;
m_groupCache.put(project.getGroupId(),group);
}
return group;
}
/**
* Reads the group of a resource from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The group of a resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject,
CmsResource resource)
throws CmsException {
CmsGroup group=null;
// try to read group form cache
group=(CmsGroup)m_groupCache.get(resource.getGroupId());
if (group== null) {
group=m_dbAccess.readGroup(resource.getGroupId()) ;
m_groupCache.put(resource.getGroupId(),group);
}
return group;
}
/**
* Reads the group (role) of a task from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param task The task to read from.
* @return The group of a resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject,
CmsTask task)
throws CmsException {
// TODO: To be implemented
//return null;
return m_dbAccess.readGroup(task.getRole());
}
/**
* Returns a group object.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param groupname The name of the group that is to be read.
* @return Group.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject,
String groupname)
throws CmsException {
CmsGroup group=null;
// try to read group form cache
group=(CmsGroup)m_groupCache.get(groupname);
if (group== null) {
group=m_dbAccess.readGroup(groupname) ;
m_groupCache.put(groupname,group);
}
return group;
}
/**
* Reads the managergroup of a project from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The group of a resource.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsGroup readManagerGroup(CmsUser currentUser, CmsProject currentProject,
CmsProject project)
throws CmsException {
CmsGroup group=null;
// try to read group form cache
group=(CmsGroup)m_groupCache.get(project.getManagerGroupId());
if (group== null) {
group=m_dbAccess.readGroup(project.getManagerGroupId()) ;
m_groupCache.put(project.getManagerGroupId(),group);
}
return group;
}
/**
* Gets the MimeTypes.
* The Mime-Types will be returned.
*
* <B>Security:</B>
* All users are garnted<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
*
* @return the mime-types.
*/
public Hashtable readMimeTypes(CmsUser currentUser, CmsProject currentProject)
throws CmsException {
return(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_MIMETYPES);
}
/**
* Reads the original agent of a task from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param task The task to read the original agent from.
* @return The owner of a task.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsUser readOriginalAgent(CmsUser currentUser, CmsProject currentProject,
CmsTask task)
throws CmsException {
return readUser(currentUser,currentProject,task.getOriginalUser());
}
/**
* Reads the owner of a project from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The owner of a resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject,
CmsProject project)
throws CmsException {
return readUser(currentUser,currentProject,project.getOwnerId());
}
/**
* Reads the owner of a resource from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The owner of a resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject,
CmsResource resource)
throws CmsException {
return readUser(currentUser,currentProject,resource.getOwnerId() );
}
/**
* Reads the owner (initiator) of a task from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param task The task to read the owner from.
* @return The owner of a task.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject,
CmsTask task)
throws CmsException {
return readUser(currentUser,currentProject,task.getInitiatorUser());
}
/**
* Reads the owner of a tasklog from the OpenCms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @return The owner of a resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTaskLog log)
throws CmsException {
return readUser(currentUser,currentProject,log.getUser());
}
/**
* Reads a project from the Cms.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id of the project to read.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException {
CmsProject project=null;
project=(CmsProject)m_projectCache.get(id);
if (project==null) {
project=m_dbAccess.readProject(id);
m_projectCache.put(id,project);
}
return project;
}
/**
* Reads a project from the Cms.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param res The resource to read the project of.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(CmsUser currentUser, CmsProject currentProject,
CmsResource res)
throws CmsException {
return readProject(currentUser, currentProject, res.getProjectId());
}
/**
* Reads a project from the Cms.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param task The task to read the project of.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(CmsUser currentUser, CmsProject currentProject,
CmsTask task)
throws CmsException {
// read the parent of the task, until it has no parents.
task = this.readTask(currentUser, currentProject, task.getId());
while(task.getParent() != 0) {
task = readTask(currentUser, currentProject, task.getParent());
}
return m_dbAccess.readProject(task);
}
/**
* Reads all file headers of a project from the Cms.
*
* @param projectId the id of the project to read the file headers for.
* @param filter The filter for the resources (all, new, changed, deleted, locked)
*
* @return a Vector of resources.
*/
public Vector readProjectView(CmsUser currentUser, CmsProject currentProject, int projectId, String filter)
throws CmsException {
CmsProject project = readProject(currentUser, currentProject, projectId);
Vector retValue = new Vector();
String whereClause = new String();
if("new".equalsIgnoreCase(filter)){
whereClause = " AND STATE="+C_STATE_NEW;
} else if ("changed".equalsIgnoreCase(filter)){
whereClause = " AND STATE="+C_STATE_CHANGED;
} else if ("deleted".equalsIgnoreCase(filter)){
whereClause = " AND STATE="+C_STATE_DELETED;
} else if ("locked".equalsIgnoreCase(filter)){
whereClause = " AND LOCKED_BY != "+C_UNKNOWN_ID;
} else {
whereClause = " AND STATE != "+C_STATE_UNCHANGED;
}
Vector resources = m_dbAccess.readProjectView(currentProject.getId(), projectId, whereClause);
// check the security
for(int i = 0; i < resources.size(); i++) {
if( accessRead(currentUser, project, (CmsResource) resources.elementAt(i)) ) {
retValue.addElement(resources.elementAt(i));
}
}
return retValue;
}
/**
* Reads the backupinformation of a project from the Cms.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param versionId The versionId of the project.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsBackupProject readBackupProject(CmsUser currentUser, CmsProject currentProject, int versionId)
throws CmsException {
return m_dbAccess.readBackupProject(versionId);
}
/**
* Reads log entries for a project.
*
* @param projectId The id of the projec for tasklog to read.
* @return A Vector of new TaskLog objects
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readProjectLogs(CmsUser currentUser, CmsProject currentProject,
int projectid)
throws CmsException {
return m_dbAccess.readProjectLogs(projectid);
}
/**
* Returns a propertyinformation of a file or folder.
*
* <B>Security</B>
* Only the user is granted, who has the right to view the resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource of which the propertyinformation has
* to be read.
* @param property The propertydefinition-name of which the propertyinformation has to be read.
*
* @return propertyinfo The propertyinfo as string.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public String readProperty(CmsUser currentUser, CmsProject currentProject,
String resource, String property)
throws CmsException {
CmsResource res;
// read the resource from the currentProject
try {
res = readFileHeader(currentUser,currentProject, resource, true);
} catch(CmsException exc) {
// the resource was not readable
throw exc;
}
// check the security
if( ! accessRead(currentUser, currentProject, res) ) {
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_NO_ACCESS);
}
String returnValue = null;
returnValue = (String)m_propertyCache.get(currentProject.getId()+property +
Integer.toString(res.getResourceId()) +","+ Integer.toString(res.getType()));
if (returnValue == null){
returnValue = m_dbAccess.readProperty(property,currentProject.getId(),res,res.getType());
if (returnValue == null) {
returnValue="";
}
m_propertyCache.put(currentProject.getId()+property +Integer.toString(res.getResourceId()) +
","+ Integer.toString(res.getType()), returnValue);
}
if (returnValue.equals("")){returnValue=null;}
return returnValue;
}
/**
* Reads a definition for the given resource type.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param name The name of the propertydefinition to read.
* @param resourcetype The name of the resource type for which the propertydefinition
* is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(CmsUser currentUser,
CmsProject currentProject,
String name, String resourcetype)
throws CmsException {
I_CmsResourceType resType = getResourceType(currentUser,currentProject,resourcetype);
CmsPropertydefinition returnValue = null;
returnValue = (CmsPropertydefinition)m_propertyDefCache.get(name + resType.getResourceType());
if (returnValue == null){
returnValue = m_dbAccess.readPropertydefinition(name, resType);
m_propertyDefCache.put(name + resType.getResourceType(), returnValue);
}
return returnValue;
}
public Vector readResources(CmsProject project) throws com.opencms.core.CmsException
{
return m_dbAccess.readResources(project);
}
/**
* Read a task by id.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id for the task to read.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask readTask(CmsUser currentUser, CmsProject currentProject,
int id)
throws CmsException {
return m_dbAccess.readTask(id);
}
/**
* Reads log entries for a task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The task for the tasklog to read .
* @return A Vector of new TaskLog objects
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readTaskLogs(CmsUser currentUser, CmsProject currentProject,
int taskid)
throws CmsException {
return m_dbAccess.readTaskLogs(taskid);;
}
/**
* Reads all tasks for a project.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the Project in which the tasks are defined. Can be null for all tasks
* @tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy Chooses, how to order the tasks.
* @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readTasksForProject(CmsUser currentUser, CmsProject currentProject,
int projectId, int tasktype,
String orderBy, String sort)
throws CmsException {
CmsProject project = null;
if(projectId != C_UNKNOWN_ID) {
project = readProject(currentUser, currentProject, projectId);
}
return m_dbAccess.readTasks(project, null, null, null, tasktype, orderBy, sort);
}
/**
* Reads all tasks for a role in a project.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the Project in which the tasks are defined.
* @param user The user who has to process the task.
* @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW.
* @param orderBy Chooses, how to order the tasks.
* @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readTasksForRole(CmsUser currentUser, CmsProject currentProject,
int projectId, String roleName, int tasktype,
String orderBy, String sort)
throws CmsException {
CmsProject project = null;
CmsGroup role = null;
if(roleName != null) {
role = readGroup(currentUser, currentProject, roleName);
}
if(projectId != C_UNKNOWN_ID) {
project = readProject(currentUser, currentProject, projectId);
}
return m_dbAccess.readTasks(project, null, null, role, tasktype, orderBy, sort);
}
/**
* Reads all tasks for a user in a project.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param projectId The id of the Project in which the tasks are defined.
* @param userName The user who has to process the task.
* @param taskType Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW.
* @param orderBy Chooses, how to order the tasks.
* @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readTasksForUser(CmsUser currentUser, CmsProject currentProject,
int projectId, String userName, int taskType,
String orderBy, String sort)
throws CmsException {
CmsUser user = m_dbAccess.readUser(userName, C_USER_TYPE_SYSTEMUSER);
return m_dbAccess.readTasks(currentProject, user, null, null, taskType, orderBy, sort);
}
/**
* Returns a user object.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id of the user that is to be read.
* @return User
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser readUser(CmsUser currentUser, CmsProject currentProject,
int id)
throws CmsException {
try {
CmsUser user=null;
// try to read the user from cache
user=(CmsUser)m_userCache.get(id);
if (user==null) {
user=m_dbAccess.readUser(id);
m_userCache.put(id,user);
}
return user;
} catch (CmsException ex) {
return new CmsUser(C_UNKNOWN_ID, id + "", "deleted user");
}
}
/**
* Returns a user object.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user that is to be read.
* @return User
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser readUser(CmsUser currentUser, CmsProject currentProject,
String username)
throws CmsException {
CmsUser user = null;
// try to read the user from cache
user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER);
if (user == null) {
user = m_dbAccess.readUser(username, C_USER_TYPE_SYSTEMUSER);
m_userCache.put(username+C_USER_TYPE_SYSTEMUSER,user);
}
return user;
}
/**
* Returns a user object.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user that is to be read.
* @param type The type of the user.
* @return User
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser readUser(CmsUser currentUser, CmsProject currentProject,
String username,int type)
throws CmsException {
CmsUser user = null;
// try to read the user from cache
user = (CmsUser)m_userCache.get(username+type);
if (user == null) {
user = m_dbAccess.readUser(username, type);
m_userCache.put(username+type,user);
}
return user;
}
/**
* Returns a user object if the password for the user is correct.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The username of the user that is to be read.
* @param password The password of the user that is to be read.
* @return User
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser readUser(CmsUser currentUser, CmsProject currentProject,
String username, String password)
throws CmsException {
CmsUser user = null;
// ednfal: don't read user from cache because password may be changed
//user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER);
// store user in cache
if (user == null) {
user = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER);
m_userCache.put(username+C_USER_TYPE_SYSTEMUSER, user);
}
return user;
}
/**
* Returns a user object if the password for the user is correct.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The username of the user that is to be read.
* @return User
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject,
String username)
throws CmsException {
CmsUser user = null;
user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER);
// store user in cache
if (user == null) {
user = m_dbAccess.readUser(username, C_USER_TYPE_WEBUSER);
m_userCache.put(username+C_USER_TYPE_WEBUSER, user);
}
return user;
}
/**
* Returns a user object if the password for the user is correct.<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The username of the user that is to be read.
* @param password The password of the user that is to be read.
* @return User
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject,
String username, String password)
throws CmsException {
CmsUser user = null;
user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER);
// store user in cache
if (user == null) {
user = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER);
m_userCache.put(username+C_USER_TYPE_WEBUSER,user);
}
return user;
}
/**
* Reaktivates a task from the Cms.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task to accept.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void reaktivateTask(CmsUser currentUser, CmsProject currentProject,
int taskId)
throws CmsException {
CmsTask task = m_dbAccess.readTask(taskId);
task.setState(C_TASK_STATE_STARTED);
task.setPercentage(0);
task = m_dbAccess.writeTask(task);
m_dbAccess.writeSystemTaskLog(taskId,
"Task was reactivated from " +
currentUser.getFirstname() + " " +
currentUser.getLastname() + ".");
}
/**
* Sets a new password only if the user knows his recovery-password.
*
* All users can do this if he knows the recovery-password.<P/>
*
* <B>Security:</B>
* All users can do this if he knows the recovery-password.<P/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user.
* @param recoveryPassword The recovery password.
* @param newPassword The new password.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void recoverPassword(CmsUser currentUser, CmsProject currentProject,
String username, String recoveryPassword, String newPassword)
throws CmsException {
// check the length of the new password.
if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_SHORT_PASSWORD);
}
// check the length of the recovery password.
if(recoveryPassword.length() < C_PASSWORD_MINIMUMSIZE) {
throw new CmsException("[" + this.getClass().getName() + "] no recovery password.");
}
m_dbAccess.recoverPassword(username, recoveryPassword, newPassword);
}
/**
* Removes a user from a group.
*
* Only the admin can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user that is to be removed from the group.
* @param groupname The name of the group.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void removeUserFromGroup(CmsUser currentUser, CmsProject currentProject,
String username, String groupname)
throws CmsException {
// test if this user is existing in the group
if (!userInGroup(currentUser,currentProject,username,groupname)) {
// user already there, throw exception
throw new CmsException("[" + this.getClass().getName() + "] remove " + username+ " from " +groupname,
CmsException.C_NO_USER);
}
if( isAdmin(currentUser, currentProject) ) {
CmsUser user;
CmsGroup group;
user=readUser(currentUser,currentProject,username);
//check if the user exists
if (user != null) {
group=readGroup(currentUser,currentProject,groupname);
//check if group exists
if (group != null){
// do not remmove the user from its default group
if (user.getDefaultGroupId() != group.getId()) {
//remove this user from the group
m_dbAccess.removeUserFromGroup(user.getId(),group.getId());
m_usergroupsCache.clear();
} else {
throw new CmsException("["+this.getClass().getName()+"]",CmsException.C_NO_DEFAULT_GROUP);
}
} else {
throw new CmsException("["+this.getClass().getName()+"]"+groupname,CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS);
}
}
}
/**
* Renames the file to a new name. <br>
*
* Rename can only be done in an offline project. To rename a file, the following
* steps have to be done:
* <ul>
* <li> Copy the file with the oldname to a file with the new name, the state
* of the new file is set to NEW (2).
* <ul>
* <li> If the state of the original file is UNCHANGED (0), the file content of the
* file is read from the online project. </li>
* <li> If the state of the original file is CHANGED (1) or NEW (2) the file content
* of the file is read from the offline project. </li>
* </ul>
* </li>
* <li> Set the state of the old file to DELETED (3). </li>
* </ul>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param oldname The complete path to the resource which will be renamed.
* @param newname The new name of the resource (CmsUser callingUser, No path information allowed).
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void renameFile(CmsUser currentUser, CmsProject currentProject, String oldname, String newname) throws CmsException {
// read the old file
CmsResource file = readFileHeader(currentUser, currentProject, oldname);
// checks, if the newname is valid, if not it throws a exception
validFilename(newname);
// has the user write-access?
if (accessWrite(currentUser, currentProject, file)) {
String path = oldname.substring(0, oldname.lastIndexOf("/") + 1);
copyFile(currentUser, currentProject, oldname, path + newname);
deleteFile(currentUser, currentProject, oldname);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + oldname, CmsException.C_NO_ACCESS);
}
/*
// check, if the new name is a valid filename
validFilename(newname);
// read the old file
CmsResource file = readFileHeader(currentUser, currentProject, oldname);
// has the user write-access?
if( accessWrite(currentUser, currentProject, file) ) {
// write-acces was granted - rename the file.
m_dbAccess.renameFile(currentProject,
onlineProject(currentUser, currentProject),
currentUser.getId(),
file.getResourceId(), file.getPath() + newname );
// copy the metainfos
writeProperties(currentUser,currentProject, file.getPath() + newname,
readAllProperties(currentUser,currentProject,file.getAbsolutePath()));
// inform about the file-system-change
fileSystemChanged();
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + oldname,
CmsException.C_NO_ACCESS);
}
*/
}
/**
* This method loads old sessiondata from the database. It is used
* for sessionfailover.
*
* @param oldSessionId the id of the old session.
* @return the old sessiondata.
*/
public Hashtable restoreSession(String oldSessionId)
throws CmsException {
return m_dbAccess.readSession(oldSessionId);
}
/**
* Restores a file in the current project with a version in the backup
*
* @param currentUser The current user
* @param currentProject The current project
* @param versionId The version id of the resource
* @param filename The name of the file to restore
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void restoreResource(CmsUser currentUser, CmsProject currentProject,
int versionId, String filename) throws CmsException {
CmsBackupResource backupFile = null;
CmsFile offlineFile = null;
// read the backup file
backupFile = readFileForHist(currentUser, currentProject, versionId, filename);
// try to read the owner and the group
int ownerId = currentUser.getId();
int groupId = currentUser.getDefaultGroupId();
try{
ownerId = readUser(currentUser, currentProject, backupFile.getOwnerName()).getId();
} catch(CmsException exc){
// user can not be read, set the userid of current user
}
try{
groupId = readGroup(currentUser, currentProject, backupFile.getGroupName()).getId();
} catch(CmsException exc){
// group can not be read, set the groupid of current user
}
offlineFile = readFile(currentUser, currentProject, filename);
if (backupFile != null && offlineFile != null){
CmsFile newFile = new CmsFile(offlineFile.getResourceId(), offlineFile.getParentId(),
offlineFile.getFileId(), offlineFile.getAbsolutePath(),
backupFile.getType(), backupFile.getFlags(),
ownerId, groupId,
currentProject.getId(), backupFile.getAccessFlags(),
C_STATE_CHANGED, offlineFile.isLockedBy(),
backupFile.getLauncherType(), backupFile.getLauncherClassname(),
offlineFile.getDateCreated(), offlineFile.getDateLastModified(),
currentUser.getId(), backupFile.getContents(),
backupFile.getLength(), currentProject.getId());
writeFile(currentUser, currentProject, newFile);
}
}
/**
* Set a new name for a task
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task to set the percentage.
* @param name The new name value
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void setName(CmsUser currentUser, CmsProject currentProject,
int taskId, String name)
throws CmsException {
if( (name == null) || name.length() == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " +
name, CmsException.C_BAD_NAME);
}
CmsTask task = m_dbAccess.readTask(taskId);
task.setName(name);
task = m_dbAccess.writeTask(task);
m_dbAccess.writeSystemTaskLog(taskId,
"Name was set to " + name + "% from " +
currentUser.getFirstname() + " " +
currentUser.getLastname() + ".");
}
/**
* Sets a new parent-group for an already existing group in the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param groupName The name of the group that should be written to the Cms.
* @param parentGroupName The name of the parentGroup to set, or null if the parent
* group should be deleted.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void setParentGroup(CmsUser currentUser, CmsProject currentProject,
String groupName, String parentGroupName)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
CmsGroup group = readGroup(currentUser, currentProject, groupName);
int parentGroupId = C_UNKNOWN_ID;
// if the group exists, use its id, else set to unknown.
if( parentGroupName != null ) {
parentGroupId = readGroup(currentUser, currentProject, parentGroupName).getId();
}
group.setParentId(parentGroupId);
// write the changes to the cms
writeGroup(currentUser,currentProject,group);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + groupName,
CmsException.C_NO_ACCESS);
}
}
/**
* Sets the password for a user.
*
* Only a adminstrator can do this.<P/>
*
* <B>Security:</B>
* Users, which are in the group "administrators" are granted.<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user.
* @param newPassword The new password.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void setPassword(CmsUser currentUser, CmsProject currentProject,
String username, String newPassword)
throws CmsException {
// check the length of the new password.
if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_SHORT_PASSWORD);
}
if( isAdmin(currentUser, currentProject) ) {
m_dbAccess.setPassword(username, newPassword);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS);
}
}
/**
* Sets the password for a user.
*
* Only a adminstrator or the curretuser can do this.<P/>
*
* <B>Security:</B>
* Users, which are in the group "administrators" are granted.<BR/>
* Current users can change their own password.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user.
* @param oldPassword The new password.
* @param newPassword The new password.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void setPassword(CmsUser currentUser, CmsProject currentProject,
String username, String oldPassword, String newPassword)
throws CmsException {
// check the length of the new password.
if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_SHORT_PASSWORD);
}
// read the user
CmsUser user;
try {
user = readUser(currentUser, currentProject, username, oldPassword);
} catch(CmsException exc) {
// this is no system-user - maybe a webuser?
try{
user = readWebUser(currentUser, currentProject, username, oldPassword);
} catch(CmsException e) {
throw exc;
}
}
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) &&
( isAdmin(user, currentProject) || user.equals(currentUser)) ) {
m_dbAccess.setPassword(username, newPassword);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS);
}
}
/**
* Set priority of a task
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task to set the percentage.
* @param new priority value
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void setPriority(CmsUser currentUser, CmsProject currentProject,
int taskId, int priority)
throws CmsException {
CmsTask task = m_dbAccess.readTask(taskId);
task.setPriority(priority);
task = m_dbAccess.writeTask(task);
m_dbAccess.writeSystemTaskLog(taskId,
"Priority was set to " + priority + " from " +
currentUser.getFirstname() + " " +
currentUser.getLastname() + ".");
}
/**
* Sets the recovery password for a user.
*
* Only a adminstrator or the curretuser can do this.<P/>
*
* <B>Security:</B>
* Users, which are in the group "administrators" are granted.<BR/>
* Current users can change their own password.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param username The name of the user.
* @param password The password of the user.
* @param newPassword The new recoveryPassword to be set.
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void setRecoveryPassword(CmsUser currentUser, CmsProject currentProject,
String username, String password, String newPassword)
throws CmsException {
// check the length of the new password.
if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_SHORT_PASSWORD);
}
// read the user
CmsUser user;
try {
user = readUser(currentUser, currentProject, username, password);
} catch(CmsException exc) {
// this is no system-user - maybe a webuser?
user = readWebUser(currentUser, currentProject, username, password);
}
if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) &&
( isAdmin(user, currentProject) || user.equals(currentUser)) ) {
m_dbAccess.setRecoveryPassword(username, newPassword);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + username,
CmsException.C_NO_ACCESS);
}
}
/**
* Set a Parameter for a task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskId The Id of the task.
* @param parName Name of the parameter.
* @param parValue Value if the parameter.
*
* @return The id of the inserted parameter or 0 if the parameter already exists for this task.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void setTaskPar(CmsUser currentUser, CmsProject currentProject,
int taskId, String parName, String parValue)
throws CmsException {
m_dbAccess.setTaskPar(taskId, parName, parValue);
}
/**
* Set timeout of a task
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task to set the percentage.
* @param new timeout value
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void setTimeout(CmsUser currentUser, CmsProject currentProject,
int taskId, long timeout)
throws CmsException {
CmsTask task = m_dbAccess.readTask(taskId);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
task.setTimeOut(timestamp);
task = m_dbAccess.writeTask(task);
m_dbAccess.writeSystemTaskLog(taskId,
"Timeout was set to " + timeout + " from " +
currentUser.getFirstname() + " " +
currentUser.getLastname() + ".");
}
/**
* This method stores sessiondata into the database. It is used
* for sessionfailover.
*
* @param sessionId the id of the session.
* @param isNew determines, if the session is new or not.
* @return data the sessionData.
*/
public void storeSession(String sessionId, Hashtable sessionData)
throws CmsException {
// update the session
int rowCount = m_dbAccess.updateSession(sessionId, sessionData);
if(rowCount != 1) {
// the entry dosn't exists - create it
m_dbAccess.createSession(sessionId, sessionData);
}
}
/**
* Undo all changes in the resource, restore the online file.
*
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resourceName The name of the resource to be restored.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void undoChanges(CmsUser currentUser, CmsProject currentProject, String resourceName)
throws CmsException {
CmsProject onlineProject = readProject(currentUser, currentProject, C_PROJECT_ONLINE_ID);
// change folder or file?
if (resourceName.endsWith("/")){
// read the resource from the online project
CmsFolder onlineFolder = readFolder(currentUser, onlineProject, resourceName);
// read the resource from the offline project and change the data
CmsFolder offlineFolder = readFolder(currentUser, currentProject, resourceName);
CmsFolder restoredFolder = new CmsFolder(offlineFolder.getResourceId(), offlineFolder.getParentId(),
offlineFolder.getFileId(), offlineFolder.getAbsolutePath(),
onlineFolder.getType(), onlineFolder.getFlags(),
onlineFolder.getOwnerId(), onlineFolder.getGroupId(),
currentProject.getId(), onlineFolder.getAccessFlags(),
C_STATE_UNCHANGED, offlineFolder.isLockedBy(), offlineFolder.getDateCreated(),
offlineFolder.getDateLastModified(), currentUser.getId(),
currentProject.getId());
// write the file in the offline project
// has the user write-access?
if( accessWrite(currentUser, currentProject, (CmsResource)restoredFolder) ) {
// write-access was granted - write the folder without setting state = changed
m_dbAccess.writeFolder(currentProject, restoredFolder, false);
// restore the properties in the offline project
m_dbAccess.deleteAllProperties(currentProject.getId(),restoredFolder);
Hashtable propertyInfos = m_dbAccess.readAllProperties(onlineProject.getId(),onlineFolder,onlineFolder.getType());
m_dbAccess.writeProperties(propertyInfos,currentProject.getId(),restoredFolder,restoredFolder.getType());
m_propertyCache.clear();
// update the cache
//m_resourceCache.put(currentProject.getId()+C_FOLDER+restoredFolder.getAbsolutePath(),restoredFolder);
m_resourceCache.remove(restoredFolder.getAbsolutePath());
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + restoredFolder.getAbsolutePath(),
CmsException.C_NO_ACCESS);
}
} else {
// read the file from the online project
CmsFile onlineFile = readFile(currentUser, onlineProject, resourceName);
// read the file from the offline project and change the data
CmsFile offlineFile = readFile(currentUser, currentProject, resourceName);
CmsFile restoredFile = new CmsFile(offlineFile.getResourceId(), offlineFile.getParentId(),
offlineFile.getFileId(), offlineFile.getAbsolutePath(),
onlineFile.getType(), onlineFile.getFlags(),
onlineFile.getOwnerId(), onlineFile.getGroupId(),
currentProject.getId(), onlineFile.getAccessFlags(),
C_STATE_UNCHANGED, offlineFile.isLockedBy(), onlineFile.getLauncherType(),
onlineFile.getLauncherClassname(), offlineFile.getDateCreated(),
offlineFile.getDateLastModified(), currentUser.getId(),
onlineFile.getContents(), onlineFile.getLength(), currentProject.getId());
// write the file in the offline project
// has the user write-access?
if( accessWrite(currentUser, currentProject, (CmsResource)restoredFile) ) {
// write-acces was granted - write the file without setting state = changed
m_dbAccess.writeFile(currentProject,
onlineProject(currentUser, currentProject), restoredFile, false);
// restore the properties in the offline project
m_dbAccess.deleteAllProperties(currentProject.getId(),restoredFile);
Hashtable propertyInfos = m_dbAccess.readAllProperties(onlineProject.getId(),onlineFile,onlineFile.getType());
m_dbAccess.writeProperties(propertyInfos,currentProject.getId(),restoredFile,restoredFile.getType());
m_propertyCache.clear();
// update the cache
m_resourceCache.remove(restoredFile.getAbsolutePath());
//m_resourceCache.put(currentProject.getId()+C_FILE+restoredFile.getAbsolutePath(),restoredFile);
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + restoredFile.getAbsolutePath(),
CmsException.C_NO_ACCESS);
}
}
}
/**
* Unlocks all resources in this project.
*
* <B>Security</B>
* Only the admin or the owner of the project can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param id The id of the project to be published.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void unlockProject(CmsUser currentUser, CmsProject currentProject, int id)
throws CmsException {
// read the project.
CmsProject project = readProject(currentUser, currentProject, id);
// check the security
if( (isAdmin(currentUser, currentProject) ||
isManagerOfProject(currentUser, project) ) &&
(project.getFlags() == C_PROJECT_STATE_UNLOCKED )) {
// unlock all resources in the project
m_dbAccess.unlockProject(project);
m_resourceCache.clear();
m_projectCache.clear();
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + id,
CmsException.C_NO_ACCESS);
}
}
/**
* Unlocks a resource.<br>
*
* Only a resource in an offline project can be unlock. The state of the resource
* is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* Only the user who locked a resource can unlock it.
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user had locked the resource before</li>
* </ul>
*
* @param user The user who wants to lock the file.
* @param project The project in which the resource will be used.
* @param resourcename The complete path to the resource to lock.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void unlockResource(CmsUser currentUser,CmsProject currentProject,
String resourcename)
throws CmsException {
CmsResource cmsResource=null;
// read the resource, that should be locked
if (resourcename.endsWith("/")) {
cmsResource = readFolder(currentUser,currentProject,resourcename);
} else {
cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename);
}
// check, if the user may lock the resource
if( accessUnlock(currentUser, currentProject, cmsResource) ) {
// unlock the resource.
if (cmsResource.isLocked()){
// check if the resource is locked by the actual user
if (cmsResource.isLockedBy()==currentUser.getId()) {
// unlock the resource
cmsResource.setLocked(C_UNKNOWN_ID);
//update resource
m_dbAccess.updateLockstate(cmsResource, cmsResource.getLockedInProject());
if (resourcename.endsWith("/")) {
// update the cache
m_resourceCache.remove(resourcename);
//m_resourceCache.put(currentProject.getId()+C_FOLDER+resourcename,(CmsFolder)cmsResource);
} else {
// update the cache
m_resourceCache.remove(resourcename);
//m_resourceCache.put(currentProject.getId()+C_FILE+resourcename,(CmsFile)cmsResource);
}
m_subresCache.clear();
} else {
throw new CmsException("[" + this.getClass().getName() + "] " +
resourcename + CmsException.C_NO_ACCESS);
}
}
// if this resource is a folder -> lock all subresources, too
if(cmsResource.isFolder()) {
Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getAbsolutePath());
Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getAbsolutePath());
CmsResource currentResource;
// lock all files in this folder
for(int i = 0; i < files.size(); i++ ) {
currentResource = (CmsResource)files.elementAt(i);
if (currentResource.getState() != C_STATE_DELETED) {
unlockResource(currentUser, currentProject, currentResource.getAbsolutePath());
}
}
// lock all files in this folder
for(int i = 0; i < folders.size(); i++) {
currentResource = (CmsResource)folders.elementAt(i);
if (currentResource.getState() != C_STATE_DELETED) {
unlockResource(currentUser, currentProject, currentResource.getAbsolutePath());
}
}
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + resourcename,
CmsException.C_NO_ACCESS);
}
}
/**
* Checks if a user is member of a group.<P/>
*
* <B>Security:</B>
* All users are granted, except the anonymous user.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param callingUser The user who wants to use this method.
* @param nameuser The name of the user to check.
* @param groupname The name of the group to check.
* @return True or False
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public boolean userInGroup(CmsUser currentUser, CmsProject currentProject,
String username, String groupname)
throws CmsException {
Vector groups = getGroupsOfUser(currentUser,currentProject,username);
CmsGroup group;
for(int z = 0; z < groups.size(); z++) {
group = (CmsGroup) groups.elementAt(z);
if(groupname.equals(group.getName())) {
return true;
}
}
return false;
}
/**
* Checks ii characters in a String are allowed for filenames
*
* @param filename String to check
*
* @exception throws a exception, if the check fails.
*/
protected void validFilename( String filename )
throws CmsException {
if (filename == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_BAD_NAME);
}
int l = filename.trim().length();
if (l == 0 || filename.startsWith(".")) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_BAD_NAME);
}
for (int i=0; i<l; i++) {
char c = filename.charAt(i);
if (
((c < 'a') || (c > 'z')) &&
((c < '0') || (c > '9')) &&
((c < 'A') || (c > 'Z')) &&
(c != '-') && (c != '.') &&
(c != '_') && (c != '~')
) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename,
CmsException.C_BAD_NAME);
}
}
}
/**
* Checks ii characters in a String are allowed for filenames
*
* @param filename String to check
*
* @exception throws a exception, if the check fails.
*/
protected void validTaskname( String taskname )
throws CmsException {
if (taskname == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname,
CmsException.C_BAD_NAME);
}
int l = taskname.length();
if (l == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname,
CmsException.C_BAD_NAME);
}
for (int i=0; i<l; i++) {
char c = taskname.charAt(i);
if (
((c < '') || (c > '')) &&
((c < '') || (c > '')) &&
((c < 'a') || (c > 'z')) &&
((c < '0') || (c > '9')) &&
((c < 'A') || (c > 'Z')) &&
(c != '-') && (c != '.') &&
(c != '_') && (c != '~') &&
(c != ' ') && (c != '')
) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname,
CmsException.C_BAD_NAME);
}
}
}
/**
* Checks ii characters in a String are allowed for names
*
* @param name String to check
*
* @exception throws a exception, if the check fails.
*/
protected void validName(String name, boolean blank) throws CmsException {
if (name == null || name.length() == 0 || name.trim().length() == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// throw exception if no blanks are allowed
if (!blank) {
int l = name.length();
for (int i = 0; i < l; i++) {
char c = name.charAt(i);
if (c == ' ') {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
}
}
/*
for (int i=0; i<l; i++) {
char c = name.charAt(i);
if (
((c < 'a') || (c > 'z')) &&
((c < '0') || (c > '9')) &&
((c < 'A') || (c > 'Z')) &&
(c != '-') && (c != '.') &&
(c != '_') && (c != '~')
) {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_BAD_NAME);
}
}
*/
}
/**
* Writes the export-path for the system.
* This path is used for db-export and db-import.
*
* <B>Security:</B>
* Users, which are in the group "administrators" are granted.<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param mountpoint The mount point in the Cms filesystem.
*/
public void writeExportPath(CmsUser currentUser, CmsProject currentProject, String path)
throws CmsException {
// check the security
if( isAdmin(currentUser, currentProject) ) {
// security is ok - write the exportpath.
if(m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH) == null) {
// the property wasn't set before.
m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path);
} else {
// overwrite the property.
m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + path,
CmsException.C_NO_ACCESS);
}
}
/**
* Writes a file to the Cms.<br>
*
* A file can only be written to an offline project.<br>
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).<br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who own this file.
* @param currentProject The project in which the resource will be used.
* @param file The name of the file to write.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFile(CmsUser currentUser, CmsProject currentProject,
CmsFile file)
throws CmsException {
// has the user write-access?
if( accessWrite(currentUser, currentProject, (CmsResource)file) ) {
// write-acces was granted - write the file.
m_dbAccess.writeFile(currentProject,
onlineProject(currentUser, currentProject), file,true );
if (file.getState()==C_STATE_UNCHANGED) {
file.setState(C_STATE_CHANGED);
}
// update the cache
m_resourceCache.remove(file.getAbsolutePath());
//m_resourceCache.put(currentProject.getId()+C_FILE+file.getAbsolutePath(),file);
//m_resourceCache.put(currentProject.getId()+C_FILECONTENT+file.getAbsolutePath(),file);
m_subresCache.clear();
m_accessCache.clear();
// inform about the file-system-change
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(),
CmsException.C_NO_ACCESS);
}
}
/**
* Writes the file extensions
*
* <B>Security:</B>
* Users, which are in the group "Administrators" are authorized.<BR/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param extensions Holds extensions as keys and resourcetypes (Stings) as values
*/
public void writeFileExtensions(CmsUser currentUser, CmsProject currentProject,
Hashtable extensions)
throws CmsException {
if (extensions != null) {
if (isAdmin(currentUser, currentProject)) {
Enumeration enu=extensions.keys();
while (enu.hasMoreElements()) {
String key=(String)enu.nextElement();
validFilename(key);
}
if (m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS) == null) {
// the property wasn't set before.
m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions);
} else {
// overwrite the property.
m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions);
}
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + extensions.size(),
CmsException.C_NO_ACCESS);
}
}
}
/**
* Writes a fileheader to the Cms.<br>
*
* A file can only be written to an offline project.<br>
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).<br>
*
* <B>Security:</B>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param currentUser The user who own this file.
* @param currentProject The project in which the resource will be used.
* @param file The file to write.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFileHeader(CmsUser currentUser, CmsProject currentProject,
CmsFile file)
throws CmsException {
// has the user write-access?
if( accessWrite(currentUser, currentProject, (CmsResource)file) ) {
// write-acces was granted - write the file.
m_dbAccess.writeFileHeader(currentProject, file,true );
if (file.getState()==C_STATE_UNCHANGED) {
file.setState(C_STATE_CHANGED);
}
// update the cache
m_resourceCache.remove(file.getAbsolutePath());
//m_resourceCache.put(currentProject.getId()+C_FILE+file.getAbsolutePath(),file);
// inform about the file-system-change
m_subresCache.clear();
m_accessCache.clear();
fileSystemChanged(false);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(),
CmsException.C_NO_ACCESS);
}
}
/**
* Writes an already existing group in the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param group The group that should be written to the Cms.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void writeGroup(CmsUser currentUser, CmsProject currentProject,
CmsGroup group)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
m_dbAccess.writeGroup(group);
m_groupCache.put(group.getName(),group);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + group.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Writes a couple of propertyinformation for a file or folder.
*
* <B>Security</B>
* Only the user is granted, who has the right to write the resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource of which the propertyinformation
* has to be read.
* @param propertyinfos A Hashtable with propertydefinition- propertyinfo-pairs as strings.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeProperties(CmsUser currentUser, CmsProject currentProject,
String resource, Hashtable propertyinfos)
throws CmsException {
// read the resource
CmsResource res = readFileHeader(currentUser,currentProject, resource);
// check the security
if( ! accessWrite(currentUser, currentProject, res) ) {
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_NO_ACCESS);
}
m_dbAccess.writeProperties(propertyinfos,currentProject.getId(),res,res.getType());
m_propertyCache.clear();
if (res.getState()==C_STATE_UNCHANGED) {
res.setState(C_STATE_CHANGED);
}
if(res.isFile()){
m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, false);
// update the cache
m_resourceCache.remove(resource);
//m_resourceCache.put(currentProject.getId()+C_FILE+resource,res);
} else {
m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), false);
// update the cache
m_resourceCache.remove(resource);
//m_resourceCache.put(currentProject.getId()+C_FOLDER+resource,(CmsFolder)res);
}
m_subresCache.clear();
}
/**
* Writes a propertyinformation for a file or folder.
*
* <B>Security</B>
* Only the user is granted, who has the right to write the resource.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param resource The name of the resource of which the propertyinformation has
* to be read.
* @param property The propertydefinition-name of which the propertyinformation has to be set.
* @param value The value for the propertyinfo to be set.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeProperty(CmsUser currentUser, CmsProject currentProject,
String resource, String property, String value)
throws CmsException {
// read the resource
CmsResource res = readFileHeader(currentUser,currentProject, resource);
// check the security
if( ! accessWrite(currentUser, currentProject, res) ) {
throw new CmsException("[" + this.getClass().getName() + "] " + resource,
CmsException.C_NO_ACCESS);
}
m_dbAccess.writeProperty(property, currentProject.getId(),value, res,res.getType());
m_propertyCache.clear();
// set the file-state to changed
if(res.isFile()){
m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true);
if (res.getState()==C_STATE_UNCHANGED) {
res.setState(C_STATE_CHANGED);
}
// update the cache
//m_resourceCache.put(currentProject.getId()+C_FILE+resource,res);
m_resourceCache.remove(resource);
} else {
if (res.getState()==C_STATE_UNCHANGED) {
res.setState(C_STATE_CHANGED);
}
m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true);
// update the cache
m_resourceCache.remove(resource);
//m_resourceCache.put(currentProject.getId()+C_FOLDER+resource,(CmsFolder)res);
}
m_subresCache.clear();
}
/**
* Updates the propertydefinition for the resource type.<BR/>
*
* <B>Security</B>
* Only the admin can do this.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param propertydef The propertydef to be deleted.
*
* @return The propertydefinition, that was written.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition writePropertydefinition(CmsUser currentUser,
CmsProject currentProject,
CmsPropertydefinition propertydef)
throws CmsException {
// check the security
if( isAdmin(currentUser, currentProject) ) {
m_propertyDefVectorCache.clear();
return( m_dbAccess.writePropertydefinition(propertydef) );
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + propertydef.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Writes a new user tasklog for a task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task .
* @param comment Description for the log
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void writeTaskLog(CmsUser currentUser, CmsProject currentProject,
int taskid, String comment)
throws CmsException {
m_dbAccess.writeTaskLog(taskid, currentUser.getId(),
new java.sql.Timestamp(System.currentTimeMillis()),
comment, C_TASKLOG_USER);
}
/**
* Writes a new user tasklog for a task.
*
* <B>Security:</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param taskid The Id of the task .
* @param comment Description for the log
* @param tasktype Type of the tasklog. User tasktypes must be greater then 100.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void writeTaskLog(CmsUser currentUser, CmsProject currentProject,
int taskid, String comment, int type)
throws CmsException {
m_dbAccess.writeTaskLog(taskid, currentUser.getId(),
new java.sql.Timestamp(System.currentTimeMillis()),
comment, type);
}
/**
* Updates the user information.<BR/>
*
* Only the administrator can do this.<P/>
*
* <B>Security:</B>
* Only users, which are in the group "administrators" are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param user The user to be updated.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeUser(CmsUser currentUser, CmsProject currentProject,
CmsUser user)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) || (currentUser.equals(user)) ) {
// prevent the admin to be set disabled!
if( isAdmin(user, currentProject) ) {
user.setEnabled();
}
m_dbAccess.writeUser(user);
// update the cache
m_userCache.put(user.getName()+user.getType(),user);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Updates the user information of a web user.<BR/>
*
* Only a web user can be updated this way.<P/>
*
* <B>Security:</B>
* Only users of the user type webuser can be updated this way.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param user The user to be updated.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeWebUser(CmsUser currentUser, CmsProject currentProject,
CmsUser user)
throws CmsException {
// Check the security
if( user.getType() == C_USER_TYPE_WEBUSER) {
m_dbAccess.writeUser(user);
// update the cache
m_userCache.put(user.getName()+user.getType(),user);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(),
CmsException.C_NO_ACCESS);
}
}
/**
* Changes the project-id of a resource to the new project
* for publishing the resource directly
*
* @param newProjectId The new project-id
* @param resourcename The name of the resource to change
*/
public void changeLockedInProject(int projectId, String resourcename) throws CmsException{
m_dbAccess.changeLockedInProject(projectId, resourcename);
m_resourceCache.remove(resourcename);
}
} |
import java.applet.Applet;
import java.awt.AlphaComposite;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Event;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.TextArea;
import java.awt.TextField;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.URI;
import java.net.URL;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GameSparker extends Applet implements Runnable {
private static final long serialVersionUID = -5976860556958716653L;
Graphics2D rd;
Image offImage;
Thread gamer;
int mload = 1;
boolean exwist = false;
int apx = 0;
int apy = 0;
float apmult = 1.0F;
float reqmult = 0.0F;
int smooth = 1;
int moto = 1;
int lastw = 0;
int lasth = 0;
boolean onbar = false;
boolean oncarm = false;
boolean onstgm = false;
boolean onfulls = false;
Image sizebar;
Image blb;
Image fulls;
Image[] chkbx = new Image[2];
Image[] carmaker = new Image[2];
Image[] stagemaker = new Image[2];
int showsize = 0;
Control[] u = new Control[8];
int mouses = 0;
int xm = 0;
int ym = 0;
int mousew = 0;
boolean lostfcs = false;
boolean moused = false;
int fcscnt = 0;
int nob = 0;
int notb = 0;
int view = 0;
int mvect = 100;
int lmxz = 0;
int shaka = 0;
boolean applejava = false;
TextField tnick;
TextField tpass;
TextField temail;
TextField cmsg;
TextArea mmsg;
Checkbox mycar;
Checkbox notp;
Checkbox keplo;
boolean openm = false;
Smenu sgame = new Smenu(8);
Smenu wgame = new Smenu(4);
Smenu warb = new Smenu(102);
Smenu pgame = new Smenu(11);
Smenu vnpls = new Smenu(5);
Smenu vtyp = new Smenu(6);
Smenu snfmm = new Smenu(12);
Smenu snfm1 = new Smenu(12);
Smenu snfm2 = new Smenu(19);
Smenu mstgs = new Smenu(707);
Smenu mcars = new Smenu(707);
Smenu slaps = new Smenu(17);
Smenu snpls = new Smenu(9);
Smenu snbts = new Smenu(8);
Smenu swait = new Smenu(6);
Smenu sclass = new Smenu(7);
Smenu scars = new Smenu(4);
Smenu sfix = new Smenu(7);
Smenu gmode = new Smenu(3);
Smenu rooms = new Smenu(7);
Smenu sendtyp = new Smenu(6);
Smenu senditem = new Smenu(707);
Smenu clanlev = new Smenu(8);
Smenu clcars = new Smenu(707);
Smenu datat = new Smenu(26);
Smenu ilaps = new Smenu(18);
Smenu icars = new Smenu(5);
Smenu proitem = new Smenu(707);
public void run() {
rd.setColor(new Color(0, 0, 0));
rd.fillRect(0, 0, 800, 450);
repaint();
requestFocus();
if (System.getProperty("java.vendor").toLowerCase().indexOf("apple") != -1) applejava = true;
Medium medium = new Medium();
Trackers trackers = new Trackers();
CheckPoints checkpoints = new CheckPoints();
ContO[] contos = new ContO[124];
CarDefine cardefine = new CarDefine(contos, medium, trackers, this);
xtGraphics var_xtGraphics = new xtGraphics(medium, cardefine, rd, this);
sizebar = var_xtGraphics.getImage("data/sizebar.gif");
blb = var_xtGraphics.getImage("data/b.gif");
fulls = var_xtGraphics.getImage("data/fullscreen.gif");
chkbx[0] = var_xtGraphics.getImage("data/checkbox1.gif");
chkbx[1] = var_xtGraphics.getImage("data/checkbox2.gif");
carmaker[0] = var_xtGraphics.getImage("data/carmaker1.gif");
carmaker[1] = var_xtGraphics.getImage("data/carmaker2.gif");
stagemaker[0] = var_xtGraphics.getImage("data/stagemaker1.gif");
stagemaker[1] = var_xtGraphics.getImage("data/stagemaker2.gif");
var_xtGraphics.loaddata();
Login login = null;
Lobby lobby = null;
Globe globe = null;
boolean bool = false;
UDPMistro udpmistro = new UDPMistro();
Record record = new Record(medium);
loadbase(contos, medium, trackers, var_xtGraphics, false);
ContO[] contos_0_ = new ContO[10000];
Mad[] mads = new Mad[8];
for (int i = 0; i < 8; i++) {
mads[i] = new Mad(cardefine, medium, record, var_xtGraphics, i);
u[i] = new Control(medium);
}
float f = 47.0F;
readcookies(var_xtGraphics, cardefine, contos);
(var_xtGraphics).testdrive = Madness.testdrive;
if ((var_xtGraphics).testdrive != 0) {
if ((var_xtGraphics).testdrive <= 2) {
(var_xtGraphics).sc[0] = cardefine.loadcar(Madness.testcar, 16);
if ((var_xtGraphics).sc[0] != -1)
(var_xtGraphics).fase = -9;
else {
Madness.testcar = "Failx12";
Madness.carmaker();
}
} else {
(checkpoints).name = Madness.testcar;
(var_xtGraphics).fase = -9;
}
}
var_xtGraphics.stoploading();
requestFocus();
if ((var_xtGraphics).testdrive == 0 && (var_xtGraphics).firstime) setupini();
System.gc();
Date date = new Date();
long l = 0L;
long l_1_ = date.getTime();
float f_2_ = 30.0F;
boolean bool_3_ = false;
int i = 30;
int i_4_ = 530;
int i_5_ = 0;
int i_6_ = 0;
int i_7_ = 0;
int i_8_ = 0;
int i_9_ = 0;
boolean bool_10_ = false;
final int TICKS_PER_SECOND = 25;
final int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
final int MAX_FRAMESKIP = 5;
double next_game_tick = System.currentTimeMillis();
int loops;
while (true) {
loops = 0;
while (System.currentTimeMillis() > next_game_tick && loops < MAX_FRAMESKIP) {
date = new Date();
long l_11_ = date.getTime();
if ((var_xtGraphics).fase == 111) {
if (mouses == 1) i_7_ = 800;
if (i_7_ < 800) {
var_xtGraphics.clicknow();
i_7_++;
} else {
i_7_ = 0;
if (!exwist)
(var_xtGraphics).fase = 9;
mouses = 0;
lostfcs = false;
}
}
if ((var_xtGraphics).fase == 9) {
if (i_7_ < 76) {
var_xtGraphics.rad(i_7_);
catchlink();
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
i_7_++;
} else {
i_7_ = 0;
(var_xtGraphics).fase = 10;
mouses = 0;
u[0].falseo(0);
}
}
if ((var_xtGraphics).fase == -9) {
if ((var_xtGraphics).loadedt) {
var_xtGraphics.mainbg(-101);
rd.setColor(new Color(0, 0, 0));
rd.fillRect(0, 0, 800, 450);
repaint();
(var_xtGraphics).strack.unload();
(var_xtGraphics).strack = null;
(var_xtGraphics).flexpix = null;
(var_xtGraphics).fleximg = null;
System.gc();
(var_xtGraphics).loadedt = false;
}
if (i_7_ < 2) {
var_xtGraphics.mainbg(-101);
rd.setColor(new Color(0, 0, 0));
rd.fillRect(65, 25, 670, 400);
i_7_++;
} else {
checkmemory(var_xtGraphics);
var_xtGraphics.inishcarselect(contos);
i_7_ = 0;
(var_xtGraphics).fase = 7;
mvect = 50;
mouses = 0;
}
}
if ((var_xtGraphics).fase == 8) {
var_xtGraphics.credits(u[0], xm, ym, mouses);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if ((var_xtGraphics).flipo <= 100) catchlink();
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == 10) {
mvect = 100;
var_xtGraphics.maini(u[0]);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == 102) {
mvect = 100;
if ((var_xtGraphics).loadedt) {
rd.setColor(new Color(0, 0, 0));
rd.fillRect(0, 0, 800, 450);
repaint();
checkmemory(var_xtGraphics);
(var_xtGraphics).strack.unload();
(var_xtGraphics).strack = null;
(var_xtGraphics).flexpix = null;
(var_xtGraphics).fleximg = null;
System.gc();
(var_xtGraphics).loadedt = false;
}
if ((var_xtGraphics).testdrive == 1 || (var_xtGraphics).testdrive == 2) Madness.carmaker();
if ((var_xtGraphics).testdrive == 3 || (var_xtGraphics).testdrive == 4) Madness.stagemaker();
var_xtGraphics.maini2(u[0], xm, ym, mouses);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == -22) {
(checkpoints).name = Madness.testcar;
(checkpoints).stage = -1;
loadstage(contos_0_, contos, medium, trackers, checkpoints,
var_xtGraphics, mads, record);
if ((checkpoints).stage == -3) {
Madness.testcar = "Failx12";
Madness.stagemaker();
}
}
if ((var_xtGraphics).fase == 11) {
var_xtGraphics.inst(u[0]);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == -5) {
mvect = 100;
var_xtGraphics.finish(checkpoints, contos, u[0], xm, ym, moused);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == 7) {
var_xtGraphics.carselect(u[0], contos,
mads[0], xm, ym, moused);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
drawms();
}
if ((var_xtGraphics).fase == 6) {
var_xtGraphics.musicomp((checkpoints).stage, u[0]);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == 5) {
mvect = 100;
var_xtGraphics.loadmusic((checkpoints).stage, (checkpoints).trackname, (checkpoints).trackvol);
}
if ((var_xtGraphics).fase == 4) {
var_xtGraphics.cantgo(u[0]);
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == 3) {
rd.setColor(new Color(0, 0, 0));
rd.fillRect(65, 25, 670, 400);
repaint();
var_xtGraphics.inishstageselect(checkpoints);
}
if ((var_xtGraphics).fase == 2) {
mvect = 100;
var_xtGraphics.loadingstage((checkpoints).stage,
true);
(checkpoints).nfix = 0;
(checkpoints).notb = false;
loadstage(contos_0_, contos, medium, trackers, checkpoints,
var_xtGraphics, mads, record);
u[0].falseo(0);
(udpmistro).freg = 0.0F;
mvect = 20;
}
if ((var_xtGraphics).fase == 1) {
var_xtGraphics.trackbg(false);
rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
if ((checkpoints).stage != -3) {
medium.aroundtrack(checkpoints);
if ((medium).hit == 5000 && mvect < 40) mvect++;
int i_12_ = 0;
int[] is = new int[1000];
for (int i_13_ = (var_xtGraphics).nplayers;
i_13_ < notb; i_13_++) {
if ((contos_0_[i_13_]).dist != 0) {
is[i_12_] = i_13_;
i_12_++;
} else contos_0_[i_13_].d(rd);
}
int[] is_14_ = new int[i_12_];
for (int i_15_ = 0; i_15_ < i_12_; i_15_++)
is_14_[i_15_] = 0;
for (int i_16_ = 0; i_16_ < i_12_; i_16_++) {
for (int i_17_ = i_16_ + 1; i_17_ < i_12_; i_17_++) {
if ((contos_0_[is[i_16_]]).dist != (contos_0_[is[i_17_]]).dist) {
if ((contos_0_[is[i_16_]]).dist < (contos_0_[is[i_17_]]).dist) is_14_[i_16_]++;
else is_14_[i_17_]++;
} else if (i_17_ > i_16_) is_14_[i_16_]++;
else is_14_[i_17_]++;
}
}
for (int i_18_ = 0; i_18_ < i_12_; i_18_++) {
for (int i_19_ = 0; i_19_ < i_12_; i_19_++) {
if (is_14_[i_19_] == i_18_) contos_0_[is[i_19_]].d(rd);
}
}
}
if (!openm) var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
var_xtGraphics.stageselect(checkpoints, u[0], xm, ym, moused);
drawms();
}
if ((var_xtGraphics).fase == 1177) {
mvect = 100;
if (!bool) {
if ((var_xtGraphics).loadedt) {
rd.setColor(new Color(0, 0, 0));
rd.fillRect(0, 0, 800, 450);
repaint();
checkmemory(var_xtGraphics);
(var_xtGraphics).strack.unload();
(var_xtGraphics).strack = null;
(var_xtGraphics).flexpix = null;
(var_xtGraphics).fleximg = null;
System.gc();
(var_xtGraphics).loadedt = false;
}
(var_xtGraphics).intertrack.unloadimod();
rd.setColor(new Color(0, 0, 0));
rd.fillRect(65, 25, 670, 400);
if (mload > 0) rd.drawImage(((
var_xtGraphics)
.mload),
259, 195, this);
repaint();
if (mload == 2) {
cardefine.loadready();
loadbase(contos, medium, trackers, var_xtGraphics,
true);
readcookies(var_xtGraphics, cardefine, contos);
mload = -1;
}
System.gc();
login = new Login(medium, rd,
var_xtGraphics, this);
globe = new Globe(rd, var_xtGraphics,
medium, login, cardefine, checkpoints,
contos, contos_0_, this);
lobby = new Lobby(medium, rd, login,
globe, var_xtGraphics, cardefine, this);
bool = true;
}
if ((login).fase != 18) {
boolean bool_20_ = false;
if ((login).fase == 0) login.inishmulti();
if ((login).fase >= 1 && (login).fase <= 11) login.multistart(contos, xm, ym, moused);
if ((login).fase >= 12 && (login).fase <= 17) {
if ((globe).open != 452) login.multimode(contos);
else bool_20_ = true;
globe.dome(0, xm, ym, moused, u[0]);
}
if ((login).justlog) {
if (!(var_xtGraphics).clan.equals(""))
(globe).itab = 2;
(login).justlog = false;
}
if (!bool_20_) {
login.ctachm(xm, ym, mouses, u[0], lobby);
mvect = 50;
} else {
drawms();
mvect = 100;
}
if (mouses == 1) mouses = 11;
if (mouses <= -1) {
mouses
if (mouses == -4) mouses = 0;
}
if (mousew != 0) {
if (mousew > 0) mousew
else mousew++;
}
} else {
boolean bool_21_ = false;
if ((lobby).fase == 0) {
lobby.inishlobby();
mvect = 100;
}
if ((lobby).fase == 1) {
if ((globe).open >= 2 && (globe).open < 452) openm = true;
if ((globe).open != 452) lobby.lobby(xm, ym, moused, mousew,
checkpoints, u[0],
contos);
else bool_21_ = true;
globe.dome((lobby).conon, xm, ym, moused, u[0]);
if ((lobby).loadstage > 0) {
setCursor(new Cursor(3));
drawms();
repaint();
(trackers).nt = 0;
if (loadstagePreview((lobby).loadstage, "",
contos_0_, contos, medium,
checkpoints)) {
(lobby).gstagename = (checkpoints).name;
(lobby).gstagelaps = (checkpoints).nlaps;
(lobby).loadstage = -(lobby).loadstage;
} else {
(lobby).loadstage = 0;
(checkpoints).name = "";
}
setCursor(new Cursor(0));
}
if ((lobby).msload != 0) {
setCursor(new Cursor(3));
drawms();
repaint();
if ((lobby).msload == 1) cardefine.loadmystages(checkpoints);
if ((lobby).msload == 7) cardefine.loadclanstages((
var_xtGraphics)
.clan);
if ((lobby).msload == 3 || (lobby).msload == 4) cardefine.loadtop20((lobby).msload);
(lobby).msload = 0;
setCursor(new Cursor(0));
}
}
if ((lobby).fase == 3) {
var_xtGraphics.trackbg(false);
(medium).trk = 0;
(medium).focus_point = 400;
(medium).crs = true;
(medium).x = -335;
(medium).y = 0;
(medium).z = -50;
(medium).xz = 0;
(medium).zy = 20;
(medium).ground = -2000;
mvect = 100;
(lobby).fase = 1;
}
if ((lobby).fase == 4) {
mvect = 50;
rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
medium.d(rd);
medium.aroundtrack(checkpoints);
int i_22_ = 0;
int[] is = new int[1000];
for (int i_23_ = 0; i_23_ < nob;
i_23_++) {
if ((contos_0_[i_23_]).dist != 0) {
is[i_22_] = i_23_;
i_22_++;
} else contos_0_[i_23_].d(rd);
}
int[] is_24_ = new int[i_22_];
for (int i_25_ = 0; i_25_ < i_22_; i_25_++)
is_24_[i_25_] = 0;
for (int i_26_ = 0; i_26_ < i_22_; i_26_++) {
for (int i_27_ = i_26_ + 1; i_27_ < i_22_;
i_27_++) {
if ((contos_0_[is[i_26_]]).dist != (contos_0_[is[i_27_]]).dist) {
if ((contos_0_[is[i_26_]]).dist < (contos_0_[is[i_27_]]).dist) is_24_[i_26_]++;
else is_24_[i_27_]++;
} else if (i_27_ > i_26_) is_24_[i_26_]++;
else is_24_[i_27_]++;
}
}
for (int i_28_ = 0; i_28_ < i_22_; i_28_++) {
for (int i_29_ = 0; i_29_ < i_22_; i_29_++) {
if (is_24_[i_29_] == i_28_) contos_0_[is[i_29_]].d(rd);
}
}
rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
lobby.stageselect(checkpoints, u[0], xm, ym, moused);
if ((lobby).plsndt == 1) {
mvect = 70;
repaint();
setCursor(new Cursor(3));
var_xtGraphics.loadstrack((checkpoints).stage, (checkpoints).trackname, (checkpoints).trackvol);
(var_xtGraphics).strack.play();
(lobby).plsndt = 2;
moused = false;
mouses = 0;
}
}
if ((lobby).fase == 2) {
int i_30_ = 0;
for (int i_31_ = 0; i_31_ < (lobby).ngm;
i_31_++) {
if ((lobby).ongame == (lobby).gnum[i_31_]) i_30_ = i_31_;
}
boolean bool_32_ = false;
if ((lobby).gstgn[i_30_] > 0) {
if ((lobby).gstgn[i_30_] == -(lobby).loadstage) bool_32_ = true;
} else if ((lobby).gstages[i_30_].equals((checkpoints).name)) bool_32_ = true;
if (bool_32_) {
(lobby).fase = 4;
(lobby).addstage = 0;
} else {
var_xtGraphics.loadingstage(((lobby).gstgn[i_30_]),
false);
(trackers).nt = 0;
if (loadstagePreview((lobby).gstgn[i_30_], ((lobby).gstages[i_30_]),
contos_0_, contos, medium,
checkpoints)) {
(lobby).loadstage = -(lobby).gstgn[i_30_];
(lobby).fase = 4;
(lobby).addstage = 0;
} else {
(lobby).loadstage = 0;
(checkpoints).name = "";
(lobby).fase = 3;
}
}
}
if ((lobby).fase == 76) {
(checkpoints).nlaps = (lobby).laps;
(checkpoints).stage = (lobby).stage;
(checkpoints).name = (lobby).stagename;
(checkpoints).nfix = (lobby).nfix;
(checkpoints).notb = (lobby).notb;
(var_xtGraphics).fase = 21;
(u[0]).multion = (var_xtGraphics).multion;
}
if ((globe).loadwbgames == 7) {
repaint();
globe.redogame();
}
if (!openm) {
if (!bool_21_) lobby.ctachm(xm, ym, mouses, u[0]);
} else mouses = 0;
drawms();
if ((lobby).fase == 1) lobby.preforma(xm, ym);
if ((lobby).loadwarb) {
repaint();
globe.loadwarb();
(lobby).loadwarb = false;
}
if ((globe).loadwbgames == 1) {
repaint();
globe.loadwgames();
}
if (mouses == 1) mouses = 11;
if (mouses <= -1) {
mouses
if (mouses == -4) mouses = 0;
}
if (mousew != 0) {
if (mousew > 0) mousew
else mousew++;
if (!(lobby).zeromsw) mousew = 0;
}
}
}
if ((var_xtGraphics).fase == 24) {
login.endcons();
login = null;
lobby = null;
globe = null;
bool = false;
System.gc();
System.runFinalization();
if (!(var_xtGraphics).mtop) {
(var_xtGraphics).fase = 102;
(var_xtGraphics).opselect = 2;
} else {
(var_xtGraphics).fase = 10;
(var_xtGraphics).opselect = 1;
}
}
if ((var_xtGraphics).fase == 23) {
if ((login).fase == 18)
(var_xtGraphics).playingame = -101;
login.stopallnow();
lobby.stopallnow();
globe.stopallnow();
login = null;
lobby = null;
globe = null;
hidefields();
bool = false;
System.gc();
System.runFinalization();
(var_xtGraphics).fase = -9;
}
if ((var_xtGraphics).fase == 22) {
loadstage(contos_0_, contos, medium, trackers, checkpoints,
var_xtGraphics, mads, record);
if ((checkpoints).stage != -3) {
if ((var_xtGraphics).lan && (var_xtGraphics).im == 0) udpmistro.UDPLanServer((var_xtGraphics).nplayers, (var_xtGraphics).server, (var_xtGraphics).servport, (var_xtGraphics).playingame);
u[0].falseo(2);
requestFocus();
} else(var_xtGraphics).fase = 1177;
}
if ((var_xtGraphics).fase == 21) {
login.endcons();
login = null;
lobby = null;
globe = null;
bool = false;
System.gc();
System.runFinalization();
(var_xtGraphics).fase = 22;
}
if ((var_xtGraphics).fase == 0) {
for (int i_33_ = 0;
i_33_ < (var_xtGraphics).nplayers; i_33_++) {
if ((mads[i_33_]).newcar) {
int i_34_ = (contos_0_[i_33_]).xz;
int i_35_ = (contos_0_[i_33_]).xy;
int i_36_ = (contos_0_[i_33_]).zy;
contos_0_[i_33_] = new ContO(contos[(mads[i_33_]).cn], (contos_0_[i_33_]).x, (contos_0_[i_33_]).y, (contos_0_[i_33_]).z, 0);
(contos_0_[i_33_]).xz = i_34_;
(contos_0_[i_33_]).xy = i_35_;
(contos_0_[i_33_]).zy = i_36_;
(mads[i_33_]).newcar = false;
}
}
medium.d(rd);
int i_37_ = 0;
int[] is = new int[10000];
for (int i_38_ = 0; i_38_ < nob;
i_38_++) {
if ((contos_0_[i_38_]).dist != 0) {
is[i_37_] = i_38_;
i_37_++;
} else contos_0_[i_38_].d(rd);
}
int[] is_39_ = new int[i_37_];
int[] is_40_ = new int[i_37_];
for (int i_41_ = 0; i_41_ < i_37_; i_41_++)
is_39_[i_41_] = 0;
for (int i_42_ = 0; i_42_ < i_37_; i_42_++) {
for (int i_43_ = i_42_ + 1; i_43_ < i_37_; i_43_++) {
if ((contos_0_[is[i_42_]]).dist < (contos_0_[is[i_43_]]).dist) is_39_[i_42_]++;
else is_39_[i_43_]++;
}
is_40_[is_39_[i_42_]] = i_42_;
}
for (int i_44_ = 0; i_44_ < i_37_; i_44_++)
contos_0_[is[is_40_[i_44_]]].d(rd);
if ((var_xtGraphics).starcnt == 0) {
for (int i_45_ = 0;
i_45_ < (var_xtGraphics).nplayers;
i_45_++) {
for (int i_46_ = 0;
i_46_ < (var_xtGraphics).nplayers;
i_46_++) {
if (i_46_ != i_45_) mads[i_45_].colide(contos_0_[i_45_],
mads[i_46_],
contos_0_[i_46_]);
}
}
for (int i_47_ = 0;
i_47_ < (var_xtGraphics).nplayers;
i_47_++)
mads[i_47_].drive(u[i_47_],
contos_0_[i_47_], trackers,
checkpoints);
for (int i_48_ = 0;
i_48_ < (var_xtGraphics).nplayers;
i_48_++)
record.rec(contos_0_[i_48_], i_48_, (mads[i_48_]).squash, (mads[i_48_]).lastcolido, (mads[i_48_]).cntdest, 0);
checkpoints.checkstat(mads, contos_0_, record, ((var_xtGraphics)
.nplayers), (var_xtGraphics).im, 0);
for (int i_49_ = 1;
i_49_ < (var_xtGraphics).nplayers;
i_49_++)
u[i_49_].preform(mads[i_49_],
contos_0_[i_49_],
checkpoints,
trackers);
} else {
if ((var_xtGraphics).starcnt == 130) {
(medium).adv = 1900;
(medium).zy = 40;
(medium).vxz = 70;
rd.setColor(new Color(255, 255,
255));
rd.fillRect(0, 0, 800, 450);
}
if ((var_xtGraphics).starcnt != 0)
(var_xtGraphics).starcnt
}
if ((var_xtGraphics).starcnt < 38) {
if (view == 0) {
medium.follow(contos_0_[0], (mads[0]).cxz, ((u[0])
.lookback));
var_xtGraphics.stat(mads[0], contos_0_[0], checkpoints, u[0], true);
if ((mads[0]).outshakedam > 0) {
shaka = (mads[0]).outshakedam / 20;
if (shaka > 25) shaka = 25;
}
mvect = 65 + Math.abs(lmxz - (medium).xz) / 5 * 100;
if (mvect > 90) mvect = 90;
lmxz = (medium).xz;
}
if (view == 1) {
medium.around(contos_0_[0], false);
var_xtGraphics.stat(mads[0], contos_0_[0], checkpoints, u[0], false);
mvect = 80;
}
if (view == 2) {
medium.watch(contos_0_[0], (mads[0]).mxz);
var_xtGraphics.stat(mads[0], contos_0_[0], checkpoints, u[0], false);
mvect = 65 + Math.abs(lmxz - (medium).xz) / 5 * 100;
if (mvect > 90) mvect = 90;
lmxz = (medium).xz;
}
if (mouses == 1) {
(u[0]).enter = true;
mouses = 0;
}
} else {
int i_50_ = 3;
if ((var_xtGraphics).nplayers == 1) i_50_ = 0;
medium.around(contos_0_[i_50_], true);
mvect = 80;
if ((u[0]).enter || (u[0]).handb) {
(var_xtGraphics).starcnt = 38;
(u[0]).enter = false;
(u[0]).handb = false;
}
if ((var_xtGraphics).starcnt == 38) {
mouses = 0;
(medium).vert = false;
(medium).adv = 900;
(medium).vxz = 180;
checkpoints.checkstat(mads, contos_0_, record, ((var_xtGraphics)
.nplayers), (var_xtGraphics).im,
0);
medium.follow(contos_0_[0], (mads[0]).cxz, 0);
var_xtGraphics.stat(mads[0], contos_0_[0], checkpoints, u[0], true);
rd.setColor(new Color(255, 255,
255));
rd.fillRect(0, 0, 800, 450);
}
}
}
if ((var_xtGraphics).fase == 7001) {
for (int i_51_ = 0;
i_51_ < (var_xtGraphics).nplayers; i_51_++) {
if ((mads[i_51_]).newedcar == 0 && (mads[i_51_]).newcar) {
int i_52_ = (contos_0_[i_51_]).xz;
int i_53_ = (contos_0_[i_51_]).xy;
int i_54_ = (contos_0_[i_51_]).zy;
var_xtGraphics.colorCar(contos[(mads[i_51_]).cn],
i_51_);
contos_0_[i_51_] = new ContO(contos[(mads[i_51_]).cn], (contos_0_[i_51_]).x, (contos_0_[i_51_]).y, (contos_0_[i_51_]).z, 0);
(contos_0_[i_51_]).xz = i_52_;
(contos_0_[i_51_]).xy = i_53_;
(contos_0_[i_51_]).zy = i_54_;
(mads[i_51_]).newedcar = 20;
}
}
medium.d(rd);
int i_55_ = 0;
int[] is = new int[10000];
for (int i_56_ = 0; i_56_ < nob;
i_56_++) {
if ((contos_0_[i_56_]).dist != 0) {
is[i_55_] = i_56_;
i_55_++;
} else contos_0_[i_56_].d(rd);
}
int[] is_57_ = new int[i_55_];
int[] is_58_ = new int[i_55_];
for (int i_59_ = 0; i_59_ < i_55_; i_59_++)
is_57_[i_59_] = 0;
for (int i_60_ = 0; i_60_ < i_55_; i_60_++) {
for (int i_61_ = i_60_ + 1; i_61_ < i_55_; i_61_++) {
if ((contos_0_[is[i_60_]]).dist < (contos_0_[is[i_61_]]).dist) is_57_[i_60_]++;
else is_57_[i_61_]++;
}
is_58_[is_57_[i_60_]] = i_60_;
}
for (int i_62_ = 0; i_62_ < i_55_; i_62_++) {
if ((is[is_58_[i_62_]] < (var_xtGraphics).nplayers) && (is[is_58_[i_62_]] != (var_xtGraphics).im)) udpmistro.readContOinfo(contos_0_[is[is_58_[i_62_]]],
is[is_58_[i_62_]]);
contos_0_[is[is_58_[i_62_]]].d(rd);
}
if ((var_xtGraphics).starcnt == 0) {
if ((var_xtGraphics).multion == 1) {
int i_63_ = 1;
for (int i_64_ = 0;
i_64_ < (var_xtGraphics).nplayers;
i_64_++) {
if ((var_xtGraphics).im != i_64_) {
udpmistro.readinfo(mads[i_64_], contos_0_[i_64_], u[i_63_], i_64_, (checkpoints).dested);
i_63_++;
}
}
} else {
for (int i_65_ = 0;
i_65_ < (var_xtGraphics).nplayers;
i_65_++)
udpmistro.readinfo(mads[i_65_], contos_0_[i_65_], u[i_65_],
i_65_, ((checkpoints)
.dested));
}
for (int i_66_ = 0;
i_66_ < (var_xtGraphics).nplayers;
i_66_++) {
for (int i_67_ = 0;
i_67_ < (var_xtGraphics).nplayers;
i_67_++) {
if (i_67_ != i_66_) mads[i_66_].colide(contos_0_[i_66_],
mads[i_67_],
contos_0_[i_67_]);
}
}
if ((var_xtGraphics).multion == 1) {
int i_68_ = 1;
for (int i_69_ = 0;
i_69_ < (var_xtGraphics).nplayers;
i_69_++) {
if ((var_xtGraphics).im != i_69_) {
mads[i_69_].drive((u[i_68_]),
contos_0_[i_69_], trackers,
checkpoints);
i_68_++;
} else mads[i_69_].drive(u[0],
contos_0_[i_69_], trackers,
checkpoints);
}
for (int i_70_ = 0;
i_70_ < (var_xtGraphics).nplayers;
i_70_++)
record.rec(contos_0_[i_70_], i_70_, (mads[i_70_]).squash, (mads[i_70_]).lastcolido, (mads[i_70_]).cntdest, (var_xtGraphics).im);
} else {
for (int i_71_ = 0;
i_71_ < (var_xtGraphics).nplayers;
i_71_++)
mads[i_71_].drive(u[i_71_],
contos_0_[i_71_], trackers,
checkpoints);
}
checkpoints.checkstat(mads, contos_0_, record, ((var_xtGraphics)
.nplayers), (var_xtGraphics).im, ((var_xtGraphics)
.multion));
} else {
if ((var_xtGraphics).starcnt == 130) {
(medium).adv = 1900;
(medium).zy = 40;
(medium).vxz = 70;
rd.setColor(new Color(255, 255,
255));
rd.fillRect(0, 0, 800, 450);
repaint();
if ((var_xtGraphics).lan) {
udpmistro.UDPConnectLan((var_xtGraphics).localserver, (var_xtGraphics).nplayers, (var_xtGraphics).im);
if ((var_xtGraphics).im == 0) var_xtGraphics.setbots(((udpmistro)
.isbot), ((udpmistro)
.frame));
} else udpmistro.UDPConnectOnline((var_xtGraphics).server, (var_xtGraphics).gameport, (var_xtGraphics).nplayers, (var_xtGraphics).im);
if ((var_xtGraphics).multion >= 2) {
(var_xtGraphics).im = (int)(Math.random() * (double)(
var_xtGraphics).nplayers);
(var_xtGraphics).starcnt = 0;
}
}
if ((var_xtGraphics).starcnt == 50)
(udpmistro).frame[(udpmistro).im][0] = 0;
if ((var_xtGraphics).starcnt != 39 && (var_xtGraphics).starcnt != 0)
(var_xtGraphics).starcnt
if ((udpmistro).go && (var_xtGraphics).starcnt >= 39) {
(var_xtGraphics).starcnt = 38;
if ((var_xtGraphics).lan) {
int i_72_ = (checkpoints).stage;
if (i_72_ < 0) i_72_ = 33;
if ((var_xtGraphics).loadedt)
(var_xtGraphics).strack.play();
}
}
}
if ((var_xtGraphics).lan && (udpmistro).im == 0) {
for (int i_73_ = 2;
i_73_ < (var_xtGraphics).nplayers;
i_73_++) {
if ((udpmistro).isbot[i_73_]) {
u[i_73_].preform(mads[i_73_], (contos_0_[i_73_]),
checkpoints,
trackers);
udpmistro.setinfo(mads[i_73_], contos_0_[i_73_], u[i_73_], ((checkpoints).pos[i_73_]), ((checkpoints)
.magperc[i_73_]),
false, i_73_);
}
}
}
if ((var_xtGraphics).starcnt < 38) {
if ((var_xtGraphics).multion == 1) {
udpmistro.setinfo((mads[(var_xtGraphics).im]), (contos_0_[(var_xtGraphics).im]), u[0], ((checkpoints).pos[(var_xtGraphics).im]), ((checkpoints).magperc[(var_xtGraphics).im]), (var_xtGraphics).holdit, (var_xtGraphics).im);
if (view == 0) {
medium.follow((contos_0_[(var_xtGraphics).im]), ((mads[(
var_xtGraphics).im])
.cxz), ((u[0])).lookback);
var_xtGraphics.stat(mads[(var_xtGraphics).im],
contos_0_[(var_xtGraphics).im],
checkpoints, u[0], true);
if (((mads[(var_xtGraphics).im])
.outshakedam) > 0) {
shaka = ((
mads[(var_xtGraphics).im])
.outshakedam) / 20;
if (shaka > 25) shaka = 25;
}
mvect = 65 + (Math.abs(lmxz - (medium).xz) / 5 * 100);
if (mvect > 90) mvect = 90;
lmxz = (medium).xz;
}
if (view == 1) {
medium.around((contos_0_[(var_xtGraphics).im]),
false);
var_xtGraphics.stat(mads[(var_xtGraphics).im],
contos_0_[(var_xtGraphics).im],
checkpoints, u[0],
false);
mvect = 80;
}
if (view == 2) {
medium.watch((contos_0_[(var_xtGraphics).im]), ((mads[(
var_xtGraphics).im])
.mxz));
var_xtGraphics.stat(mads[(var_xtGraphics).im],
contos_0_[(var_xtGraphics).im],
checkpoints, u[0],
false);
mvect = 65 + (Math.abs(lmxz - (medium).xz) / 5 * 100);
if (mvect > 90) mvect = 90;
lmxz = (medium).xz;
}
} else {
if (view == 0) {
medium.getaround(contos_0_[(
var_xtGraphics).im]);
mvect = 80;
}
if (view == 1) {
medium.getfollow(contos_0_[(var_xtGraphics).im], (
mads[(var_xtGraphics).im]).cxz, ((u[0])
.lookback));
mvect = 65 + (Math.abs(lmxz - (medium).xz) / 5 * 100);
if (mvect > 90) mvect = 90;
lmxz = (medium).xz;
}
if (view == 2) {
medium.watch((contos_0_[(var_xtGraphics).im]), ((mads[(
var_xtGraphics).im])
.mxz));
mvect = 65 + (Math.abs(lmxz - (medium).xz) / 5 * 100);
if (mvect > 90) mvect = 90;
lmxz = (medium).xz;
}
var_xtGraphics.stat(mads[(var_xtGraphics).im],
contos_0_[(var_xtGraphics).im],
checkpoints, u[0], true);
}
if (mouses == 1) {
if ((var_xtGraphics).holdit && (var_xtGraphics).exitm != 4 && (var_xtGraphics).multion == 1)
(u[0]).enter = true;
mouses = 0;
}
} else {
medium.around(contos_0_[(var_xtGraphics).im],
true);
mvect = 80;
if ((var_xtGraphics).starcnt == 39) var_xtGraphics.waitenter();
if ((var_xtGraphics).starcnt == 38) {
(var_xtGraphics).forstart = 0;
mouses = 0;
(medium).vert = false;
(medium).adv = 900;
(medium).vxz = 180;
checkpoints.checkstat(mads, contos_0_, record, ((var_xtGraphics)
.nplayers), (var_xtGraphics).im, ((var_xtGraphics)
.multion));
medium.follow((contos_0_[(var_xtGraphics).im]), ((
mads[(var_xtGraphics).im])
.cxz),
0);
var_xtGraphics.stat(mads[(var_xtGraphics).im],
contos_0_[(var_xtGraphics).im],
checkpoints, u[0], true);
rd.setColor(new Color(255, 255,
255));
rd.fillRect(0, 0, 800, 450);
}
}
var_xtGraphics.multistat(u[0],
checkpoints, xm, ym, moused,
udpmistro);
}
if ((var_xtGraphics).fase == -1) {
if (i_6_ == 0) {
for (int i_74_ = 0;
i_74_ < (var_xtGraphics).nplayers;
i_74_++) {
(record).ocar[i_74_] = new ContO(contos_0_[i_74_], 0, 0, 0, 0);
contos_0_[i_74_] = new ContO((record).car[0][i_74_], 0, 0,
0, 0);
}
}
medium.d(rd);
int i_75_ = 0;
int[] is = new int[10000];
for (int i_76_ = 0; i_76_ < nob;
i_76_++) {
if ((contos_0_[i_76_]).dist != 0) {
is[i_75_] = i_76_;
i_75_++;
} else contos_0_[i_76_].d(rd);
}
int[] is_77_ = new int[i_75_];
for (int i_78_ = 0; i_78_ < i_75_; i_78_++)
is_77_[i_78_] = 0;
for (int i_79_ = 0; i_79_ < i_75_; i_79_++) {
for (int i_80_ = i_79_ + 1; i_80_ < i_75_; i_80_++) {
if ((contos_0_[is[i_79_]]).dist != (contos_0_[is[i_80_]]).dist) {
if ((contos_0_[is[i_79_]]).dist < (contos_0_[is[i_80_]]).dist) is_77_[i_79_]++;
else is_77_[i_80_]++;
} else if (i_80_ > i_79_) is_77_[i_79_]++;
else is_77_[i_80_]++;
}
}
for (int i_81_ = 0; i_81_ < i_75_; i_81_++) {
for (int i_82_ = 0; i_82_ < i_75_; i_82_++) {
if (is_77_[i_82_] == i_81_) contos_0_[is[i_82_]].d(rd);
}
}
if ((u[0]).enter || (u[0]).handb || mouses == 1) {
i_6_ = 299;
(u[0]).enter = false;
(u[0]).handb = false;
mouses = 0;
}
for (int i_83_ = 0;
i_83_ < (var_xtGraphics).nplayers; i_83_++) {
if ((record).fix[i_83_] == i_6_) {
if ((contos_0_[i_83_]).dist == 0)
(contos_0_[i_83_]).fcnt = 8;
else(contos_0_[i_83_]).fix = true;
}
if ((contos_0_[i_83_]).fcnt == 7 || (contos_0_[i_83_]).fcnt == 8) {
contos_0_[i_83_] = new ContO(contos[(mads[i_83_]).cn], 0, 0,
0, 0);
(record).cntdest[i_83_] = 0;
}
if (i_6_ == 299) contos_0_[i_83_] = new ContO((record).ocar[i_83_], 0, 0, 0,
0);
record.play(contos_0_[i_83_], mads[i_83_], i_83_, i_6_);
}
if (++i_6_ == 300) {
i_6_ = 0;
(var_xtGraphics).fase = -6;
} else var_xtGraphics.replyn();
medium.around(contos_0_[0], false);
}
if ((var_xtGraphics).fase == -2) {
if ((var_xtGraphics).multion >= 2)
(record).hcaught = false;
u[0].falseo(3);
if ((record).hcaught && (record).wasted == 0 && (record).whenwasted != 229 && ((checkpoints).stage == 1 || (checkpoints).stage == 2) && (var_xtGraphics).looped != 0)
(record).hcaught = false;
if ((record).hcaught) {
rd.setColor(new Color(0, 0, 0));
rd.fillRect(0, 0, 800, 450);
repaint();
}
if ((var_xtGraphics).multion != 0) {
udpmistro.UDPquit();
var_xtGraphics.stopchat();
if (cmsg.isShowing()) cmsg.hide();
cmsg.setText("");
requestFocus();
}
if ((record).hcaught) {
if ((double) medium.random() > 0.45)
(medium).vert = false;
else(medium).vert = true;
(medium).adv = (int)(900.0F * medium.random());
(medium).vxz = (int)(360.0F * medium.random());
i_6_ = 0;
(var_xtGraphics).fase = -3;
i_7_ = 0;
i_8_ = 0;
} else {
i_6_ = -2;
(var_xtGraphics).fase = -4;
}
}
if ((var_xtGraphics).fase == -3) {
if (i_6_ == 0) {
if ((record).wasted == 0) {
if ((record).whenwasted == 229) {
i_9_ = 67;
(medium).vxz += 90;
} else {
i_9_ = (int)(medium.random() * 4.0F);
if (i_9_ == 1 || i_9_ == 3) i_9_ = 69;
if (i_9_ == 2 || i_9_ == 4) i_9_ = 30;
}
} else if ((record).closefinish != 0 && i_8_ != 0)
(medium).vxz += 90;
for (int i_84_ = 0;
i_84_ < (var_xtGraphics).nplayers;
i_84_++)
contos_0_[i_84_] = new ContO((record).starcar[i_84_], 0, 0,
0, 0);
}
medium.d(rd);
int i_85_ = 0;
int[] is = new int[10000];
for (int i_86_ = 0; i_86_ < nob;
i_86_++) {
if ((contos_0_[i_86_]).dist != 0) {
is[i_85_] = i_86_;
i_85_++;
} else contos_0_[i_86_].d(rd);
}
int[] is_87_ = new int[i_85_];
for (int i_88_ = 0; i_88_ < i_85_; i_88_++)
is_87_[i_88_] = 0;
for (int i_89_ = 0; i_89_ < i_85_; i_89_++) {
for (int i_90_ = i_89_ + 1; i_90_ < i_85_; i_90_++) {
if ((contos_0_[is[i_89_]]).dist != (contos_0_[is[i_90_]]).dist) {
if ((contos_0_[is[i_89_]]).dist < (contos_0_[is[i_90_]]).dist) is_87_[i_89_]++;
else is_87_[i_90_]++;
} else if (i_90_ > i_89_) is_87_[i_89_]++;
else is_87_[i_90_]++;
}
}
for (int i_91_ = 0; i_91_ < i_85_; i_91_++) {
for (int i_92_ = 0; i_92_ < i_85_; i_92_++) {
if (is_87_[i_92_] == i_91_) contos_0_[is[i_92_]].d(rd);
}
}
for (int i_93_ = 0;
i_93_ < (var_xtGraphics).nplayers; i_93_++) {
if ((record).hfix[i_93_] == i_6_) {
if ((contos_0_[i_93_]).dist == 0)
(contos_0_[i_93_]).fcnt = 8;
else(contos_0_[i_93_]).fix = true;
}
if ((contos_0_[i_93_]).fcnt == 7 || (contos_0_[i_93_]).fcnt == 8) {
contos_0_[i_93_] = new ContO(contos[(mads[i_93_]).cn], 0, 0,
0, 0);
(record).cntdest[i_93_] = 0;
}
record.playh(contos_0_[i_93_], mads[i_93_], i_93_, i_6_, (var_xtGraphics).im);
}
if (i_8_ == 2 && i_6_ == 299)
(u[0]).enter = true;
if ((u[0]).enter || (u[0]).handb) {
(var_xtGraphics).fase = -4;
(u[0]).enter = false;
(u[0]).handb = false;
i_6_ = -7;
} else {
var_xtGraphics.levelhigh((record).wasted, (record).whenwasted, (record).closefinish,
i_6_, ((checkpoints)
.stage));
if (i_6_ == 0 || i_6_ == 1 || i_6_ == 2) {
rd.setColor(new Color(0, 0, 0));
rd.fillRect(0, 0, 800, 450);
}
if ((record).wasted != (var_xtGraphics).im) {
if ((record).closefinish == 0) {
if (i_7_ == 9 || i_7_ == 11) {
rd.setColor(new Color(255, 255, 255));
rd.fillRect(0, 0, 800,
450);
}
if (i_7_ == 0) medium.around(contos_0_[(
var_xtGraphics).im],
false);
if (i_7_ > 0 && i_7_ < 20) medium.transaround(contos_0_[((
var_xtGraphics)
.im)],
contos_0_[((record)
.wasted)],
i_7_);
if (i_7_ == 20) medium.around((contos_0_[(record).wasted]),
false);
if (i_6_ > (record).whenwasted && i_7_ != 20) i_7_++;
if ((i_7_ == 0 || i_7_ == 20) && ++i_6_ == 300) {
i_6_ = 0;
i_7_ = 0;
i_8_++;
}
} else if ((record).closefinish == 1) {
if (i_7_ == 0) medium.around(contos_0_[(
var_xtGraphics).im],
false);
if (i_7_ > 0 && i_7_ < 20) medium.transaround(contos_0_[((
var_xtGraphics)
.im)],
contos_0_[((record)
.wasted)],
i_7_);
if (i_7_ == 20) medium.around((contos_0_[(record).wasted]),
false);
if (i_7_ > 20 && i_7_ < 40) medium.transaround(contos_0_[((record)
.wasted)],
contos_0_[((
var_xtGraphics)
.im)],
i_7_ - 20);
if (i_7_ == 40) medium.around(contos_0_[(
var_xtGraphics).im],
false);
if (i_7_ > 40 && i_7_ < 60) medium.transaround(contos_0_[((
var_xtGraphics)
.im)],
contos_0_[((record)
.wasted)],
i_7_ - 40);
if (i_7_ == 60) medium.around((contos_0_[(record).wasted]),
false);
if (i_6_ > 160 && i_7_ < 20) i_7_++;
if (i_6_ > 230 && i_7_ < 40) i_7_++;
if (i_6_ > 280 && i_7_ < 60) i_7_++;
if ((i_7_ == 0 || i_7_ == 20 || i_7_ == 40 || i_7_ == 60) && ++i_6_ == 300) {
i_6_ = 0;
i_7_ = 0;
i_8_++;
}
} else {
if (i_7_ == 0) medium.around(contos_0_[(
var_xtGraphics).im],
false);
if (i_7_ > 0 && i_7_ < 20) medium.transaround(contos_0_[((
var_xtGraphics)
.im)],
contos_0_[((record)
.wasted)],
i_7_);
if (i_7_ == 20) medium.around((contos_0_[(record).wasted]),
false);
if (i_7_ > 20 && i_7_ < 40) medium.transaround(contos_0_[((record)
.wasted)],
contos_0_[((
var_xtGraphics)
.im)],
i_7_ - 20);
if (i_7_ == 40) medium.around(contos_0_[(
var_xtGraphics).im],
false);
if (i_7_ > 40 && i_7_ < 60) medium.transaround(contos_0_[((
var_xtGraphics)
.im)],
contos_0_[((record)
.wasted)],
i_7_ - 40);
if (i_7_ == 60) medium.around((contos_0_[(record).wasted]),
false);
if (i_7_ > 60 && i_7_ < 80) medium.transaround(contos_0_[((record)
.wasted)],
contos_0_[((
var_xtGraphics)
.im)],
i_7_ - 60);
if (i_7_ == 80) medium.around(contos_0_[(
var_xtGraphics).im],
false);
if (i_6_ > 90 && i_7_ < 20) i_7_++;
if (i_6_ > 160 && i_7_ < 40) i_7_++;
if (i_6_ > 230 && i_7_ < 60) i_7_++;
if (i_6_ > 280 && i_7_ < 80) i_7_++;
if ((i_7_ == 0 || i_7_ == 20 || i_7_ == 40 || i_7_ == 60 || i_7_ == 80) && ++i_6_ == 300) {
i_6_ = 0;
i_7_ = 0;
i_8_++;
}
}
} else {
if (i_9_ == 67 && (i_7_ == 3 || i_7_ == 31 || i_7_ == 66)) {
rd.setColor(new Color(255, 255, 255));
rd.fillRect(0, 0, 800, 450);
}
if (i_9_ == 69 && (i_7_ == 3 || i_7_ == 5 || i_7_ == 31 || i_7_ == 33 || i_7_ == 66 || i_7_ == 68)) {
rd.setColor(new Color(255, 255, 255));
rd.fillRect(0, 0, 800, 450);
}
if (i_9_ == 30 && i_7_ >= 1 && i_7_ < 30) {
if ((i_7_ % (int)(2.0F + medium.random() * 3.0F) == 0) && !bool_10_) {
rd.setColor(new Color(255, 255, 255));
rd.fillRect(0, 0, 800,
450);
bool_10_ = true;
} else bool_10_ = false;
}
if (i_6_ > (record).whenwasted && i_7_ != i_9_) i_7_++;
medium.around((contos_0_[(var_xtGraphics).im]),
false);
if ((i_7_ == 0 || i_7_ == i_9_) && ++i_6_ == 300) {
i_6_ = 0;
i_7_ = 0;
i_8_++;
}
}
}
}
if ((var_xtGraphics).fase == -4) {
if (i_6_ == 0) {
var_xtGraphics.sendwin(checkpoints);
if ((var_xtGraphics).winner && (var_xtGraphics).multion == 0 && (var_xtGraphics).gmode != 0 && (checkpoints).stage != 27 && ((checkpoints).stage == (((var_xtGraphics).unlocked[(var_xtGraphics).gmode - 1]) + (((var_xtGraphics).gmode - 1) * 10)))) {
(var_xtGraphics).unlocked[(var_xtGraphics).gmode - 1]++;
setcarcookie((var_xtGraphics).sc[0], ((cardefine).names[(var_xtGraphics).sc[0]]), (var_xtGraphics).arnp, (var_xtGraphics).gmode, (var_xtGraphics).unlocked,
false);
(var_xtGraphics).unlocked[(var_xtGraphics).gmode - 1]
}
}
if (i_6_ <= 0) {
rd.drawImage((
var_xtGraphics).mdness,
289, 30, null);
rd.drawImage((
var_xtGraphics).dude[0],
135, 10, null);
}
if (i_6_ >= 0) var_xtGraphics.fleximage(offImage,
i_6_, ((checkpoints)
.stage));
if (++i_6_ == 7) {
(var_xtGraphics).fase = -5;
rd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
}
if ((var_xtGraphics).fase == -6) {
repaint();
var_xtGraphics.pauseimage(offImage);
(var_xtGraphics).fase = -7;
mouses = 0;
}
if ((var_xtGraphics).fase == -7) {
var_xtGraphics.pausedgame((checkpoints).stage, u[0], record);
if (i_6_ != 0) i_6_ = 0;
var_xtGraphics.ctachm(xm, ym, mouses, u[0]);
if (mouses == 2) mouses = 0;
if (mouses == 1) mouses = 2;
}
if ((var_xtGraphics).fase == -8) {
var_xtGraphics.cantreply();
if (++i_6_ == 150 || (u[0]).enter || (u[0]).handb || mouses == 1) {
(var_xtGraphics).fase = -7;
mouses = 0;
(u[0]).enter = false;
(u[0]).handb = false;
}
}
if (lostfcs && (var_xtGraphics).fase == 7001) {
if (fcscnt == 0) {
if ((u[0]).chatup == 0) requestFocus();
fcscnt = 10;
} else fcscnt
}
repaint();
if ((var_xtGraphics).im > -1 && (var_xtGraphics).im < 8) {
int i_94_ = 0;
if ((var_xtGraphics).multion == 2 || (var_xtGraphics).multion == 3) {
i_94_ = (var_xtGraphics).im;
(u[i_94_]).mutem = (u[0]).mutem;
(u[i_94_]).mutes = (u[0]).mutes;
}
var_xtGraphics.playsounds((mads[(var_xtGraphics).im]), u[i_94_], (checkpoints).stage);
}
date = new Date();
long l_95_ = date.getTime();
if ((var_xtGraphics).fase == 0 || (var_xtGraphics).fase == -1 || (var_xtGraphics).fase == -3 || (var_xtGraphics).fase == 7001) {
if (!bool_3_) {
i = 15;
f_2_ = f;
if (f_2_ < 30.0F) f_2_ = 30.0F;
bool_3_ = true;
i_5_ = 0;
}
if (i_5_ == 10) {
float f_96_ = (((float) i_4_ + (udpmistro).freg - (float)(l_95_ - l_1_)) / 20.0F);
if (f_96_ > 40.0F) f_96_ = 40.0F;
if (f_96_ < -40.0F) f_96_ = -40.0F;
f_2_ += f_96_;
if (f_2_ < 5.0F) f_2_ = 5.0F;
medium.adjstfade(f_2_, f_96_, (var_xtGraphics).starcnt,
this);
l_1_ = l_95_;
i_5_ = 0;
} else i_5_++;
} else {
if (bool_3_) {
i = 30;
f = f_2_;
bool_3_ = false;
i_5_ = 0;
}
if (i_5_ == 10) {
if (l_95_ - l_1_ < 400L) f_2_ += 3.5;
else {
f_2_ -= 3.5;
if (f_2_ < 5.0F) f_2_ = 5.0F;
}
l_1_ = l_95_;
i_5_ = 0;
} else i_5_++;
}
if (exwist) {
rd.dispose();
var_xtGraphics.stopallnow();
cardefine.stopallnow();
udpmistro.UDPquit();
if (bool) {
lobby.stopallnow();
login.stopallnow();
globe.stopallnow();
}
System.gc();
if (Madness.endadv == 2) Madness.advopen();
gamer.stop();
gamer = null;
}
l = (long) Math.round(f_2_) - (l_95_ - l_11_);
if (l < (long) i) l = (long) i;
try {
if (gamer != null) {
/* empty */
}
Thread.sleep(l);
} catch (InterruptedException interruptedexception) {
/* empty */
}
next_game_tick += SKIP_TICKS;
loops++;
}
}
}
public void checkmemory(xtGraphics var_xtGraphics) {
if (applejava || Runtime.getRuntime().freeMemory() / 1048576L < 50L)
(var_xtGraphics).badmac = true;
}
public void paint(Graphics graphics) {
Graphics2D graphics2d = (Graphics2D) graphics;
if (lastw != getWidth() || lasth != getHeight()) {
lastw = getWidth();
lasth = getHeight();
showsize = 100;
if (lastw <= 800 || lasth <= 550) reqmult = 0.0F;
if (Madness.fullscreen) {
apx = (int)((float)(getWidth() / 2) - 400.0F * apmult);
apy = (int)((float)(getHeight() / 2) - 225.0F * apmult);
}
}
int i = 0;
int i_97_ = 0;
if (moto == 1 && shaka > 0) {
i = (int)((((double)(shaka * 2) * Math.random()) - (double) shaka) * (double) apmult);
i_97_ = (int)((((double)(shaka * 2) * Math.random()) - (double) shaka) * (double) apmult);
shaka
}
if (!Madness.fullscreen) {
if (showsize != 0) {
if (showsize == 100 || showsize == 70) graphics2d.clearRect(0, 0, getWidth(), getHeight());
float f = (float)(getWidth() - 40) / 800.0F - 1.0F;
if (f > (float)(getHeight() - 70) / 450.0F - 1.0F) f = (float)(getHeight() - 70) / 450.0F - 1.0F;
if (f > 1.0F) f = 1.0F;
if (f < 0.0F) f = 0.0F;
apmult = 1.0F + f * reqmult;
if (!oncarm) graphics2d.drawImage(carmaker[0], 50,
14, this);
else graphics2d.drawImage(carmaker[1], 50,
14, this);
if (!onstgm) graphics2d.drawImage(stagemaker[0],
getWidth() - 208, 14, this);
else graphics2d.drawImage(stagemaker[1],
getWidth() - 208, 14, this);
graphics2d.drawImage(sizebar,
getWidth() / 2 - 230, 23, this);
graphics2d.drawImage(blb, (int)((float)(getWidth() / 2 - 222) + 141.0F * (this.reqmult)),
23, this);
graphics2d.drawImage((chkbx[smooth]),
getWidth() / 2 - 53, 23, this);
graphics2d.setFont(new Font("Arial", 1, 11));
graphics2d.setColor(new Color(74, 99, 125));
graphics2d.drawString("Screen Size:", getWidth() / 2 - 224,
17);
graphics2d.drawString("Smooth", getWidth() / 2 - 36, 34);
graphics2d.drawImage(fulls,
getWidth() / 2 + 27, 15, this);
graphics2d.setColor(new Color(94, 126, 159));
graphics2d.drawString("Fullscreen", getWidth() / 2 + 63, 30);
graphics2d.drawImage(chkbx[Madness.anti],
getWidth() / 2 + 135, 9, this);
graphics2d.drawString("Antialiasing", getWidth() / 2 + 152,
20);
graphics2d.drawImage((chkbx[moto]),
getWidth() / 2 + 135, 26, this);
graphics2d.drawString("Motion Effects", getWidth() / 2 + 152,
37);
graphics2d.setColor(new Color(0, 0, 0));
graphics2d.fillRect(getWidth() / 2 - 153, 5, 80, 16);
graphics2d.setColor(new Color(121, 135, 152));
String string = new StringBuilder().append("").append((int)(apmult * 100.0F)).append("%").toString();
if (reqmult == 0.0F) string = "Original";
if (reqmult == 1.0F) string = "Maximum";
graphics2d.drawString(string, getWidth() / 2 - 150, 17);
if (!oncarm && !onstgm) showsize
if (showsize == 0) {
graphics2d.setColor(new Color(0, 0, 0));
graphics2d.fillRect(getWidth() / 2 - 260, 0, 520, 40);
graphics2d.fillRect(50, 14, 142, 23);
graphics2d.fillRect(getWidth() - 208, 14, 158, 23);
}
}
apx = (int)((float)(getWidth() / 2) - 400.0F * apmult);
apy = (int)((float)(getHeight() / 2) - 225.0F * apmult - 50.0F);
if (apy < 50) apy = 50;
if (apmult > 1.0F) {
if (smooth == 1) {
graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
if (moto == 1) {
graphics2d.setComposite(AlphaComposite.getInstance(3, (float)(this.mvect) / 100.0F));
rd.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
graphics2d.drawImage(offImage, apx + i, apy + i_97_, (int)(800.0F * apmult), (int)(450.0F * apmult),
this);
cropit(graphics2d, i, i_97_);
} else graphics2d.drawImage(offImage, apx, apy, (int)(800.0F * apmult), (int)(450.0F * apmult),
this);
} else if (moto == 1) {
graphics2d.setComposite(AlphaComposite.getInstance(3, (float)(this.mvect) / 100.0F));
rd.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
graphics2d.drawImage(offImage, apx + i, apy + i_97_, (int)(800.0F * apmult), (int)(450.0F * apmult),
this);
cropit(graphics2d, i, i_97_);
} else graphics2d.drawImage(offImage, apx, apy, (int)(800.0F * apmult), (int)(450.0F * apmult),
this);
} else if (moto == 1) {
graphics2d.setComposite(AlphaComposite.getInstance(3, ((float) mvect / 100.0F)));
rd.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
graphics2d.drawImage(offImage, apx + i, apy + i_97_, this);
cropit(graphics2d, i, i_97_);
} else graphics2d.drawImage(offImage, apx, apy, this);
} else if (moto == 1) {
graphics2d.setComposite(AlphaComposite.getInstance(3, ((float) mvect / 100.0F)));
rd.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
graphics2d.drawImage(offImage, apx + i, apy + i_97_, this);
cropit(graphics2d, i, i_97_);
} else graphics2d.drawImage(offImage, apx, apy, this);
}
public void cropit(Graphics2D graphics2d, int i, int i_98_) {
if (i != 0 || i_98_ != 0) {
graphics2d.setComposite(AlphaComposite.getInstance(3, 1.0F));
graphics2d.setColor(new Color(0, 0, 0));
}
if (i != 0) {
if (i < 0) graphics2d.fillRect(apx + i, (apy - (int)(25.0F * apmult)),
Math.abs(i), (int)(500.0F * apmult));
else graphics2d.fillRect((apx + (int)(800.0F * apmult)), (apy - (int)(25.0F * apmult)),
i, (int)(500.0F * apmult));
}
if (i_98_ != 0) {
if (i_98_ < 0) graphics2d.fillRect((apx - (int)(25.0F * apmult)), apy + i_98_, (int)(850.0F * apmult),
Math.abs(i_98_));
else graphics2d.fillRect((apx - (int)(25.0F * apmult)), (apy + (int)(450.0F * apmult)), (int)(850.0F * apmult),
i_98_);
}
}
public void update(Graphics graphics) {
paint(graphics);
}
public void init() {
setBackground(new Color(0, 0, 0));
offImage = createImage(800, 450);
if (offImage != null) rd = (Graphics2D) offImage.getGraphics();
rd.setRenderingHint((RenderingHints.KEY_TEXT_ANTIALIASING), (RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
rd.setRenderingHint((RenderingHints.KEY_ANTIALIASING), (RenderingHints.VALUE_ANTIALIAS_ON));
setLayout(null);
tnick = new TextField("Nickbname");
tnick.setFont(new Font("Arial", 1, 13));
tpass = new TextField("");
tpass.setFont(new Font("Arial", 1, 13));
tpass.setEchoCharacter('*');
temail = new TextField("");
temail.setFont(new Font("Arial", 1, 13));
cmsg = new TextField("");
if (System.getProperty("java.vendor").toLowerCase().indexOf("oracle") != -1) cmsg.addKeyListener( /*TYPE_ERROR*/ new GameSparker$1(this));
mmsg = new TextArea("", 200, 20, 3);
cmsg.setFont(new Font("Tahoma", 0, 11));
mmsg.setFont(new Font("Tahoma", 0, 11));
mycar = new Checkbox("Sword of Justice Game!");
notp = new Checkbox("No Trees & Piles");
keplo = new Checkbox("Stay logged in");
keplo.setState(true);
add(tnick);
add(tpass);
add(temail);
add(cmsg);
add(mmsg);
add(mycar);
add(notp);
add(keplo);
sgame.setFont(new Font("Arial", 1, 13));
wgame.setFont(new Font("Arial", 1, 13));
warb.setFont(new Font("Arial", 1, 13));
pgame.setFont(new Font("Arial", 1, 12));
vnpls.setFont(new Font("Arial", 1, 13));
vtyp.setFont(new Font("Arial", 1, 13));
snfmm.setFont(new Font("Arial", 1, 13));
snfm1.setFont(new Font("Arial", 1, 13));
snfm2.setFont(new Font("Arial", 1, 13));
mstgs.setFont(new Font("Arial", 1, 13));
mcars.setFont(new Font("Arial", 1, 13));
slaps.setFont(new Font("Arial", 1, 13));
snpls.setFont(new Font("Arial", 0, 13));
snbts.setFont(new Font("Arial", 0, 13));
swait.setFont(new Font("Arial", 0, 12));
sclass.setFont(new Font("Arial", 1, 12));
scars.setFont(new Font("Arial", 1, 12));
sfix.setFont(new Font("Arial", 1, 12));
mycar.setFont(new Font("Arial", 1, 12));
notp.setFont(new Font("Arial", 1, 12));
keplo.setFont(new Font("Arial", 1, 12));
gmode.setFont(new Font("Arial", 1, 13));
rooms.setFont(new Font("Arial", 1, 13));
sendtyp.setFont(new Font("Arial", 1, 12));
senditem.setFont(new Font("Arial", 1, 12));
datat.setFont(new Font("Arial", 1, 12));
clanlev.setFont(new Font("Arial", 1, 12));
clcars.setFont(new Font("Arial", 1, 12));
(clcars).alphad = true;
ilaps.setFont(new Font("Arial", 1, 13));
icars.setFont(new Font("Arial", 1, 12));
proitem.setFont(new Font("Arial", 1, 12));
sgame.add(rd, " NFM 1 ");
sgame.add(rd, " NFM 2 ");
sgame.add(rd, " My Stages ");
sgame.add(rd,
" Weekly Top20 ");
sgame.add(rd,
" Monthly Top20 ");
sgame.add(rd,
" All Time Top20 ");
sgame.add(rd,
" Stage Maker ");
wgame.add(rd,
" Normal Game");
wgame.add(rd,
" War / Battle");
wgame.add(rd,
" War / Battle - Practice");
warb.add(rd,
" Loading your clan's wars and battles, please wait...");
pgame.add(rd, " Select the game you want to practice");
vnpls.add(rd, "Players");
vnpls.add(rd, " 2 VS 2");
vnpls.add(rd, " 3 VS 3");
vnpls.add(rd, " 4 VS 4");
vtyp.add(rd,
"Normal clan game");
vtyp.add(rd, "Racing only");
vtyp.add(rd, "Wasting only");
vtyp.add(rd,
"Racers VS Wasters - my clan wastes");
vtyp.add(rd,
"Racers VS Wasters - my clan races");
snfmm.add(rd,
"Select Stage");
snfm1.add(rd,
"Select Stage");
snfm2.add(rd,
"Select Stage");
mstgs.add(rd,
"Suddenly the King becomes Santa's Little Helper");
mcars.add(rd,
"Sword of Justice");
snpls.add(rd, "Select");
swait.add(rd, "1 Minute");
ilaps.add(rd, "Laps");
ilaps.add(rd, "1 Lap");
for (int i = 0; i < 5; i++)
snfmm.add(rd,
new StringBuilder().append(" Stage ").append(i + 1).append("").toString());
for (int i = 0; i < 10; i++)
snfm1.add(rd,
new StringBuilder().append(" Stage ").append(i + 1).append("").toString());
for (int i = 0; i < 17; i++)
snfm2.add(rd,
new StringBuilder().append(" Stage ").append(i + 1).append("").toString());
for (int i = 0; i < 7; i++)
snpls.add(rd,
new StringBuilder().append(" ").append(i + 2).append("").toString());
for (int i = 0; i < 7; i++)
snbts.add(rd,
new StringBuilder().append(" ").append(i).append(" ").toString());
for (int i = 0; i < 2; i++)
swait.add(rd,
new StringBuilder().append("")
.append(i + 2).append(" Minutes").toString());
for (int i = 0; i < 15; i++)
slaps.add(rd,
new StringBuilder().append("")
.append(i + 1).append("").toString());
for (int i = 0; i < 14; i++)
ilaps.add(rd,
new StringBuilder().append("")
.append(i + 2).append(" Laps").toString());
sclass.add(rd,
"All Classes");
sclass.add(rd,
"Class C Cars");
sclass.add(rd,
"Class B & C Cars");
sclass.add(rd,
"Class B Cars");
sclass.add(rd,
"Class A & B Cars");
sclass.add(rd,
"Class A Cars");
scars.add(rd, "All Cars");
scars.add(rd, "Custom Cars");
scars.add(rd, "Game Cars");
sfix.add(rd,
"Unlimited Fixing");
sfix.add(rd, "4 Fixes");
sfix.add(rd, "3 Fixes");
sfix.add(rd, "2 Fixes");
sfix.add(rd, "1 Fix");
sfix.add(rd, "No Fixing");
icars.add(rd,
"Type of Cars");
icars.add(rd, "All Cars");
icars.add(rd, "Clan Cars");
icars.add(rd, "Game Cars");
(icars).w = 140;
gmode.add(rd,
" Normal Game ");
gmode.add(rd,
" Practice Game ");
(rooms).rooms = true;
rooms.add(rd,
"Ghostrider :: 1");
sendtyp.add(rd,
"Write a Message");
sendtyp.add(rd,
"Share a Custom Car");
sendtyp.add(rd,
"Share a Custom Stage");
sendtyp.add(rd,
"Send a Clan Invitation");
sendtyp.add(rd,
"Share a Relative Date");
senditem.add(rd,
"Suddenly the King becomes Santa's Little Helper");
for (int i = 0; i < 6; i++)
clanlev.add(rd,
new StringBuilder().append("")
.append(i + 1).append("").toString());
clanlev.add(rd, "7 - Admin");
hidefields();
}
public void hidefields() {
ilaps.hide();
icars.hide();
proitem.hide();
clcars.hide();
clanlev.hide();
mmsg.hide();
datat.hide();
senditem.hide();
sendtyp.hide();
rooms.hide();
mcars.hide();
mstgs.hide();
gmode.hide();
sclass.hide();
scars.hide();
sfix.hide();
mycar.hide();
notp.hide();
keplo.hide();
tnick.hide();
tpass.hide();
temail.hide();
cmsg.hide();
sgame.hide();
wgame.hide();
pgame.hide();
vnpls.hide();
vtyp.hide();
warb.hide();
slaps.hide();
snfm1.hide();
snfmm.hide();
snfm2.hide();
snpls.hide();
snbts.hide();
swait.hide();
}
public void drawms() {
openm = false;
if (gmode.draw(rd, xm, ym, moused, 450,
true)) openm = true;
if (swait.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (slaps.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (snpls.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (snbts.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (scars.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (sgame.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (snfm1.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (snfm2.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (snfmm.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (mstgs.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (mcars.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (pgame.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (vnpls.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (vtyp.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (warb.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (wgame.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (rooms.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (sendtyp.draw(rd, xm, ym, moused, 450,
true)) openm = true;
if (senditem.draw(rd, xm, ym, moused,
450, true)) openm = true;
if (datat.draw(rd, xm, ym, moused, 450,
true)) openm = true;
if (clanlev.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (clcars.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (ilaps.draw(rd, xm, ym, moused, 450,
true)) openm = true;
if (icars.draw(rd, xm, ym, moused, 450,
true)) openm = true;
if (proitem.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (sfix.draw(rd, xm, ym, moused, 450,
false)) openm = true;
if (sclass.draw(rd, xm, ym, moused, 450,
false)) openm = true;
}
public void movefield(Component component, int i, int i_99_, int i_100_,
int i_101_) {
if (i_100_ == 360 || i_100_ == 576) {
i = (int)((float) i * apmult + (float) apx + ((float)(component.getWidth() / 2) * (apmult - 1.0F)));
i_99_ = (int)((float) i_99_ * apmult + (float) apy + 12.0F * (apmult - 1.0F));
} else {
i = (int)((float) i * apmult + (float) apx);
i_99_ = (int)((float) i_99_ * apmult + (float) apy + 12.0F * (apmult - 1.0F));
}
if (component.getX() != i || component.getY() != i_99_) component.setBounds(i, i_99_, i_100_, i_101_);
}
public void movefieldd(TextField textfield, int i, int i_102_, int i_103_,
int i_104_, boolean bool) {
if (applejava) {
if (bool) {
if ((xm > i && xm < i + i_103_ && ym > i_102_ && ym < i_102_ + i_104_) || !textfield.getText().equals("")) {
if (!textfield.isShowing()) {
textfield.show();
textfield.requestFocus();
}
if (i_103_ == 360 || i_103_ == 576) {
i = (int)((float) i * apmult + (float) apx + ((float)(textfield.getWidth() / 2) * (apmult - 1.0F)));
i_102_ = (int)(((float) i_102_ * apmult) + (float) apy + 12.0F * (apmult - 1.0F));
} else {
i = (int)((float) i * apmult + (float) apx);
i_102_ = (int)(((float) i_102_ * apmult) + (float) apy + 12.0F * (apmult - 1.0F));
}
if (textfield.getX() != i || textfield.getY() != i_102_) textfield.setBounds(i, i_102_, i_103_, i_104_);
} else {
if (textfield.isShowing()) {
textfield.hide();
requestFocus();
}
rd.setColor(textfield.getBackground());
rd.fillRect(i, i_102_, i_103_ - 1,
i_104_ - 1);
rd.setColor(textfield.getBackground().darker());
rd.drawRect(i, i_102_, i_103_ - 1,
i_104_ - 1);
}
}
} else {
if (bool && !textfield.isShowing()) textfield.show();
movefield(textfield, i, i_102_, i_103_, i_104_);
}
}
public void movefielda(TextArea textarea, int i, int i_105_, int i_106_,
int i_107_) {
if (applejava) {
if ((xm > i && xm < i + i_106_ && ym > i_105_ && ym < i_105_ + i_107_) || !textarea.getText().equals(" ")) {
if (!textarea.isShowing()) {
textarea.show();
textarea.requestFocus();
}
if (i_106_ == 360 || i_106_ == 576) {
i = (int)((float) i * apmult + (float) apx + ((float)(textarea.getWidth() / 2) * (apmult - 1.0F)));
i_105_ = (int)((float) i_105_ * apmult + (float) apy + 12.0F * (apmult - 1.0F));
} else {
i = (int)((float) i * apmult + (float) apx);
i_105_ = (int)((float) i_105_ * apmult + (float) apy + 12.0F * (apmult - 1.0F));
}
if (textarea.getX() != i || textarea.getY() != i_105_) textarea.setBounds(i, i_105_, i_106_, i_107_);
} else {
if (textarea.isShowing()) {
textarea.hide();
requestFocus();
}
rd.setColor(textarea.getBackground());
rd.fillRect(i, i_105_, i_106_ - 1,
i_107_ - 1);
rd.setColor(textarea.getBackground().darker());
rd.drawRect(i, i_105_, i_106_ - 1,
i_107_ - 1);
}
} else {
if (!textarea.isShowing()) textarea.show();
movefield(textarea, i, i_105_, i_106_, i_107_);
}
}
public void loadstage(ContO[] contos, ContO[] contos_108_, Medium medium,
Trackers trackers, CheckPoints checkpoints,
xtGraphics var_xtGraphics, Mad[] mads,
Record record) {
if ((var_xtGraphics).testdrive == 2 || (var_xtGraphics).testdrive == 4)
(var_xtGraphics).nplayers = 1;
if ((var_xtGraphics).gmode == 1) {
(var_xtGraphics).nplayers = 5;
(var_xtGraphics).xstart[4] = 0;
(var_xtGraphics).zstart[4] = 760;
}
(trackers).nt = 0;
nob = (var_xtGraphics).nplayers;
notb = 0;
(checkpoints).n = 0;
(checkpoints).nsp = 0;
(checkpoints).fn = 0;
(checkpoints).trackname = "";
(checkpoints).haltall = false;
(checkpoints).wasted = 0;
(checkpoints).catchfin = 0;
(medium).resdown = 0;
(medium).rescnt = 5;
(medium).lightson = false;
(medium).noelec = 0;
(medium).ground = 250;
(medium).trk = 0;
view = 0;
int i = 0;
int i_109_ = 100;
int i_110_ = 0;
int i_111_ = 100;
(var_xtGraphics).newparts = false;
String string = "";
try {
DataInputStream datainputstream;
if ((var_xtGraphics).multion == 0 && (checkpoints).stage != -2) {
String string_112_ = new StringBuilder().append("stages/").append((checkpoints).stage).append("").toString();
if ((checkpoints).stage == -1) string_112_ = new StringBuilder().append("mystages/").append((checkpoints).name).append("").toString();
File file = new File(new StringBuilder().append("").append(Madness.fpath).append("").append(string_112_).append(".txt").toString());
datainputstream = new DataInputStream(new FileInputStream(file));
} else if ((checkpoints).stage > 0) {
URL url = (new URL(new StringBuilder().append("http://multiplayer.needformadness.com/stages/")
.append((checkpoints).stage).append(".txt").toString()));
datainputstream = new DataInputStream(url.openStream());
} else {
String string_113_ = new StringBuilder().append("http://multiplayer.needformadness.com/tracks/")
.append((checkpoints).name).append(".radq").toString();
string_113_ = string_113_.replace(' ', '_');
URL url = new URL(string_113_);
int i_114_ = url.openConnection().getContentLength();
DataInputStream datainputstream_115_ = new DataInputStream(url.openStream());
byte[] is = new byte[i_114_];
datainputstream_115_.readFully(is);
ZipInputStream zipinputstream;
if (is[0] == 80 && is[1] == 75 && is[2] == 3) zipinputstream = new ZipInputStream(new ByteArrayInputStream(is));
else {
byte[] is_116_ = new byte[i_114_ - 40];
for (int i_117_ = 0; i_117_ < i_114_ - 40; i_117_++) {
int i_118_ = 20;
if (i_117_ >= 500) i_118_ = 40;
is_116_[i_117_] = is[i_117_ + i_118_];
}
zipinputstream = (new ZipInputStream(new ByteArrayInputStream(is_116_)));
}
ZipEntry zipentry = zipinputstream.getNextEntry();
int i_119_ = Integer.valueOf(zipentry.getName()).intValue();
byte[] is_120_ = new byte[i_119_];
int i_121_ = 0;
int i_122_;
for ( ; i_119_ > 0; i_119_ -= i_122_) {
i_122_ = zipinputstream.read(is_120_, i_121_, i_119_);
i_121_ += i_122_;
}
zipinputstream.close();
datainputstream_115_.close();
datainputstream = new DataInputStream(new ByteArrayInputStream(is_120_));
}
String string_123_;
while ((string_123_ = datainputstream.readLine()) != null) {
string = new StringBuilder().append("").append(string_123_.trim()).toString();
if (string.startsWith("snap")) medium.setsnap(getint("snap", string, 0),
getint("snap", string, 1),
getint("snap", string, 2));
if (string.startsWith("sky")) {
medium.setsky(getint("sky", string, 0),
getint("sky", string, 1),
getint("sky", string, 2));
var_xtGraphics.snap((checkpoints).stage);
}
if (string.startsWith("ground")) medium.setgrnd(getint("ground", string, 0),
getint("ground", string, 1),
getint("ground", string, 2));
if (string.startsWith("polys")) medium.setpolys(getint("polys", string, 0),
getint("polys", string, 1),
getint("polys", string, 2));
if (string.startsWith("fog")) medium.setfade(getint("fog", string, 0),
getint("fog", string, 1),
getint("fog", string, 2));
if (string.startsWith("texture")) medium.setexture(getint("texture", string, 0),
getint("texture", string, 1),
getint("texture", string, 2),
getint("texture", string, 3));
if (string.startsWith("clouds")) medium.setcloads(getint("clouds", string, 0),
getint("clouds", string, 1),
getint("clouds", string, 2),
getint("clouds", string, 3),
getint("clouds", string, 4));
if (string.startsWith("density")) {
(medium).fogd = (getint("density", string, 0) + 1) * 2 - 1;
if ((medium).fogd < 1)
(medium).fogd = 1;
if ((medium).fogd > 30)
(medium).fogd = 30;
}
if (string.startsWith("fadefrom")) medium.fadfrom(getint("fadefrom", string, 0));
if (string.startsWith("lightson"))
(medium).lightson = true;
if (string.startsWith("mountains"))
(medium).mgen = getint("mountains", string, 0);
if (string.startsWith("set")) {
int i_124_ = getint("set", string, 0);
if ((var_xtGraphics).nplayers == 8) {
if (i_124_ == 47) i_124_ = 76;
if (i_124_ == 48) i_124_ = 77;
}
boolean bool = true;
if (i_124_ >= 65 && i_124_ <= 75 && (checkpoints).notb) bool = false;
if (bool) {
if (i_124_ == 49 || i_124_ == 64 || i_124_ >= 56 && i_124_ <= 61)
(var_xtGraphics).newparts = true;
if (((checkpoints).stage < 0 || (checkpoints).stage >= 28) && i_124_ >= 10 && i_124_ <= 25)
(medium).loadnew = true;
i_124_ += 46;
contos[nob] = new ContO(contos_108_[i_124_],
getint("set", string, 1), ((medium).ground - (contos_108_[i_124_]).grat),
getint("set", string, 2),
getint("set", string, 3));
if (string.indexOf(")p") != -1) {
(checkpoints).x[(checkpoints).n] = getint("set", string, 1);
(checkpoints).z[(checkpoints).n] = getint("set", string, 2);
(checkpoints).y[(checkpoints).n] = 0;
(checkpoints).typ[(checkpoints).n] = 0;
if (string.indexOf(")pt") != -1)
(checkpoints).typ[(checkpoints).n] = -1;
if (string.indexOf(")pr") != -1)
(checkpoints).typ[(checkpoints).n] = -2;
if (string.indexOf(")po") != -1)
(checkpoints).typ[(checkpoints).n] = -3;
if (string.indexOf(")ph") != -1)
(checkpoints).typ[(checkpoints).n] = -4;
if (string.indexOf("out") != -1) System.out.println(new StringBuilder().append("out: ").append((
checkpoints).n)
.toString());
(checkpoints).n++;
notb = nob + 1;
}
nob++;
if ((medium).loadnew)
(medium).loadnew = false;
}
}
if (string.startsWith("chk")) {
int i_125_ = getint("chk", string, 0);
i_125_ += 46;
int i_126_ = ((medium).ground - (contos_108_[i_125_]).grat);
if (i_125_ == 110) i_126_ = getint("chk", string, 4);
contos[nob] = new ContO(contos_108_[i_125_],
getint("chk", string, 1), i_126_,
getint("chk", string, 2),
getint("chk", string, 3));
(checkpoints).x[((checkpoints)
.n)] = getint("chk", string, 1);
(checkpoints).z[((checkpoints)
.n)] = getint("chk", string, 2);
(checkpoints).y[((checkpoints)
.n)] = i_126_;
if (getint("chk", string, 3) == 0)
(checkpoints).typ[(checkpoints).n] = 1;
else(checkpoints).typ[(checkpoints).n] = 2;
(checkpoints).pcs = (checkpoints).n;
(checkpoints).n++;
(contos[nob]).checkpoint = (checkpoints).nsp + 1;
(checkpoints).nsp++;
nob++;
notb = nob;
}
if ((checkpoints).nfix != 5 && string.startsWith("fix")) {
int i_127_ = getint("fix", string, 0);
i_127_ += 46;
contos[nob] = new ContO(contos_108_[i_127_],
getint("fix", string, 1),
getint("fix", string, 3),
getint("fix", string, 2),
getint("fix", string, 4));
(checkpoints).fx[((checkpoints)
.fn)] = getint("fix", string, 1);
(checkpoints).fz[((checkpoints)
.fn)] = getint("fix", string, 2);
(checkpoints).fy[((checkpoints)
.fn)] = getint("fix", string, 3);
(contos[nob]).elec = true;
if (getint("fix", string, 4) != 0) {
(checkpoints).roted[(checkpoints).fn] = true;
(contos[nob]).roted = true;
} else(checkpoints).roted[(checkpoints).fn] = false;
if (string.indexOf(")s") != -1)
(checkpoints).special[(checkpoints).fn] = true;
else(checkpoints).special[(checkpoints).fn] = false;
(checkpoints).fn++;
nob++;
notb = nob;
}
if (!(checkpoints).notb && string.startsWith("pile")) {
contos[nob] = new ContO(getint("pile", string, 0),
getint("pile", string, 1),
getint("pile", string, 2), medium,
trackers, getint("pile", string, 3),
getint("pile", string, 4), (medium).ground);
nob++;
}
if ((var_xtGraphics).multion == 0 && string.startsWith("nlaps")) {
(checkpoints).nlaps = getint("nlaps", string, 0);
if ((checkpoints).nlaps < 1)
(checkpoints).nlaps = 1;
if ((checkpoints).nlaps > 15)
(checkpoints).nlaps = 15;
}
if ((checkpoints).stage > 0 && string.startsWith("name"))
(checkpoints).name = getstring("name", string, 0).replace('|', ',');
if (string.startsWith("stagemaker"))
(checkpoints).maker = getstring("stagemaker", string, 0);
if (string.startsWith("publish"))
(checkpoints).pubt = getint("publish", string, 0);
if (string.startsWith("soundtrack")) {
(checkpoints).trackname = getstring("soundtrack", string, 0);
(checkpoints).trackvol = getint("soundtrack", string, 1);
if ((checkpoints).trackvol < 50)
(checkpoints).trackvol = 50;
if ((checkpoints).trackvol > 300)
(checkpoints).trackvol = 300;
(var_xtGraphics).sndsize[32] = getint("soundtrack", string, 2);
}
if (string.startsWith("maxr")) {
int i_128_ = getint("maxr", string, 0);
int i_129_ = getint("maxr", string, 1);
i = i_129_;
int i_130_ = getint("maxr", string, 2);
for (int i_131_ = 0; i_131_ < i_128_; i_131_++) {
contos[nob] = new ContO(contos_108_[85], i_129_, ((medium).ground - (contos_108_[85]).grat),
i_131_ * 4800 + i_130_, 0);
nob++;
}
(trackers).y[(trackers).nt] = -5000;
(trackers).rady[(trackers).nt] = 7100;
(trackers).x[(trackers).nt] = i_129_ + 500;
(trackers).radx[(trackers).nt] = 600;
(trackers).z[(trackers).nt] = i_128_ * 4800 / 2 + i_130_ - 2400;
(trackers).radz[(trackers).nt] = i_128_ * 4800 / 2;
(trackers).xy[(trackers).nt] = 90;
(trackers).zy[(trackers).nt] = 0;
(trackers).dam[(trackers).nt] = 167;
(trackers).decor[(trackers).nt] = false;
(trackers).skd[(trackers).nt] = 0;
(trackers).nt++;
}
if (string.startsWith("maxl")) {
int i_132_ = getint("maxl", string, 0);
int i_133_ = getint("maxl", string, 1);
i_109_ = i_133_;
int i_134_ = getint("maxl", string, 2);
for (int i_135_ = 0; i_135_ < i_132_; i_135_++) {
contos[nob] = new ContO(contos_108_[85], i_133_, ((medium).ground - (contos_108_[85]).grat),
i_135_ * 4800 + i_134_, 180);
nob++;
}
(trackers).y[(trackers).nt] = -5000;
(trackers).rady[(trackers).nt] = 7100;
(trackers).x[(trackers).nt] = i_133_ - 500;
(trackers).radx[(trackers).nt] = 600;
(trackers).z[(trackers).nt] = i_132_ * 4800 / 2 + i_134_ - 2400;
(trackers).radz[(trackers).nt] = i_132_ * 4800 / 2;
(trackers).xy[(trackers).nt] = -90;
(trackers).zy[(trackers).nt] = 0;
(trackers).dam[(trackers).nt] = 167;
(trackers).decor[(trackers).nt] = false;
(trackers).skd[(trackers).nt] = 0;
(trackers).nt++;
}
if (string.startsWith("maxt")) {
int i_136_ = getint("maxt", string, 0);
int i_137_ = getint("maxt", string, 1);
i_110_ = i_137_;
int i_138_ = getint("maxt", string, 2);
for (int i_139_ = 0; i_139_ < i_136_; i_139_++) {
contos[nob] = new ContO(contos_108_[85],
i_139_ * 4800 + i_138_, ((medium).ground - (contos_108_[85]).grat),
i_137_, 90);
nob++;
}
(trackers).y[(trackers).nt] = -5000;
(trackers).rady[(trackers).nt] = 7100;
(trackers).z[(trackers).nt] = i_137_ + 500;
(trackers).radz[(trackers).nt] = 600;
(trackers).x[(trackers).nt] = i_136_ * 4800 / 2 + i_138_ - 2400;
(trackers).radx[(trackers).nt] = i_136_ * 4800 / 2;
(trackers).zy[(trackers).nt] = 90;
(trackers).xy[(trackers).nt] = 0;
(trackers).dam[(trackers).nt] = 167;
(trackers).decor[(trackers).nt] = false;
(trackers).skd[(trackers).nt] = 0;
(trackers).nt++;
}
if (string.startsWith("maxb")) {
int i_140_ = getint("maxb", string, 0);
int i_141_ = getint("maxb", string, 1);
i_111_ = i_141_;
int i_142_ = getint("maxb", string, 2);
for (int i_143_ = 0; i_143_ < i_140_; i_143_++) {
contos[nob] = new ContO(contos_108_[85],
i_143_ * 4800 + i_142_, ((medium).ground - (contos_108_[85]).grat),
i_141_, -90);
nob++;
}
(trackers).y[(trackers).nt] = -5000;
(trackers).rady[(trackers).nt] = 7100;
(trackers).z[(trackers).nt] = i_141_ - 500;
(trackers).radz[(trackers).nt] = 600;
(trackers).x[(trackers).nt] = i_140_ * 4800 / 2 + i_142_ - 2400;
(trackers).radx[(trackers).nt] = i_140_ * 4800 / 2;
(trackers).zy[(trackers).nt] = -90;
(trackers).xy[(trackers).nt] = 0;
(trackers).dam[(trackers).nt] = 167;
(trackers).decor[(trackers).nt] = false;
(trackers).skd[(trackers).nt] = 0;
(trackers).nt++;
}
}
datainputstream.close();
medium.newpolys(i_109_, i - i_109_, i_111_, i_110_ - i_111_,
trackers, notb);
medium.newclouds(i_109_, i, i_111_, i_110_);
medium.newmountains(i_109_, i, i_111_, i_110_);
medium.newstars();
trackers.devidetrackers(i_109_, i - i_109_, i_111_,
i_110_ - i_111_);
} catch (Exception exception) {
(checkpoints).stage = -3;
System.out.println(new StringBuilder().append("Error in stage ").append((checkpoints).stage)
.toString());
System.out.println(new StringBuilder().append("").append(exception).toString());
System.out.println(new StringBuilder().append("At line: ").append(string).toString());
}
if ((checkpoints).nsp < 2)
(checkpoints).stage = -3;
if ((medium).nrw * (medium).ncl >= 16000)
(checkpoints).stage = -3;
if ((checkpoints).stage != -3) {
(checkpoints).top20 = Math.abs((checkpoints).top20);
if ((checkpoints).stage == 26)
(medium).lightn = 0;
else(medium).lightn = -1;
if ((checkpoints).stage == 1 || (checkpoints).stage == 11)
(medium).nochekflk = false;
else(medium).nochekflk = true;
for (int i_144_ = 0;
i_144_ < (var_xtGraphics).nplayers; i_144_++)
u[i_144_].reset(checkpoints, ((
var_xtGraphics)
.sc[i_144_]));
var_xtGraphics.resetstat((checkpoints).stage);
checkpoints.calprox();
for (int i_145_ = 0;
i_145_ < (var_xtGraphics).nplayers; i_145_++) {
if ((var_xtGraphics).fase == 22) var_xtGraphics.colorCar((contos_108_[((var_xtGraphics).sc[i_145_])]),
i_145_);
contos[i_145_] = new ContO((contos_108_[(var_xtGraphics).sc[i_145_]]), (var_xtGraphics).xstart[i_145_],
250 - ((contos_108_[((var_xtGraphics)
.sc[i_145_])])).grat, (var_xtGraphics).zstart[i_145_],
0);
mads[i_145_].reseto((var_xtGraphics).sc[i_145_],
contos[i_145_], checkpoints);
}
if ((var_xtGraphics).fase == 2 || (var_xtGraphics).fase == -22) {
(medium).trx = (long)((i_109_ + i) / 2);
(medium).trz = (long)((i_110_ + i_111_) / 2);
(medium).ptr = 0;
(medium).ptcnt = -10;
(medium).hit = 45000;
(medium).fallen = 0;
(medium).nrnd = 0;
(medium).trk = 1;
(medium).ih = 25;
(medium).iw = 65;
(medium).h = 425;
(medium).w = 735;
(var_xtGraphics).fase = 1;
mouses = 0;
}
if ((var_xtGraphics).fase == 22) {
(medium).crs = false;
(var_xtGraphics).fase = 5;
}
if ((checkpoints).stage > 0) {
int i_146_ = (checkpoints).stage;
if (i_146_ > 27) i_146_ -= 27;
else if (i_146_ > 10) i_146_ -= 10;
(var_xtGraphics).asay = new StringBuilder().append("Stage ").append(i_146_)
.append(": ").append((checkpoints).name).append(" ").toString();
} else(var_xtGraphics).asay = new StringBuilder().append("Custom Stage: ").append((checkpoints).name).append(" ").toString();
record.reset(contos);
} else if ((var_xtGraphics).fase == 2)
(var_xtGraphics).fase = 1;
System.gc();
}
public boolean loadstagePreview(int i, String string, ContO[] contos,
ContO[] contos_147_, Medium medium,
CheckPoints checkpoints) {
boolean bool = true;
if (i < 100) {
(checkpoints).stage = i;
if ((checkpoints).stage < 0)
(checkpoints).name = string;
} else {
(checkpoints).stage = -2;
if (sgame.getSelectedIndex() == 3 || sgame.getSelectedIndex() == 4)
(checkpoints).name = mstgs.getSelectedItem();
else {
int i_148_ = (mstgs.getSelectedItem()
.indexOf(" ") + 1);
if (i_148_ > 0)
(checkpoints).name = mstgs.getSelectedItem()
.substring(i_148_);
}
}
nob = 0;
(checkpoints).n = 0;
(checkpoints).nsp = 0;
(checkpoints).fn = 0;
(checkpoints).haltall = false;
(checkpoints).wasted = 0;
(checkpoints).catchfin = 0;
(medium).ground = 250;
view = 0;
(medium).trx = 0L;
(medium).trz = 0L;
int i_149_ = 0;
int i_150_ = 100;
int i_151_ = 0;
int i_152_ = 100;
String string_153_ = "";
try {
DataInputStream datainputstream;
if ((checkpoints).stage > 0) {
URL url = (new URL(new StringBuilder().append("http://multiplayer.needformadness.com/stages/")
.append((checkpoints).stage).append(".txt").toString()));
datainputstream = new DataInputStream(url.openStream());
} else {
String string_154_ = new StringBuilder().append("http://multiplayer.needformadness.com/tracks/")
.append((checkpoints).name).append(".radq").toString();
string_154_ = string_154_.replace(' ', '_');
URL url = new URL(string_154_);
int i_155_ = url.openConnection().getContentLength();
DataInputStream datainputstream_156_ = new DataInputStream(url.openStream());
byte[] is = new byte[i_155_];
datainputstream_156_.readFully(is);
ZipInputStream zipinputstream;
if (is[0] == 80 && is[1] == 75 && is[2] == 3) zipinputstream = new ZipInputStream(new ByteArrayInputStream(is));
else {
byte[] is_157_ = new byte[i_155_ - 40];
for (int i_158_ = 0; i_158_ < i_155_ - 40; i_158_++) {
int i_159_ = 20;
if (i_158_ >= 500) i_159_ = 40;
is_157_[i_158_] = is[i_158_ + i_159_];
}
zipinputstream = (new ZipInputStream(new ByteArrayInputStream(is_157_)));
}
ZipEntry zipentry = zipinputstream.getNextEntry();
int i_160_ = Integer.valueOf(zipentry.getName()).intValue();
byte[] is_161_ = new byte[i_160_];
int i_162_ = 0;
int i_163_;
for ( ; i_160_ > 0; i_160_ -= i_163_) {
i_163_ = zipinputstream.read(is_161_, i_162_, i_160_);
i_162_ += i_163_;
}
zipinputstream.close();
datainputstream_156_.close();
datainputstream = new DataInputStream(new ByteArrayInputStream(is_161_));
}
String string_164_;
while ((string_164_ = datainputstream.readLine()) != null) {
string_153_ = new StringBuilder().append("").append(string_164_.trim()).toString();
if (string_153_.startsWith("snap")) medium.setsnap(getint("snap", string_153_, 0),
getint("snap", string_153_, 1),
getint("snap", string_153_, 2));
if (string_153_.startsWith("sky")) medium.setsky(getint("sky", string_153_, 0),
getint("sky", string_153_, 1),
getint("sky", string_153_, 2));
if (string_153_.startsWith("ground")) medium.setgrnd(getint("ground", string_153_, 0),
getint("ground", string_153_, 1),
getint("ground", string_153_, 2));
if (string_153_.startsWith("polys")) medium.setpolys(getint("polys", string_153_, 0),
getint("polys", string_153_, 1),
getint("polys", string_153_, 2));
if (string_153_.startsWith("fog")) medium.setfade(getint("fog", string_153_, 0),
getint("fog", string_153_, 1),
getint("fog", string_153_, 2));
if (string_153_.startsWith("texture")) medium.setexture(getint("texture", string_153_, 0),
getint("texture", string_153_, 1),
getint("texture", string_153_, 2),
getint("texture", string_153_, 3));
if (string_153_.startsWith("clouds")) medium.setcloads(getint("clouds", string_153_, 0),
getint("clouds", string_153_, 1),
getint("clouds", string_153_, 2),
getint("clouds", string_153_, 3),
getint("clouds", string_153_, 4));
if (string_153_.startsWith("density")) {
(medium).fogd = (getint("density", string_153_, 0) + 1) * 2 - 1;
if ((medium).fogd < 1)
(medium).fogd = 1;
if ((medium).fogd > 30)
(medium).fogd = 30;
}
if (string_153_.startsWith("fadefrom")) medium.fadfrom(getint("fadefrom", string_153_, 0));
if (string_153_.startsWith("lightson"))
(medium).lightson = true;
if (string_153_.startsWith("mountains"))
(medium).mgen = getint("mountains", string_153_, 0);
if (string_153_.startsWith("soundtrack")) {
(checkpoints).trackname = getstring("soundtrack", string_153_, 0);
(checkpoints).trackvol = getint("soundtrack", string_153_, 1);
if ((checkpoints).trackvol < 50)
(checkpoints).trackvol = 50;
if ((checkpoints).trackvol > 300)
(checkpoints).trackvol = 300;
}
if (string_153_.startsWith("set")) {
int i_165_ = getint("set", string_153_, 0);
i_165_ += 46;
contos[nob] = new ContO(contos_147_[i_165_],
getint("set", string_153_, 1), ((medium).ground - (contos_147_[i_165_]).grat),
getint("set", string_153_, 2),
getint("set", string_153_, 3));
((contos[nob]).t)
.nt = 0;
if (string_153_.indexOf(")p") != -1) {
(checkpoints).x[(checkpoints).n] = getint("chk", string_153_, 1);
(checkpoints).z[(checkpoints).n] = getint("chk", string_153_, 2);
(checkpoints).y[(checkpoints).n] = 0;
(checkpoints).typ[(checkpoints).n] = 0;
if (string_153_.indexOf(")pt") != -1)
(checkpoints).typ[(checkpoints).n] = -1;
if (string_153_.indexOf(")pr") != -1)
(checkpoints).typ[(checkpoints).n] = -2;
if (string_153_.indexOf(")po") != -1)
(checkpoints).typ[(checkpoints).n] = -3;
if (string_153_.indexOf(")ph") != -1)
(checkpoints).typ[(checkpoints).n] = -4;
if (string_153_.indexOf("out") != -1) System.out.println(new StringBuilder().append("out: ").append((checkpoints)
.n)
.toString());
(checkpoints).n++;
}
nob++;
}
if (string_153_.startsWith("chk")) {
int i_166_ = getint("chk", string_153_, 0);
i_166_ += 46;
int i_167_ = ((medium).ground - (contos_147_[i_166_]).grat);
if (i_166_ == 110) i_167_ = getint("chk", string_153_, 4);
contos[nob] = new ContO(contos_147_[i_166_],
getint("chk", string_153_, 1), i_167_,
getint("chk", string_153_, 2),
getint("chk", string_153_, 3));
(checkpoints).x[((checkpoints)
.n)] = getint("chk", string_153_, 1);
(checkpoints).z[((checkpoints)
.n)] = getint("chk", string_153_, 2);
(checkpoints).y[((checkpoints)
.n)] = i_167_;
if (getint("chk", string_153_, 3) == 0)
(checkpoints).typ[(checkpoints).n] = 1;
else(checkpoints).typ[(checkpoints).n] = 2;
(checkpoints).pcs = (checkpoints).n;
(checkpoints).n++;
(contos[nob]).checkpoint = (checkpoints).nsp + 1;
(checkpoints).nsp++;
nob++;
}
if (string_153_.startsWith("fix")) {
int i_168_ = getint("fix", string_153_, 0);
i_168_ += 46;
contos[nob] = new ContO(contos_147_[i_168_],
getint("fix", string_153_, 1),
getint("fix", string_153_, 3),
getint("fix", string_153_, 2),
getint("fix", string_153_, 4));
(checkpoints).fx[((checkpoints)
.fn)] = getint("fix", string_153_, 1);
(checkpoints).fz[((checkpoints)
.fn)] = getint("fix", string_153_, 2);
(checkpoints).fy[((checkpoints)
.fn)] = getint("fix", string_153_, 3);
(contos[nob]).elec = true;
if (getint("fix", string_153_, 4) != 0) {
(checkpoints).roted[(checkpoints).fn] = true;
(contos[nob]).roted = true;
} else(checkpoints).roted[(checkpoints).fn] = false;
if (string_153_.indexOf(")s") != -1)
(checkpoints).special[(checkpoints).fn] = true;
else(checkpoints).special[(checkpoints).fn] = false;
(checkpoints).fn++;
nob++;
}
if (string_153_.startsWith("nlaps")) {
(checkpoints).nlaps = getint("nlaps", string_153_, 0);
if ((checkpoints).nlaps < 1)
(checkpoints).nlaps = 1;
if ((checkpoints).nlaps > 15)
(checkpoints).nlaps = 15;
}
if ((checkpoints).stage > 0 && string_153_.startsWith("name"))
(checkpoints).name = getstring("name", string_153_, 0).replace('|', ',');
if (string_153_.startsWith("stagemaker"))
(checkpoints).maker = getstring("stagemaker", string_153_, 0);
if (string_153_.startsWith("publish"))
(checkpoints).pubt = getint("publish", string_153_, 0);
if (string_153_.startsWith("maxr")) {
int i_169_ = getint("maxr", string_153_, 1);
i_149_ = i_169_;
}
if (string_153_.startsWith("maxl")) {
int i_170_ = getint("maxl", string_153_, 1);
i_150_ = i_170_;
}
if (string_153_.startsWith("maxt")) {
int i_171_ = getint("maxt", string_153_, 1);
i_151_ = i_171_;
}
if (string_153_.startsWith("maxb")) {
int i_172_ = getint("maxb", string_153_, 1);
i_152_ = i_172_;
}
}
datainputstream.close();
medium.newpolys(i_150_, i_149_ - i_150_, i_152_, i_151_ - i_152_,
null, notb);
medium.newclouds(i_150_, i_149_, i_152_, i_151_);
medium.newmountains(i_150_, i_149_, i_152_, i_151_);
medium.newstars();
} catch (Exception exception) {
bool = false;
System.out.println(new StringBuilder().append("Error in stage ").append((checkpoints).stage)
.toString());
System.out.println(new StringBuilder().append("").append(exception).toString());
System.out.println(new StringBuilder().append("At line: ").append(string_153_).toString());
}
if ((checkpoints).nsp < 2) bool = false;
if ((medium).nrw * (medium).ncl >= 16000) bool = false;
(medium).trx = (long)((i_150_ + i_149_) / 2);
(medium).trz = (long)((i_151_ + i_152_) / 2);
System.gc();
return bool;
}
public void loadbase(ContO[] contos, Medium medium, Trackers trackers,
xtGraphics var_xtGraphics, boolean bool) {
String[] strings = {
"2000tornados", "formula7", "canyenaro", "lescrab", "nimi",
"maxrevenge", "leadoxide", "koolkat", "drifter", "policecops",
"mustang", "king", "audir8", "masheen", "radicalone",
"drmonster"
};
String[] strings_173_ = {
"road", "froad", "twister2", "twister1", "turn", "offroad",
"bumproad", "offturn", "nroad", "nturn", "roblend", "noblend",
"rnblend", "roadend", "offroadend", "hpground", "ramp30",
"cramp35", "dramp15", "dhilo15", "slide10", "takeoff",
"sramp22", "offbump", "offramp", "sofframp", "halfpipe",
"spikes", "rail", "thewall", "checkpoint", "fixpoint",
"offcheckpoint", "sideoff", "bsideoff", "uprise", "riseroad",
"sroad", "soffroad", "tside", "launchpad", "thenet",
"speedramp", "offhill", "slider", "uphill", "roll1", "roll2",
"roll3", "roll4", "roll5", "roll6", "opile1", "opile2",
"aircheckpoint", "tree1", "tree2", "tree3", "tree4", "tree5",
"tree6", "tree7", "tree8", "cac1", "cac2", "cac3", "8sroad",
"8soffroad"
};
int i = 0;
(var_xtGraphics).dnload += 6;
try {
ZipInputStream zipinputstream;
if (!bool) {
File file = new File(new StringBuilder().append("").append(Madness.fpath).append("data/models.zip").toString());
zipinputstream = new ZipInputStream(new FileInputStream(file));
} else {
URL url = (new URL("http://multiplayer.needformadness.com/data/models.zip"));
zipinputstream = new ZipInputStream(url.openStream());
}
ZipEntry zipentry = zipinputstream.getNextEntry();
for ( ; zipentry != null;
zipentry = zipinputstream.getNextEntry()) {
int i_175_ = 0;
for (int i_176_ = 0; i_176_ < 16; i_176_++) {
if (zipentry.getName().startsWith(strings[i_176_])) i_175_ = i_176_;
}
for (int i_177_ = 0; i_177_ < 68; i_177_++) {
if (zipentry.getName().startsWith(strings_173_[i_177_])) i_175_ = i_177_ + 56;
}
int i_178_ = (int) zipentry.getSize();
i += i_178_;
byte[] is = new byte[i_178_];
int i_179_ = 0;
int i_180_;
for ( ; i_178_ > 0; i_178_ -= i_180_) {
i_180_ = zipinputstream.read(is, i_179_, i_178_);
i_179_ += i_180_;
}
contos[i_175_] = new ContO(is, medium, trackers);
(var_xtGraphics).dnload++;
}
zipinputstream.close();
} catch (Exception exception) {
System.out.println(new StringBuilder().append("Error Reading Models: ").append(exception).toString());
}
System.gc();
if (mload != -1 && i != 615671) mload = 2;
}
public int getint(String string, String string_181_, int i) {
int i_182_ = 0;
String string_183_ = "";
for (int i_184_ = string.length() + 1; i_184_ < string_181_.length();
i_184_++) {
String string_185_ = new StringBuilder().append("").append(string_181_.charAt(i_184_)).toString();
if (string_185_.equals(",") || string_185_.equals(")")) {
i_182_++;
i_184_++;
}
if (i_182_ == i) string_183_ = new StringBuilder().append(string_183_).append(string_181_.charAt(i_184_)).toString();
}
return Integer.valueOf(string_183_).intValue();
}
public String getstring(String string, String string_186_, int i) {
int i_187_ = 0;
String string_188_ = "";
for (int i_189_ = string.length() + 1; i_189_ < string_186_.length();
i_189_++) {
String string_190_ = new StringBuilder().append("").append(string_186_.charAt(i_189_)).toString();
if (string_190_.equals(",") || string_190_.equals(")")) {
i_187_++;
i_189_++;
}
if (i_187_ == i) string_188_ = new StringBuilder().append(string_188_).append(string_186_.charAt(i_189_)).toString();
}
return string_188_;
}
public void start() {
if (gamer == null) gamer = new Thread(this);
gamer.start();
}
public void stop() {
if (exwist && gamer != null) {
System.gc();
gamer.stop();
gamer = null;
}
exwist = true;
}
public void setcarcookie(int i, String string, float[] fs, int i_191_,
int[] is, boolean bool) {
try {
File file = new File(new StringBuilder().append("").append(Madness.fpath).append("data/user.data").toString());
String[] strings = {
"", "", "", "", ""
};
if (file.exists()) {
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
String string_192_;
for (int i_193_ = 0;
((string_192_ = bufferedreader.readLine()) != null && i_193_ < 5);
i_193_++)
strings[i_193_] = string_192_;
bufferedreader.close();
}
if (i_191_ == 0) strings[1] = new StringBuilder().append("lastcar(").append(i).append(",").append((int)(fs[0] * 100.0F)).append(",").append((int)(fs[1] * 100.0F)).append(",").append((int)(fs[2] * 100.0F)).append(",").append((int)(fs[3] * 100.0F)).append(",").append((int)(fs[4] * 100.0F)).append(",").append((int)(fs[5] * 100.0F)).append(",").append(string).append(")").toString();
if (i_191_ == 1) strings[2] = new StringBuilder().append("NFM1(").append(i).append(",").append(is[0]).append(")").toString();
if (i_191_ == 2) strings[3] = new StringBuilder().append("NFM2(").append(i).append(",").append(is[1]).append(")").toString();
strings[4] = new StringBuilder().append("graphics(").append(moto).append(",").append(Madness.anti).append(")").toString();
BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file));
for (int i_195_ = 0; i_195_ < 5; i_195_++) {
bufferedwriter.write(strings[i_195_]);
bufferedwriter.newLine();
}
bufferedwriter.close();
} catch (Exception exception) {
/* empty */
}
}
public void setloggedcookie() {
try {
File file = new File(new StringBuilder().append("").append(Madness.fpath).append("data/user.data").toString());
String[] strings = {
"", "", "", "", ""
};
if (file.exists()) {
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
String string;
for (int i = 0;
(string = bufferedreader.readLine()) != null && i < 5;
i++)
strings[i] = string;
bufferedreader.close();
}
if (keplo.getState()) strings[0] = new StringBuilder().append("lastuser(").append(tnick.getText()).append(",").append(tpass.getText()).append(")").toString();
else strings[0] = new StringBuilder().append("lastuser(").append(tnick.getText()).append(")").toString();
BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < 5; i++) {
bufferedwriter.write(strings[i]);
bufferedwriter.newLine();
}
bufferedwriter.close();
} catch (Exception exception) {
/* empty */
}
}
public void readcookies(xtGraphics var_xtGraphics, CarDefine cardefine,
ContO[] contos) {
(var_xtGraphics).nickname = "";
try {
File file = new File(new StringBuilder().append("").append(Madness.fpath).append("data/user.data").toString());
String[] strings = {
"", "", "", "", ""
};
if (file.exists()) {
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
String string;
for (int i = 0;
(string = bufferedreader.readLine()) != null && i < 5;
i++)
strings[i] = string;
bufferedreader.close();
}
if (strings[0].startsWith("lastuser")) {
(var_xtGraphics).nickname = getstring("lastuser", strings[0], 0);
if (!(var_xtGraphics).nickname.equals(""))
(var_xtGraphics).opselect = 1;
String string = "";
try {
string = getstring("lastuser", strings[0], 1);
} catch (Exception exception) {
string = "";
}
if (!string.equals("")) {
tnick.setText((var_xtGraphics).nickname);
tpass.setText(string);
(var_xtGraphics).autolog = true;
}
}
if (strings[2].startsWith("NFM1")) {
int i = getint("NFM1", strings[2], 0);
if (i >= 0 && i < 16) {
(var_xtGraphics).scm[0] = i;
(var_xtGraphics).firstime = false;
}
i = getint("NFM1", strings[2], 1);
if (i >= 1 && i <= 11)
(var_xtGraphics).unlocked[0] = i;
}
if (strings[3].startsWith("NFM2")) {
int i = getint("NFM2", strings[3], 0);
if (i >= 0 && i < 16) {
(var_xtGraphics).scm[1] = i;
(var_xtGraphics).firstime = false;
}
i = getint("NFM2", strings[3], 1);
if (i >= 1 && i <= 17)
(var_xtGraphics).unlocked[1] = i;
}
if (strings[4].startsWith("graphics")) {
int i = getint("graphics", strings[4], 0);
if (i >= 0 && i <= 1) moto = i;
i = getint("graphics", strings[4], 1);
if (i >= 0 && i <= 1) Madness.anti = i;
}
if (strings[1].startsWith("lastcar")) {
int i = getint("lastcar", strings[1], 0);
(cardefine).lastcar = getstring("lastcar", strings[1], 7);
if (i >= 0 && i < 36) {
(var_xtGraphics).osc = i;
(var_xtGraphics).firstime = false;
}
int i_198_ = 0;
for (int i_199_ = 0; i_199_ < 6; i_199_++) {
i = getint("lastcar", strings[1], i_199_ + 1);
if (i >= 0 && i <= 100) {
(var_xtGraphics).arnp[i_199_] = (float) i / 100.0F;
i_198_++;
}
}
if (i_198_ == 6 && (var_xtGraphics).osc >= 0 && (var_xtGraphics).osc <= 15) {
Color color = (Color.getHSBColor((var_xtGraphics).arnp[0], (var_xtGraphics).arnp[1],
1.0F - (var_xtGraphics).arnp[2]));
Color color_200_ = (Color.getHSBColor((var_xtGraphics).arnp[3], (var_xtGraphics).arnp[4],
1.0F - (var_xtGraphics).arnp[5]));
for (int i_201_ = 0;
(i_201_ < (
contos[(var_xtGraphics).osc]).npl);
i_201_++) {
if ((
(contos[((var_xtGraphics)
.osc)]).p[i_201_]).colnum == 1) {
(
(contos[((var_xtGraphics)
.osc)]).p[i_201_]).c[0] = color.getRed();
(
(contos[((var_xtGraphics)
.osc)]).p[i_201_]).c[1] = color.getGreen();
(
(contos[((var_xtGraphics)
.osc)]).p[i_201_]).c[2] = color.getBlue();
}
}
for (int i_202_ = 0;
(i_202_ < (
contos[(var_xtGraphics).osc]).npl);
i_202_++) {
if ((
(contos[((var_xtGraphics)
.osc)]).p[i_202_]).colnum == 2) {
(
(contos[((var_xtGraphics)
.osc)]).p[i_202_]).c[0] = color_200_.getRed();
(
(contos[((var_xtGraphics)
.osc)]).p[i_202_]).c[1] = color_200_.getGreen();
(
(contos[((var_xtGraphics)
.osc)]).p[i_202_]).c[2] = color_200_.getBlue();
}
}
}
}
} catch (Exception exception) {
/* empty */
}
}
public void regprom() {
/* empty */
}
public boolean mouseUp(Event event, int i, int i_203_) {
if (!exwist) {
if (mouses == 11) {
xm = (int)((float)(i - apx) / apmult);
ym = (int)((float)(i_203_ - apy) / apmult);
mouses = -1;
}
moused = false;
}
if (!Madness.fullscreen) {
if (i > getWidth() / 2 - 55 && i < getWidth() / 2 + 7 && i_203_ > 21 && i_203_ < 38 && !onbar) {
if (smooth == 1) smooth = 0;
else smooth = 1;
showsize = 60;
}
if (i > getWidth() / 2 + 133 && i < getWidth() / 2 + 231 && i_203_ > 7 && i_203_ < 24 && !onbar) {
if (Madness.anti == 0) Madness.anti = 1;
else Madness.anti = 0;
showsize = 60;
}
if (i > getWidth() / 2 + 133 && i < getWidth() / 2 + 231 && i_203_ > 24 && i_203_ < 41 && !onbar) {
if (moto == 0) moto = 1;
else moto = 0;
showsize = 60;
}
if (oncarm) Madness.carmaker();
if (onstgm) Madness.stagemaker();
if (onfulls) Madness.gofullscreen();
onbar = false;
}
return false;
}
public boolean mouseDown(Event event, int i, int i_204_) {
requestFocus();
if (!exwist) {
if (mouses == 0) {
xm = (int)((float)(i - apx) / apmult);
ym = (int)((float)(i_204_ - apy) / apmult);
mouses = 1;
}
moused = true;
}
if (!Madness.fullscreen) sizescreen(i, i_204_);
return false;
}
public boolean mouseMove(Event event, int i, int i_205_) {
if (!exwist && !lostfcs) {
xm = (int)((float)(i - apx) / apmult);
ym = (int)((float)(i_205_ - apy) / apmult);
}
if (!Madness.fullscreen) {
if (showsize < 20) showsize = 20;
if (i > 50 && i < 192 && i_205_ > 14 && i_205_ < 37) {
if (!oncarm) {
oncarm = true;
setCursor(new Cursor(12));
}
} else if (oncarm) {
oncarm = false;
setCursor(new Cursor(0));
}
if (i > getWidth() - 208 && i < getWidth() - 50 && i_205_ > 14 && i_205_ < 37) {
if (!onstgm) {
onstgm = true;
setCursor(new Cursor(12));
}
} else if (onstgm) {
onstgm = false;
setCursor(new Cursor(0));
}
if (i > getWidth() / 2 + 22 && i < getWidth() / 2 + 122 && i_205_ > 14 && i_205_ < 37) {
if (!onfulls) {
onfulls = true;
setCursor(new Cursor(12));
}
} else if (onfulls) {
onfulls = false;
setCursor(new Cursor(0));
}
}
return false;
}
public boolean mouseDrag(Event event, int i, int i_206_) {
if (!exwist && !lostfcs) {
xm = (int)((float)(i - apx) / apmult);
ym = (int)((float)(i_206_ - apy) / apmult);
}
if (!Madness.fullscreen) sizescreen(i, i_206_);
return false;
}
public boolean lostFocus(Event event, Object object) {
if (!exwist && !lostfcs) {
lostfcs = true;
fcscnt = 10;
if (u[0] != null) {
if ((u[0]).multion == 0) u[0].falseo(1);
else if ((u[0]).chatup == 0) requestFocus();
setCursor(new Cursor(0));
}
}
return false;
}
public boolean gotFocus(Event event, Object object) {
if (!exwist && lostfcs) lostfcs = false;
return false;
}
public void mouseW(int i) {
if (!exwist) mousew += i * 4;
}
public void sizescreen(int i, int i_207_) {
if ((i > getWidth() / 2 - 230 && i < getWidth() / 2 - 68 && i_207_ > 21 && i_207_ < 39) || onbar) {
reqmult = (float)(i - (getWidth() / 2 - 222)) / 141.0F;
if ((double) reqmult < 0.1) reqmult = 0.0F;
if (reqmult > 1.0F) reqmult = 1.0F;
onbar = true;
showsize = 100;
}
}
public void catchlink() {
if (!lostfcs) {
if ((xm > 65 && xm < 735 && ym > 135 && ym < 194) || (xm > 275 && xm < 525 && ym > 265 && ym < 284)) {
setCursor(new Cursor(12));
if (mouses == 2) openurl("http:
} else setCursor(new Cursor(0));
}
}
public void onfmmlink() {
openurl("https://github.com/chrishansen69/OpenNFMM");
}
public void musiclink() {
openurl("http://multiplayer.needformadness.com/music.html");
}
public void reglink() {
openurl("http://multiplayer.needformadness.com/register.html?ref=game");
}
public void madlink() {
openurl("http:
}
public void editlink(String string, boolean bool) {
String string_208_ = "";
if (bool) string_208_ = "?display=upgrade";
openurl(new StringBuilder().append("http://multiplayer.needformadness.com/edit.pl").append(string_208_).append("#").append(string).append("").toString());
}
public void regnew() {
openurl("http://multiplayer.needformadness.com/registernew.pl");
}
public void multlink() {
openurl("http://multiplayer.needformadness.com/");
}
public void setupini() {
Madness.inisetup = true;
try {
File file = new File(new StringBuilder().append("").append(Madness.fpath).append("Madness.ini").toString());
if (file.exists()) {
String[] strings = new String[40];
int i = 0;
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
String string;
for ( ;
(string = bufferedreader.readLine()) != null && i < 40;
i++) {
strings[i] = string;
if (strings[i].startsWith("Class Path")) {
if (strings[i].indexOf("madapps.jar") != -1) strings[i] = "Class Path=\\data\\madapps.jar;";
else strings[i] = "Class Path=\\data\\madapp.jar;";
}
if (strings[i].startsWith("JRE Path")) strings[i] = "JRE Path=data\\jre\\";
}
bufferedreader.close();
BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file));
for (int i_210_ = 0; i_210_ < i; i_210_++) {
bufferedwriter.write(strings[i_210_]);
bufferedwriter.newLine();
}
bufferedwriter.close();
}
} catch (Exception exception) {
/* empty */
}
Madness.inisetup = false;
}
public void openurl(String string) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(new URI(string));
} catch (Exception exception) {
/* empty */
}
} else {
try {
Runtime.getRuntime().exec(new StringBuilder().append("").append(Madness.urlopen()).append(" ").append(string).append("").toString());
} catch (Exception exception) {
/* empty */
}
}
}
public boolean keyDown(Event event, int i) {
if (!exwist) {
if ((u[0]).multion < 2) {
if (i == 1004)
(u[0]).up = true;
if (i == 1005)
(u[0]).down = true;
if (i == 1007)
(u[0]).right = true;
if (i == 1006)
(u[0]).left = true;
if (i == 32)
(u[0]).handb = true;
}
if (i == 10)
(u[0]).enter = true;
if (i == 27) {
(u[0]).exit = true;
if ((u[0]).chatup != 0)
(u[0]).chatup = 0;
}
if ((i == 67 || i == 99) && (u[0]).multion != 0 && (u[0]).chatup == 0) {
(u[0]).chatup = 2;
view = 0;
}
if ((u[0]).chatup == 0) {
if (i == 120 || i == 88)
(u[0]).lookback = -1;
if (i == 122 || i == 90)
(u[0]).lookback = 1;
if (i == 77 || i == 109) {
if ((u[0]).mutem)
(u[0]).mutem = false;
else(u[0]).mutem = true;
}
if (i == 78 || i == 110) {
if ((u[0]).mutes)
(u[0]).mutes = false;
else(u[0]).mutes = true;
}
if (i == 97 || i == 65) {
if ((u[0]).arrace)
(u[0]).arrace = false;
else(u[0]).arrace = true;
}
if (i == 115 || i == 83) {
if ((u[0]).radar)
(u[0]).radar = false;
else(u[0]).radar = true;
}
if (i == 118 || i == 86) {
view++;
if (view == 3) view = 0;
}
}
}
return false;
}
public boolean keyUp(Event event, int i) {
if (!exwist) {
if ((u[0]).multion < 2) {
if (i == 1004)
(u[0]).up = false;
if (i == 1005)
(u[0]).down = false;
if (i == 1007)
(u[0]).right = false;
if (i == 1006)
(u[0]).left = false;
if (i == 32)
(u[0]).handb = false;
}
if (i == 27) {
(u[0]).exit = false;
if (Madness.fullscreen) Madness.exitfullscreen();
}
if (i == 120 || i == 88 || i == 122 || i == 90)
(u[0]).lookback = 0;
}
return false;
}
} |
package com.speakingfish.protocol.ssp.type;
import java.io.OutputStream;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import com.speakingfish.common.Maps;
//import com.speakingfish.common.function.Invoker;
/*
import com.speakingfish.common.traverse.Proceed;
import com.speakingfish.common.traverse.VisitorHolder;
*/
import com.speakingfish.common.type.LocalNamed;
import com.speakingfish.common.type.Named;
import com.speakingfish.protocol.ssp.Any;
import com.speakingfish.protocol.ssp.AnyObject;
import com.speakingfish.protocol.ssp.Helper;
import com.speakingfish.protocol.ssp.LocalAny;
import com.speakingfish.protocol.ssp.LocalAnyObject;
import com.speakingfish.protocol.ssp.Types;
//import com.speakingfish.protocol.ssp.ValueVisitor;
/*
import static com.speakingfish.common.traverse.Traverses.*;
*/
import static com.speakingfish.protocol.ssp.bin.Helper.*;
public class ObjectImpl<CONTEXT> extends AnyDefaultImpl<CONTEXT, AnyObject> implements LocalAnyObject<CONTEXT> {
protected final List<String> _names;
protected final List<Any<?>> _value;
protected AbstractList< Any<?> > _valuesList ;
protected AbstractList<Entry<String, Any<?>>> _entriesList;
protected ObjectImpl(
List<String> names,
List<Any<?>> value
) {
super();
_names = names;
_value = value;
assert _names.size() == _value.size();
}
public ObjectImpl() {
this(
new ArrayList<String>(),
new ArrayList<Any<?>>()
);
}
public void addStringEntries(Iterable<Entry<String, ? extends Any<?>>> items) {
for(final Entry<String, ? extends Any<?>> item : items) {
add(item.getKey(), item.getValue());
}
}
public void addNamedEntries(Iterable<? extends Entry<? extends Named<?>, ? extends Any<?>>> items) {
for(final Entry<? extends Named<?>, ? extends Any<?>> item : items) {
add(item.getKey().id(), item.getValue());
}
}
public void addLocalEntries(Iterable<Entry<? extends LocalNamed<CONTEXT, ?>, ? extends LocalAny<?, ?>>> items) {
for(final Entry<? extends Named<?>, ? extends Any<?>> item : items) {
add(item.getKey().id(), item.getValue());
}
}
//@Override public AnyObject get () { return this; };
@Override public LocalAnyObject<CONTEXT> get () { return this; };
@Override public short type () { return Helper.SSP_TYPE_OBJECT; };
@Override public int size () { return _value.size(); };
@Override public String toString () {
final StringBuilder result = new StringBuilder("{");
if(0 < size()) {
result.append("\"").append(nameOf(0)).append("\": ").append(item(0).toString());
for(int i = 1; i < size(); ++i) {
result.append(", \"").append(nameOf(i)).append("\": ").append(item(i).toString());
}
}
result.append("}");
return result.toString();
}
@Override public int add (String name, Any<?> value) {
int index = indexOf(name);
if(0 <= index) {
_value.set(index, value);
return index;
} else {
_names.add(name);
_value.add(value);
return _value.size();
}
};
@Override public Any<?> update (int index, Any<?> value) { return _value.set(index, value); };
@Override public Any<?> update (String name, Any<?> value) { return update(indexOf(name), value); };
@Override public Any<?> remove (int index ) {
_names.remove(index);
return _value.remove(index);
};
@Override public Any<?> remove (String name ) { return remove(indexOf(name)); };
@Override public int indexOf(String name ) { return _names.indexOf(name); };
@Override public String nameOf (int index ) { return _names.get(index); };
@Override public Any<?> item (int index ) { return _value.get(index); };
@Override public Any<?> item (String name ) {
final int index = indexOf(name);
return (index < 0) ? null : item(index);
};
@Override public <T> int add (Named<T> name, Any<T> value) { return add (name.id(), value) ; };
@Override public <T> Any<T> update (Named<T> name, Any<T> value) { return Types.castAnyTo(update(name.id(), value), name); };
@Override public <T> Any<T> remove (Named<T> name ) { return Types.castAnyTo(remove(name.id() ), name); };
@Override public <T> Any<T> item (Named<T> name ) { return Types.castAnyTo(item (name.id() ), name); };
@Override public <T> T value (Named<T> name ) {
final Any<T> result = item(name);
return (null == result) ? null : result.get();
};
@Override public void writeTo(OutputStream dest) {
writeObject(dest, Types.serializableSize(this));
for(int i = 0; i < size(); ++i) {
if(Types.isSerializable(item(i))) {
writeField(dest, nameOf(i));
item(i).writeTo(dest);
}
}
}
@Override public int hashCode() {
int result = 0;
for(final Any<?> value : _value) {
result+= value.hashCode();
}
return result;
}
@Override public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof Any))
return false;
final Any<?> other = (Any<?>) obj;
if(type() != other.type())
return false;
if(size() != other.size())
return false;
for(int i = 0; i < size(); ++i) {
if(!item(i).equals(other.item(nameOf(i))))
return false;
}
return true;
}
@Override protected Any<AnyObject> makeUnmodifiable() {
return new AnyUnmodifiableObjectImpl<CONTEXT>(this);
}
@Override public LocalAny<CONTEXT, AnyObject> clone() {
return new ObjectImpl<CONTEXT>(
new ArrayList<String>(_names),
new ArrayList<Any<?>>(_value)
);
}
/*
@Override public void visit(TypeVisitor visitor) {
visitor.visitObject(this);
}
*/
/*
@Override public <PROCEED extends Proceed & VisitorHolder<ValueVisitor<PROCEED>>> void _visit(PROCEED proceed, final Any<?> objectValue) {
proceed.visitor().visitObject(
nestedInvoker(proceed, new Invoker<PROCEED>() {
@Override public void invoke(PROCEED proceed) {
for(int i = 0; i < objectValue.size(); ++i) {
final Any<?> objectItem = objectValue.item(i);
proceed.visitor().visitObjectField(
nestedInvoker(proceed, new Invoker<PROCEED>() {
@Override public void invoke(PROCEED proceed) {
objectItem.visit(nestedUnknown(proceed));
}}
),
i,
objectItem.nameOf(i),
objectItem
);
}
}}
),
objectValue
);
}
*/
@Override public Entry<String, Any<?>> entry(int index) { return Maps.<String, Any<?>>keyValue(nameOf(index), item(index)); };
@Override public Entry<String, Any<?>> entry(String name ) { return Maps.<String, Any<?>>keyValue( name , item(name )); };
@Override public List<Any<?> > values () {
if(null == _valuesList) {
_valuesList = new AbstractList<Any<?>>() {
@Override public int size ( ) { return ObjectImpl.this.size ( ); }
@Override public Any<?> get (int index ) { return ObjectImpl.this.item (index ); }
@Override public Any<?> remove(int index ) { return ObjectImpl.this.remove(index ); }
@Override public Any<?> set (int index, Any<?> element) { return ObjectImpl.this.update(index, element); }
};
}
return _valuesList;
};
@Override public List<Entry<String, Any<?>>> entries() {
if(null == _entriesList) {
_entriesList = new AbstractList<Entry<String, Any<?>>>() {
@Override public int size ( ) { return ObjectImpl.this.size ( ); }
@Override public Entry<String, Any<?>> get (int index ) { return ObjectImpl.this.entry (index ); }
@Override public Entry<String, Any<?>> remove(int index ) {
final Entry<String, Any<?>> result = this.get(index);
ObjectImpl.this.remove(index);
return result;
}
@Override public boolean add ( Entry<String, Any<?>> element) {
ObjectImpl.this.add(element.getKey(), element.getValue());
return true;
}
@Override public Entry<String, Any<?>> set (int index, Entry<String, Any<?>> element) {
if(!element.getKey().equals(ObjectImpl.this.nameOf(index))) {
throw new UnsupportedOperationException("Entry key does not match index.");
}
final Entry<String, Any<?>> result = this.get(index);
ObjectImpl.this.update(index, element.getValue());
return result;
}
};
}
return _entriesList;
}
} |
package arez;
import arez.spy.ComponentInfo;
import arez.spy.ComputedValueInfo;
import arez.spy.ElementInfo;
import arez.spy.ObservableValueInfo;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ComputedValueInfoImplTest
extends AbstractArezTest
{
@Test
public void basicOperation()
throws Throwable
{
final ArezContext context = Arez.context();
final String name = ValueUtil.randomString();
final ObservableValue<Object> observableValue = context.observable();
final AtomicReference<String> value = new AtomicReference<>();
final String initialValue = ValueUtil.randomString();
value.set( initialValue );
final ComputedValue<Object> computedValue =
context.computed( name, () -> {
observableValue.reportObserved();
return value.get();
} );
final Observer observer = context.observer( computedValue::get );
final ComputedValueInfo info = computedValue.asInfo();
assertEquals( info.getComponent(), null );
assertEquals( info.getName(), name );
assertEquals( info.toString(), name );
assertEquals( info.isActive(), true );
assertEquals( info.isComputing(), false );
assertEquals( info.getPriority(), Priority.NORMAL );
assertEquals( info.getObservers().size(), 1 );
assertEquals( info.getObservers().get( 0 ).getName(), observer.getName() );
assertUnmodifiable( info.getObservers() );
assertEquals( info.getDependencies().size(), 1 );
assertEquals( info.getDependencies().get( 0 ).getName(), observableValue.getName() );
assertUnmodifiable( info.getDependencies() );
assertEquals( info.getValue(), initialValue );
assertEquals( info.isDisposed(), false );
// Dispose observer so it does not access computedValue after it is disposed
observer.dispose();
computedValue.dispose();
assertEquals( info.isDisposed(), true );
}
@Test
public void isComputing()
throws Exception
{
final ArezContext context = Arez.context();
final Spy spy = context.getSpy();
final ComputedValue<String> computedValue = context.computed( () -> "" );
assertEquals( spy.asComputedValueInfo( computedValue ).isComputing(), false );
computedValue.setComputing( true );
assertEquals( spy.asComputedValueInfo( computedValue ).isComputing(), true );
}
@Test
public void getTransactionComputing()
throws Exception
{
final ArezContext context = Arez.context();
final ComputedValue<String> computedValue = context.computed( () -> "" );
final Observer observer = computedValue.getObserver();
final Observer observer2 = context.observer( new CountAndObserveProcedure() );
computedValue.setComputing( true );
final ComputedValueInfoImpl info = (ComputedValueInfoImpl) computedValue.asInfo();
final Transaction transaction =
new Transaction( context, null, observer.getName(), observer.getMode(), observer );
Transaction.setTransaction( transaction );
// This picks up where it is the first transaction in stack
assertEquals( info.getTransactionComputing(), transaction );
final Transaction transaction2 =
new Transaction( context, transaction, ValueUtil.randomString(), observer2.getMode(), observer2 );
Transaction.setTransaction( transaction2 );
// This picks up where it is not the first transaction in stack
assertEquals( info.getTransactionComputing(), transaction );
}
@Test
public void getTransactionComputing_missingTracker()
throws Exception
{
final ArezContext context = Arez.context();
final ComputedValue<String> computedValue = context.computed( () -> "" );
computedValue.setComputing( true );
final ComputedValueInfoImpl info = (ComputedValueInfoImpl) computedValue.asInfo();
setupReadOnlyTransaction( context );
final IllegalStateException exception = expectThrows( IllegalStateException.class, info::getTransactionComputing );
assertEquals( exception.getMessage(),
"Arez-0106: ComputedValue named '" + computedValue.getName() + "' is marked as " +
"computing but unable to locate transaction responsible for computing ComputedValue" );
}
@Test
public void getDependencies()
throws Exception
{
final ArezContext context = Arez.context();
final ComputedValue<String> computedValue = context.computed( () -> "" );
final ComputedValueInfo info = computedValue.asInfo();
assertEquals( info.getDependencies().size(), 0 );
final ObservableValue<?> observableValue = context.observable();
observableValue.getObservers().add( computedValue.getObserver() );
computedValue.getObserver().getDependencies().add( observableValue );
final List<ObservableValueInfo> dependencies = info.getDependencies();
assertEquals( dependencies.size(), 1 );
assertEquals( dependencies.iterator().next().getName(), observableValue.getName() );
assertUnmodifiable( dependencies );
}
@Test
public void getDependenciesDuringComputation()
throws Exception
{
final ArezContext context = Arez.context();
final ComputedValue<String> computedValue = context.computed( () -> "" );
final ObservableValue<?> observableValue = context.observable();
final ObservableValue<?> observableValue2 = context.observable();
final ObservableValue<?> observableValue3 = context.observable();
observableValue.getObservers().add( computedValue.getObserver() );
computedValue.getObserver().getDependencies().add( observableValue );
computedValue.setComputing( true );
final ComputedValueInfo info = computedValue.asInfo();
setCurrentTransaction( computedValue.getObserver() );
assertEquals( info.getDependencies().size(), 0 );
context.getTransaction().safeGetObservables().add( observableValue2 );
context.getTransaction().safeGetObservables().add( observableValue3 );
context.getTransaction().safeGetObservables().add( observableValue2 );
final List<String> dependencies = info.getDependencies().stream().
map( ElementInfo::getName ).collect( Collectors.toList() );
assertEquals( dependencies.size(), 2 );
assertEquals( dependencies.contains( observableValue2.getName() ), true );
assertEquals( dependencies.contains( observableValue3.getName() ), true );
assertUnmodifiable( info.getDependencies() );
}
@Test
public void getComponent_ComputedValue()
{
final ArezContext context = Arez.context();
final Component component =
context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() );
final ComputedValue<Object> computedValue1 =
context.computed( component, ValueUtil.randomString(), ValueUtil::randomString );
final ComputedValue<Object> computedValue2 = context.computed( ValueUtil::randomString );
final ComponentInfo info = computedValue1.asInfo().getComponent();
assertNotNull( info );
assertEquals( info.getName(), component.getName() );
assertEquals( computedValue2.asInfo().getComponent(), null );
}
@Test
public void getComponent_ComputedValue_nativeComponentsDisabled()
{
ArezTestUtil.disableNativeComponents();
final ArezContext context = Arez.context();
final ComputedValue<Object> computedValue = context.computed( () -> "" );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> computedValue.asInfo().getComponent() );
assertEquals( exception.getMessage(),
"Arez-0109: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." );
}
@Test
public void isActive()
throws Exception
{
final ArezContext context = Arez.context();
final Spy spy = context.getSpy();
final ComputedValue<String> computedValue = context.computed( () -> "" );
assertEquals( spy.asComputedValueInfo( computedValue ).isActive(), false );
setupReadOnlyTransaction( context );
computedValue.getObserver().setState( Flags.STATE_UP_TO_DATE );
assertEquals( spy.asComputedValueInfo( computedValue ).isActive(), true );
}
@Test
public void getObservers()
throws Exception
{
final ArezContext context = Arez.context();
final Spy spy = context.getSpy();
final ComputedValue<?> computedValue = context.computed( () -> "" );
assertEquals( spy.asComputedValueInfo( computedValue ).getObservers().size(), 0 );
final Observer observer = context.observer( new CountAndObserveProcedure() );
observer.getDependencies().add( computedValue.getObservableValue() );
computedValue.getObservableValue().getObservers().add( observer );
assertEquals( spy.asComputedValueInfo( computedValue ).getObservers().size(), 1 );
// Ensure the underlying list has the Observer in places
assertEquals( computedValue.getObservableValue().getObservers().size(), 1 );
assertUnmodifiable( spy.asComputedValueInfo( computedValue ).getObservers() );
}
@SuppressWarnings( "EqualsWithItself" )
@Test
public void equalsAndHashCode()
throws Exception
{
final ArezContext context = Arez.context();
final ComputedValue<Object> computedValue1 = context.computed( () -> "1" );
final ComputedValue<Object> computedValue2 = context.computed( () -> "2" );
final ComputedValueInfo info1a = computedValue1.asInfo();
final ComputedValueInfo info1b = new ComputedValueInfoImpl( context.getSpy(), computedValue1 );
final ComputedValueInfo info2 = computedValue2.asInfo();
//noinspection EqualsBetweenInconvertibleTypes
assertEquals( info1a.equals( "" ), false );
assertEquals( info1a.equals( info1a ), true );
assertEquals( info1a.equals( info1b ), true );
assertEquals( info1a.equals( info2 ), false );
assertEquals( info1b.equals( info1a ), true );
assertEquals( info1b.equals( info1b ), true );
assertEquals( info1b.equals( info2 ), false );
assertEquals( info2.equals( info1a ), false );
assertEquals( info2.equals( info1b ), false );
assertEquals( info2.equals( info2 ), true );
assertEquals( info1a.hashCode(), computedValue1.hashCode() );
assertEquals( info1a.hashCode(), info1b.hashCode() );
assertEquals( info2.hashCode(), computedValue2.hashCode() );
}
private <T> void assertUnmodifiable( @Nonnull final Collection<T> collection )
{
assertThrows( UnsupportedOperationException.class, () -> collection.remove( collection.iterator().next() ) );
}
} |
package de.fau.cs.mad.gamekobold.jackson;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ColumnHeader {
//TODO evtl final?
public String name,type;
public boolean hidden;
public ColumnHeader(String name, String type) {
this.name = name;
this.type = type;
hidden = false;
}
@JsonCreator
public ColumnHeader(@JsonProperty("name") String name,
@JsonProperty("type") String type,
@JsonProperty("hidden") boolean hidden)
{
this.name = name;
this.type = type;
this.hidden = hidden;
}
@JsonIgnore
public boolean isInt() {
return IntegerClass.TYPE_STRING.equals(type);
}
@JsonIgnore
public boolean isString() {
return StringClass.TYPE_STRING.equals(type);
}
} |
package de.gurkenlabs.litiengine.util.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import de.gurkenlabs.litiengine.Resources;
public final class XmlUtilities {
private static final Logger log = Logger.getLogger(XmlUtilities.class.getName());
private static final Map<Class<?>, JAXBContext> jaxbContexts;
private XmlUtilities() {
}
static {
jaxbContexts = new ConcurrentHashMap<>();
}
/**
* Saves the XML, contained by the specified input with the custom
* indentation. If the input is the result of jaxb marshalling, make sure to
* set Marshaller.JAXB_FORMATTED_OUTPUT to false in order for this method to
* work properly.
*
* @param input
* The input stream that contains the original XML.
* @param fos
* The output stream that is used to save the XML.
* @param indentation
* The indentation with which the XML should be saved.
*/
public static void saveWithCustomIndetation(ByteArrayInputStream input, FileOutputStream fos, int indentation) {
try {
Transformer transformer = SAXTransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation));
Source xmlSource = new SAXSource(new org.xml.sax.InputSource(input));
StreamResult res = new StreamResult(fos);
transformer.transform(xmlSource, res);
fos.flush();
fos.close();
} catch (TransformerFactoryConfigurationError | TransformerException | IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
public static <T> JAXBContext getContext(Class<T> cls) {
try {
final JAXBContext jaxbContext;
if (jaxbContexts.containsKey(cls)) {
jaxbContext = jaxbContexts.get(cls);
} else {
jaxbContext = JAXBContext.newInstance(cls);
jaxbContexts.put(cls, jaxbContext);
}
return jaxbContext;
} catch (final JAXBException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
public static <T> T readFromFile(Class<T> cls, String path) {
try {
final JAXBContext jaxbContext = getContext(cls);
if (jaxbContext == null) {
return null;
}
final Unmarshaller um = jaxbContext.createUnmarshaller();
InputStream stream = FileUtilities.getGameResource(path);
if (stream == null) {
stream = new FileInputStream(path);
}
return (T) um.unmarshal(stream);
} catch (final JAXBException | IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
public static <T> String save(T object, String fileName, String extension) {
if (fileName == null || fileName.isEmpty()) {
return null;
}
String fileNameWithExtension = fileName;
if (!fileNameWithExtension.endsWith("." + extension)) {
fileNameWithExtension += "." + extension;
}
File newFile = new File(fileNameWithExtension);
try (FileOutputStream fileOut = new FileOutputStream(newFile)) {
JAXBContext jaxbContext = getContext(object.getClass());
if (jaxbContext == null) {
return null;
}
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
// first: marshal to byte array
jaxbMarshaller.marshal(object, out);
out.flush();
// second: postprocess xml and then write it to the file
XmlUtilities.saveWithCustomIndetation(new ByteArrayInputStream(out.toByteArray()), fileOut, 1);
out.close();
jaxbMarshaller.marshal(object, out);
} catch (JAXBException | IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
return newFile.toString();
}
} |
// modification, are permitted provided that the following conditions are met:
// and/or other materials provided with the distribution.
// * Neither the name of SimpleProps nor the names of its
// contributors may be used to endorse or promote products derived from
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// 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.
package dev.kkorolyov.simpleprops;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
/**
* A {@code Properties} which encrypts properties stored in its backing file.
* Uses a byte array as a symmetric encryption key to encrypt and decrypt bytes in the backing properties file.
*/
public class EncryptedProperties extends Properties {
private byte[] key;
/**
* Constructs a new {@code EncryptedProperties} instance for a specified file and encryption key.
* @see #EncryptedProperties(File, Properties, byte[])
*/
public EncryptedProperties(File file, byte[] key) {
this(file, null, key);
}
/**
* Constructs a new {@code Properties} instance for a specified file, default values, and encryption key.
* @param file backing filesystem file
* @param defaults default properties
* @param key symmetric encryption key to use for decrypting read file contents and encrypting written file contents.
* @throws UncheckedIOException if an I/O error occurs
*/
public EncryptedProperties(File file, Properties defaults, byte[] key) {
setFile(file);
setDefaults(defaults);
setKey(key);
try {
reload();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void setKey(byte[] newKey) {
key = Arrays.copyOf(newKey, newKey.length);
}
@Override
Properties buildFileProperties(File file) {
return new EncryptedProperties(file, key);
}
@Override
String format(String line) {
return applyKey(line);
}
private String applyKey(String line) {
byte[] lineBytes = line.getBytes(),
resultBytes = new byte[lineBytes.length];
for (int i = 0; i < resultBytes.length; i++)
resultBytes[i] = (byte) (lineBytes[i] ^ key[i % key.length]); // Wraps if not enough key
return new String(resultBytes);
}
/** @return encrypted {@code toString()} value */
public String toStringEncrypted() {
return format(toString());
}
} |
package dr.evomodel.continuous;
import dr.evolution.tree.MultivariateTraitTree;
import dr.evolution.tree.NodeRef;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DiscretizedBranchRates;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.tree.TreeStatistic;
import dr.geo.math.SphericalPolarCoordinates;
import dr.inference.model.Statistic;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.stats.DiscreteStatistics;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Marc Suchard
* @author Philippe Lemey
* @author Andrew Rambaut
*/
public class DiffusionRateStatistic extends Statistic.Abstract {
public static final String DIFFUSION_RATE_STATISTIC = "diffusionRateStatistic";
public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic";
public static final String BOOLEAN_DIS_OPTION = "greatCircleDistance";
public static final String MODE = "mode";
public static final String MEDIAN = "median";
public static final String AVERAGE = "average"; // average over all branches
public static final String WEIGHTED_AVERAGE = "weightedAverage"; // weighted average (=total distance/total time)
public static final String COEFFICIENT_OF_VARIATION = "coefficientOfVariation"; // weighted average (=total distance/total time)
public static final String STATISTIC = "statistic";
public static final String DIFFUSION_RATE = "diffusionRate"; // weighted average (=total distance/total time)
public static final String WAVEFRONT_DISTANCE = "wavefrontDistance"; // weighted average (=total distance/total time)
public static final String WAVEFRONT_RATE = "wavefrontRate"; // weighted average (=total distance/total time)
public static final String DIFFUSION_COEFFICIENT = "diffusionCoefficient";
// public static final String DIFFUSIONCOEFFICIENT = "diffusionCoefficient"; // weighted average (=total distance/total time)
// public static final String BOOLEAN_DC_OPTION = "diffusionCoefficient";
public static final String HEIGHT_UPPER = "heightUpper";
public static final String HEIGHT_LOWER = "heightLower";
public DiffusionRateStatistic(String name, List<AbstractMultivariateTraitLikelihood> traitLikelihoods,
boolean option, Mode mode,
summaryStatistic statistic, double heightUpper, double heightLower) {
super(name);
this.traitLikelihoods = traitLikelihoods;
this.useGreatCircleDistances = option;
summaryMode = mode;
summaryStat = statistic;
this.heightUpper = heightUpper;
this.heightLower = heightLower;
}
public int getDimension() {
return 1;
}
public double getStatisticValue(int dim) {
String traitName = traitLikelihoods.get(0).getTraitName();
double treelength = 0;
double treeDistance = 0;
double maxDistanceFromRoot = 0;
double maxDistanceOverTimeFromRoot = 0;
//double[] rates = null;
List<Double> rates = new ArrayList<Double>();
//double[] diffusionCoefficients = null;
List<Double> diffusionCoefficients = new ArrayList<Double>();
double waDiffusionCoefficient = 0;
for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) {
MultivariateTraitTree tree = traitLikelihood.getTreeModel();
BranchRateModel branchRates = traitLikelihood.getBranchRateModel();
for (int i = 0; i < tree.getNodeCount(); i++) {
NodeRef node = tree.getNode(i);
if (node != tree.getRoot()) {
NodeRef parentNode = tree.getParent(node);
if ((tree.getNodeHeight(parentNode) > heightLower) && (tree.getNodeHeight(node) < heightUpper)) {
double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName);
double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName);
double[] traitUp = parentTrait;
double[] traitLow = trait;
double timeUp = tree.getNodeHeight(parentNode);
double timeLow = tree.getNodeHeight(node);
double rate = (branchRates != null ? branchRates.getBranchRate(tree, node) : 1.0);
MultivariateDiffusionModel diffModel = traitLikelihood.diffusionModel;
double[] precision = diffModel.getPrecisionParameter().getParameterValues();
if (tree.getNodeHeight(parentNode) > heightUpper) {
timeUp = heightUpper;
//TODO: implement TrueNoise??
traitUp = imputeValue(trait, parentTrait, heightUpper, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false);
}
if (tree.getNodeHeight(node) < heightLower) {
timeLow = heightLower;
traitLow = imputeValue(trait, parentTrait, heightLower, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false);
}
double time = timeUp - timeLow;
treelength += time;
double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName);
if (useGreatCircleDistances && (trait.length == 2)) { // Great Circle distance
SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(traitLow[0], traitLow[1]);
SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(traitUp[0], traitUp[1]);
double distance = coord1.distance(coord2);
treeDistance += distance;
double dc = Math.pow(distance,2)/(4*time);
diffusionCoefficients.add(dc);
waDiffusionCoefficient += dc*time;
rates.add(distance/time);
SphericalPolarCoordinates rootCoord = new SphericalPolarCoordinates(rootTrait[0], rootTrait[1]);
double tempDistanceFromRoot = rootCoord.distance(coord2);
if (tempDistanceFromRoot > maxDistanceFromRoot){
maxDistanceFromRoot = tempDistanceFromRoot;
maxDistanceOverTimeFromRoot = tempDistanceFromRoot/(tree.getNodeHeight(tree.getRoot()) - timeLow);
//distance between traitLow and traitUp for maxDistanceFromRoot
if (timeUp == heightUpper) {
maxDistanceFromRoot = distance;
maxDistanceOverTimeFromRoot = distance/time;
}
}
} else {
double distance = getNativeDistance(traitLow, traitLow);
treeDistance += distance;
double dc = Math.pow(distance,2)/(4*time);
diffusionCoefficients.add(dc);
waDiffusionCoefficient += dc*time;
rates.add(distance/time);
double tempDistanceFromRoot = getNativeDistance(traitLow, rootTrait);
if (tempDistanceFromRoot > maxDistanceFromRoot){
maxDistanceFromRoot = tempDistanceFromRoot;
maxDistanceOverTimeFromRoot = tempDistanceFromRoot/(tree.getNodeHeight(tree.getRoot()) - timeLow);
//distance between traitLow and traitUp for maxDistanceFromRoot
if (timeUp == heightUpper) {
maxDistanceFromRoot = distance;
maxDistanceOverTimeFromRoot = distance/time;
}
}
}
}
}
}
}
if (summaryStat == summaryStatistic.DIFFUSION_RATE){
if (summaryMode == Mode.AVERAGE) {
return DiscreteStatistics.mean(toArray(rates));
} else if (summaryMode == Mode.MEDIAN) {
return DiscreteStatistics.median(toArray(rates));
} else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
// don't compute mean twice
final double mean = DiscreteStatistics.mean(toArray(rates));
return Math.sqrt(DiscreteStatistics.variance(toArray(rates), mean)) / mean;
} else {
return treeDistance / treelength;
}
} else if (summaryStat == summaryStatistic.DIFFUSION_COEFFICIENT) {
if (summaryMode == Mode.AVERAGE) {
return DiscreteStatistics.mean(toArray(diffusionCoefficients));
} else if (summaryMode == Mode.MEDIAN) {
return DiscreteStatistics.median(toArray(diffusionCoefficients));
} else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
// don't compute mean twice
final double mean = DiscreteStatistics.mean(toArray(diffusionCoefficients));
return Math.sqrt(DiscreteStatistics.variance(toArray(diffusionCoefficients), mean)) / mean;
} else {
return waDiffusionCoefficient/treelength;
}
} else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE) {
return maxDistanceFromRoot;
} else {
return maxDistanceOverTimeFromRoot;
}
}
// private double getNativeDistance(double[] location1, double[] location2) {
// return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0));
private double getNativeDistance(double[] location1, double[] location2) {
int traitDimension = location1.length;
double sum = 0;
for (int i = 0; i < traitDimension; i++) {
sum += Math.pow((location2[i] - location1[i]),2);
}
return Math.sqrt(sum);
}
private double[] toArray(List<Double> list) {
double[] returnArray = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
returnArray[i] = Double.valueOf(list.get(i).toString());
}
return returnArray;
}
private double[] imputeValue(double[] nodeValue, double[] parentValue, double time, double nodeHeight, double parentHeight, double[] precisionArray, double rate, boolean trueNoise) {
final double scaledTimeChild = (time - nodeHeight) * rate;
final double scaledTimeParent = (parentHeight - time) * rate;
final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent;
final int dim = nodeValue.length;
double[][] precision = new double[dim][dim];
int counter = 0;
for (int a = 0; a < dim; a++){
for (int b = 0; b < dim; b++){
precision[a][b] = precisionArray[counter];
counter++ ;
}
}
if (scaledTimeChild == 0)
return nodeValue;
if (scaledTimeParent == 0)
return parentValue;
// Find mean value, weighted average
double[] mean = new double[dim];
double[][] scaledPrecision = new double[dim][dim];
for (int i = 0; i < dim; i++) {
mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal;
if (trueNoise) {
for (int j = i; j < dim; j++)
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal;
}
}
// System.out.print(time+"\t"+nodeHeight+"\t"+parentHeight+"\t"+scaledTimeChild+"\t"+scaledTimeParent+"\t"+scaledWeightTotal+"\t"+mean[0]+"\t"+mean[1]+"\t"+scaledPrecision[0][0]+"\t"+scaledPrecision[0][1]+"\t"+scaledPrecision[1][0]+"\t"+scaledPrecision[1][1]);
if (trueNoise) {
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision);
}
// System.out.println("\t"+mean[0]+"\t"+mean[1]+"\r");
double[] result = new double[dim];
for (int i = 0; i < dim; i++)
result[i] = mean[i];
return result;
}
enum Mode {
AVERAGE,
WEIGHTED_AVERAGE,
MEDIAN,
COEFFICIENT_OF_VARIATION
}
enum summaryStatistic {
DIFFUSION_RATE,
DIFFUSION_COEFFICIENT,
WAVEFRONT_DISTANCE,
WAVEFRONT_RATE,
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return DIFFUSION_RATE_STATISTIC;
}
@Override
public String[] getParserNames() {
return new String[]{getParserName(), TREE_DISPERSION_STATISTIC};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String name = xo.getAttribute(NAME, xo.getId());
boolean option = xo.getAttribute(BOOLEAN_DIS_OPTION, false); // Default value is false
Mode averageMode;
String mode = xo.getAttribute(MODE, WEIGHTED_AVERAGE);
if (mode.equals(AVERAGE)) {
averageMode = Mode.AVERAGE;
} else if (mode.equals(MEDIAN)) {
averageMode = Mode.MEDIAN;
} else if (mode.equals(COEFFICIENT_OF_VARIATION)) {
averageMode = Mode.COEFFICIENT_OF_VARIATION;
} else if (mode.equals(WEIGHTED_AVERAGE)) {
averageMode = Mode.WEIGHTED_AVERAGE;
} else {
System.err.println("Unknown mode: "+mode+". Reverting to weighted average");
averageMode = Mode.WEIGHTED_AVERAGE;
}
// boolean diffCoeff = xo.getAttribute(BOOLEAN_DC_OPTION, false); // Default value is false
summaryStatistic summaryStat;
String statistic = xo.getAttribute(STATISTIC, DIFFUSION_RATE);
if (statistic.equals(DIFFUSION_RATE)) {
summaryStat = summaryStatistic.DIFFUSION_RATE;
} else if (statistic.equals(WAVEFRONT_DISTANCE)) {
summaryStat = summaryStatistic.WAVEFRONT_DISTANCE;
} else if (statistic.equals(WAVEFRONT_RATE)) {
summaryStat = summaryStatistic.WAVEFRONT_RATE;
} else if (statistic.equals(DIFFUSION_COEFFICIENT)) {
summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT;
} else {
System.err.println("Unknown statistic: "+statistic+". Reverting to diffusion rate");
summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT;
}
final double upperHeight = xo.getAttribute(HEIGHT_UPPER, Double.MAX_VALUE);
final double lowerHeight = xo.getAttribute(HEIGHT_LOWER, 0.0);
List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>();
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) {
AbstractMultivariateTraitLikelihood amtl = (AbstractMultivariateTraitLikelihood) xo.getChild(i);
traitLikelihoods.add(amtl);
}
}
return new DiffusionRateStatistic(name, traitLikelihoods, option, averageMode, summaryStat, upperHeight, lowerHeight);
} |
package dr.inference.mcmc;
import dr.inference.loggers.Logger;
import dr.inference.loggers.MCLogger;
import dr.inference.markovchain.MarkovChain;
import dr.inference.markovchain.MarkovChainListener;
import dr.inference.model.Model;
import dr.inference.model.PathLikelihood;
import dr.inference.operators.*;
import dr.inference.prior.Prior;
import dr.util.Identifiable;
import dr.xml.*;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.BetaDistributionImpl;
/**
* @author Andrew Rambaut
* @author Alex Alekseyenko
* @author Marc Suchard
* @author Guy Baele
*/
public class MarginalLikelihoodEstimator implements Runnable, Identifiable {
public MarginalLikelihoodEstimator(String id, int chainLength, int burninLength, int pathSteps, double fixedRunValue,
// boolean linear, boolean lacing,
PathScheme scheme,
PathLikelihood pathLikelihood,
OperatorSchedule schedule,
MCLogger logger) {
this.id = id;
this.chainLength = chainLength;
this.pathSteps = pathSteps;
this.scheme = scheme;
this.schedule = schedule;
this.fixedRunValue = fixedRunValue;
// deprecated
// this.linear = (scheme == PathScheme.LINEAR);
// this.lacing = false; // Was not such a good idea
this.burninLength = burninLength;
MCMCCriterion criterion = new MCMCCriterion();
pathDelta = 1.0 / pathSteps;
pathParameter = 1.0;
this.pathLikelihood = pathLikelihood;
pathLikelihood.setPathParameter(pathParameter);
mc = new MarkovChain(Prior.UNIFORM_PRIOR, pathLikelihood, schedule, criterion, 0, 0, true);
this.logger = logger;
}
private void setDefaultBurnin() {
if (burninLength == -1) {
burnin = (int) (0.1 * chainLength);
} else {
burnin = burninLength;
}
}
public void integrate(Integrator scheme) {
setDefaultBurnin();
mc.setCurrentLength(burnin);
scheme.init();
for (pathParameter = scheme.nextPathParameter(); pathParameter >= 0; pathParameter = scheme.nextPathParameter()) {
pathLikelihood.setPathParameter(pathParameter);
reportIteration(pathParameter, chainLength, burnin, scheme.pathSteps, scheme.step);
for (int i = 0; i < schedule.getOperatorCount(); ++i) {
MCMCOperator operator = schedule.getOperator(i);
if (operator instanceof GibbsOperator) {
((GibbsOperator)operator).setPathParameter(pathParameter);
}
}
long cl = mc.getCurrentLength();
mc.setCurrentLength(0);
mc.runChain(burnin, false);
mc.setCurrentLength(cl);
mc.runChain(chainLength, false);
(new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out);
((CombinedOperatorSchedule) schedule).reset();
}
}
public abstract class Integrator {
protected int step;
protected int pathSteps;
protected Integrator(int pathSteps) {
this.pathSteps = pathSteps;
}
public void init() {
step = 0;
}
abstract double nextPathParameter();
}
public class FixedThetaRun extends Integrator {
private double value;
public FixedThetaRun(double value) {
super(1);
this.value = value;
}
double nextPathParameter() {
if (step == 0) {
step++;
return value;
} else {
return -1.0;
}
}
}
public class LinearIntegrator extends Integrator {
public LinearIntegrator(int pathSteps) {
super(pathSteps);
}
double nextPathParameter() {
if (step > pathSteps) {
return -1;
}
double pathParameter = 1.0 - (double)step / (double)(pathSteps);
step = step + 1;
return pathParameter;
}
}
public class SigmoidIntegrator extends Integrator {
private double alpha;
public SigmoidIntegrator(double alpha, int pathSteps) {
super(pathSteps);
this.alpha = alpha;
}
double nextPathParameter() {
if (step == 0) {
step++;
return 1.0;
} else if (step == pathSteps) {
step++;
return 0.0;
} else if (step > pathSteps) {
return -1.0;
} else {
double xvalue = ((pathSteps - step)/((double)pathSteps)) - 0.5;
step++;
return Math.exp(alpha*xvalue)/(Math.exp(alpha*xvalue) + Math.exp(-alpha*xvalue));
}
}
}
public class BetaQuantileIntegrator extends Integrator {
private double alpha;
public BetaQuantileIntegrator(double alpha, int pathSteps) {
super(pathSteps);
this.alpha = alpha;
}
double nextPathParameter() {
if (step > pathSteps)
return -1;
double result = Math.pow((pathSteps - step)/((double)pathSteps), 1.0/alpha);
step++;
return result;
}
}
public class BetaIntegrator extends Integrator {
private BetaDistributionImpl betaDistribution;
public BetaIntegrator(double alpha, double beta, int pathSteps) {
super(pathSteps);
this.betaDistribution = new BetaDistributionImpl(alpha, beta);
}
double nextPathParameter() {
if (step > pathSteps)
return -1;
if (step == 0) {
step += 1;
return 1.0;
} else if (step + 1 < pathSteps) {
double ratio = (double) step / (double) (pathSteps - 1);
try {
step += 1;
return 1.0 - betaDistribution.inverseCumulativeProbability(ratio);
} catch (MathException e) {
e.printStackTrace();
}
}
step += 1;
return 0.0;
}
}
public class GeometricIntegrator extends Integrator {
public GeometricIntegrator(int pathSteps) {
super(pathSteps);
}
double nextPathParameter() {
if (step > pathSteps) {
return -1;
}
if (step == pathSteps) { //pathSteps instead of pathSteps - 1
step += 1;
return 0;
}
step += 1;
return Math.pow(2, -(step - 1));
}
}
/*public void linearIntegration() {
setDefaultBurnin();
mc.setCurrentLength(0);
for (int step = 0; step < pathSteps; step++) {
pathLikelihood.setPathParameter(pathParameter);
reportIteration(pathParameter, chainLength, burnin);
//mc.runChain(chainLength + burnin, false, 0);
mc.runChain(chainLength + burnin, false);
pathParameter -= pathDelta;
}
pathLikelihood.setPathParameter(0.0);
reportIteration(pathParameter, chainLength, burnin);
//mc.runChain(chainLength + burnin, false, 0);
mc.runChain(chainLength + burnin, false);
}*/
/*public void betaIntegration(double alpha, double beta) {
setDefaultBurnin();
mc.setCurrentLength(0);
BetaDistributionImpl betaDistribution = new BetaDistributionImpl(alpha, beta);
for (int step = 0; step < pathSteps; step++) {
if (step == 0) {
pathParameter = 1.0;
} else if (step + 1 < pathSteps) {
double ratio = (double) step / (double) (pathSteps - 1);
try {
pathParameter = 1.0 - betaDistribution.inverseCumulativeProbability(ratio);
} catch (MathException e) {
e.printStackTrace();
}
} else {
pathParameter = 0.0;
}
pathLikelihood.setPathParameter(pathParameter);
reportIteration(pathParameter, chainLength, burnin);
//mc.runChain(chainLength + burnin, false, 0);
mc.runChain(chainLength + burnin, false);
(new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out);
((CombinedOperatorSchedule) schedule).reset();
}
}*/
private void reportIteration(double pathParameter, long chainLength, long burnin, long totalSteps, long steps) {
System.out.println("Attempting theta ("+steps+"/" + (totalSteps+1) +") = " + pathParameter + " for " + chainLength + " iterations + " + burnin + " burnin.");
}
public void run() {
logger.startLogging();
mc.addMarkovChainListener(chainListener);
switch (scheme) {
case FIXED:
integrate(new FixedThetaRun(fixedRunValue));
break;
case LINEAR:
integrate(new LinearIntegrator(pathSteps));
break;
case GEOMETRIC:
integrate(new GeometricIntegrator(pathSteps));
break;
case ONE_SIDED_BETA:
integrate(new BetaIntegrator(1.0, betaFactor, pathSteps));
break;
case BETA:
integrate(new BetaIntegrator(alphaFactor, betaFactor, pathSteps));
break;
case BETA_QUANTILE:
integrate(new BetaQuantileIntegrator(alphaFactor, pathSteps));
break;
case SIGMOID:
integrate(new SigmoidIntegrator(alphaFactor, pathSteps));
break;
default:
throw new RuntimeException("Illegal path scheme");
}
mc.removeMarkovChainListener(chainListener);
}
private final MarkovChainListener chainListener = new MarkovChainListener() {
// for receiving messages from subordinate MarkovChain
/**
* Called to update the current model keepEvery states.
*/
public void currentState(long state, Model currentModel) {
currentState = state;
if (currentState >= burnin) {
logger.log(state);
}
}
/**
* Called when a new new best posterior state is found.
*/
public void bestState(long state, Model bestModel) {
currentState = state;
}
/**
* cleans up when the chain finishes (possibly early).
*/
public void finished(long chainLength) {
currentState = chainLength;
(new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out);
// logger.log(currentState);
logger.stopLogging();
}
};
/**
* @return the current state of the MCMC analysis.
*/
public boolean getSpawnable() {
return spawnable;
}
private boolean spawnable = true;
public void setSpawnable(boolean spawnable) {
this.spawnable = spawnable;
}
public void setAlphaFactor(double alpha) {
alphaFactor = alpha;
}
public void setBetaFactor(double beta) {
betaFactor = beta;
}
public double getAlphaFactor() {
return alphaFactor;
}
public double getBetaFactor() {
return betaFactor;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MARGINAL_LIKELIHOOD_ESTIMATOR;
}
/**
* @return a tree object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
PathLikelihood pathLikelihood = (PathLikelihood) xo.getChild(PathLikelihood.class);
MCLogger logger = (MCLogger) xo.getChild(MCLogger.class);
int chainLength = xo.getIntegerAttribute(CHAIN_LENGTH);
int pathSteps = xo.getIntegerAttribute(PATH_STEPS);
int burninLength = -1;
if (xo.hasAttribute(BURNIN)) {
burninLength = xo.getIntegerAttribute(BURNIN);
}
int prerunLength = -1;
if (xo.hasAttribute(PRERUN)) {
prerunLength = xo.getIntegerAttribute(PRERUN);
}
double fixedRunValue = -1.0;
if (xo.hasAttribute(FIXED_VALUE)) {
fixedRunValue = xo.getDoubleAttribute(FIXED_VALUE);
}
// deprecated
boolean linear = xo.getAttribute(LINEAR, true);
// boolean lacing = xo.getAttribute(LACING,false);
PathScheme scheme;
if (linear) {
scheme = PathScheme.LINEAR;
} else {
scheme = PathScheme.GEOMETRIC;
}
// new approach
if (xo.hasAttribute(PATH_SCHEME)) { // change to: getAttribute once deprecated approach removed
scheme = PathScheme.parseFromString(xo.getAttribute(PATH_SCHEME, PathScheme.LINEAR.getText()));
}
for (int i = 0; i < xo.getChildCount(); i++) {
Object child = xo.getChild(i);
if (child instanceof Logger) {
}
}
CombinedOperatorSchedule os = new CombinedOperatorSchedule();
XMLObject mcmcXML = xo.getChild(MCMC);
for (int i = 0; i < mcmcXML.getChildCount(); ++i) {
if (mcmcXML.getChild(i) instanceof MCMC) {
MCMC mcmc = (MCMC) mcmcXML.getChild(i);
if (prerunLength > 0) {
java.util.logging.Logger.getLogger("dr.inference").info("Path Sampling Marginal Likelihood Estimator:\n\tEquilibrating chain " + mcmc.getId() + " for " + prerunLength + " iterations.");
for (Logger log : mcmc.getLoggers()) { // Stop the loggers, so nothing gets written to normal output
log.stopLogging();
}
mcmc.getMarkovChain().runChain(prerunLength, false);
}
os.addOperatorSchedule(mcmc.getOperatorSchedule());
}
}
if (os.getScheduleCount() == 0) {
System.err.println("Error: no mcmc objects provided in construction. Bayes Factor estimation will likely fail.");
}
MarginalLikelihoodEstimator mle = new MarginalLikelihoodEstimator(MARGINAL_LIKELIHOOD_ESTIMATOR, chainLength,
burninLength, pathSteps, fixedRunValue, scheme, pathLikelihood, os, logger);
if (!xo.getAttribute(SPAWN, true))
mle.setSpawnable(false);
if (xo.hasAttribute(ALPHA)) {
mle.setAlphaFactor(xo.getAttribute(ALPHA, 0.5));
}
if (xo.hasAttribute(BETA)) {
mle.setBetaFactor(xo.getAttribute(BETA, 0.5));
}
String alphaBetaText = "";
if (scheme == PathScheme.ONE_SIDED_BETA) {
alphaBetaText += "(1," + mle.getBetaFactor() + ")";
} else if (scheme == PathScheme.BETA) {
alphaBetaText += "(" + mle.getAlphaFactor() + "," + mle.getBetaFactor() + ")";
} else if (scheme == PathScheme.BETA_QUANTILE) {
alphaBetaText += "(" + mle.getAlphaFactor() + ")";
} else if (scheme == PathScheme.SIGMOID) {
alphaBetaText += "(" + mle.getAlphaFactor() + ")";
}
java.util.logging.Logger.getLogger("dr.inference").info("\nCreating the Marginal Likelihood Estimator chain:" +
"\n chainLength=" + chainLength +
"\n pathSteps=" + pathSteps +
"\n pathScheme=" + scheme.getText() + alphaBetaText +
"\n If you use these results, please cite:" +
"\n Guy Baele, Philippe Lemey, Trevor Bedford, Andrew Rambaut, Marc A. Suchard, and Alexander V. Alekseyenko." +
"\n 2012. Improving the accuracy of demographic and molecular clock model comparison while accommodating " +
"\n phylogenetic uncertainty. Mol. Biol. Evol. 29(9):2157-2167.");
return mle;
}
/**
* this markov chain does most of the work.
*/
private final MarkovChain mc;
private OperatorSchedule schedule;
private String id = null;
private long currentState;
private final long chainLength;
private long burnin;
private final long burninLength;
private int pathSteps;
// private final boolean linear;
// private final boolean lacing;
private final PathScheme scheme;
private double alphaFactor = 0.5;
private double betaFactor = 0.5;
private double fixedRunValue = -1.0;
private final double pathDelta;
private double pathParameter;
private final MCLogger logger;
private final PathLikelihood pathLikelihood;
public static final String MARGINAL_LIKELIHOOD_ESTIMATOR = "marginalLikelihoodEstimator";
public static final String CHAIN_LENGTH = "chainLength";
public static final String PATH_STEPS = "pathSteps";
public static final String FIXED = "fixed";
public static final String LINEAR = "linear";
public static final String LACING = "lacing";
public static final String SPAWN = "spawn";
public static final String BURNIN = "burnin";
public static final String MCMC = "samplers";
public static final String PATH_SCHEME = "pathScheme";
public static final String FIXED_VALUE = "fixedValue";
public static final String ALPHA = "alpha";
public static final String BETA = "beta";
public static final String PRERUN = "prerun";
} |
package edu.washington.escience.myria.api;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Date;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.joda.time.DateTime;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import edu.washington.escience.myria.CsvTupleWriter;
import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.MyriaConstants;
import edu.washington.escience.myria.TupleWriter;
import edu.washington.escience.myria.parallel.Server;
/**
* Class that handles logs.
*/
@Produces(MediaType.TEXT_PLAIN)
@Path("/logs")
public final class LogResource {
/** The Myria server running on the master. */
@Context
private Server server;
/**
* Get profiling logs of a query.
*
* @param queryId query id.
* @param fragmentId the fragment id.
* @param start the earliest time where we need data
* @param end the latest time
* @param minLength the minimum length of a span to return, default is 0
* @param onlyRootOp the operator to return data for, default is all
* @param request the current request.
* @return the profiling logs of the query across all workers
* @throws DbException if there is an error in the database.
*/
@GET
@Path("profiling")
public Response getProfileLogs(@QueryParam("queryId") final Long queryId,
@QueryParam("fragmentId") final Long fragmentId, @QueryParam("start") final Long start,
@QueryParam("end") final Long end, @DefaultValue("0") @QueryParam("minLength") final Long minLength,
@DefaultValue("false") @QueryParam("onlyRootOp") final boolean onlyRootOp, @Context final Request request)
throws DbException {
Preconditions.checkArgument(queryId != null, "Missing required field queryId.");
Preconditions.checkArgument(fragmentId != null, "Missing required field fragmentId.");
Preconditions.checkArgument(start != null, "Missing required field start.");
Preconditions.checkArgument(end != null, "Missing required field end.");
Preconditions.checkArgument(minLength >= 0, "MinLength has to be greater than or equal to 0");
EntityTag eTag = new EntityTag(Integer.toString(Joiner.on('-').join("profiling", queryId, fragmentId).hashCode()));
Object obj = checkAndAddCache(request, eTag);
if (obj instanceof Response) {
return (Response) obj;
}
ResponseBuilder response = (ResponseBuilder) obj;
response.type(MediaType.TEXT_PLAIN);
PipedOutputStream writerOutput = new PipedOutputStream();
PipedInputStream input;
try {
input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE);
} catch (IOException e) {
throw new DbException(e);
}
PipedStreamingOutput entity = new PipedStreamingOutput(input);
response.entity(entity);
TupleWriter writer = new CsvTupleWriter(writerOutput);
server.startLogDataStream(queryId, fragmentId, start, end, minLength, onlyRootOp, writer);
return response.build();
}
/**
* Get contribution of each operator to runtime.
*
* @param queryId query id.
* @param fragmentId the fragment id, default is all.
* @param request the current request.
* @return the contributions across all workers
* @throws DbException if there is an error in the database.
*/
@GET
@Path("contribution")
public Response getContributions(@QueryParam("queryId") final Long queryId,
@DefaultValue("-1") @QueryParam("fragmentId") final Long fragmentId, @Context final Request request)
throws DbException {
Preconditions.checkArgument(queryId != null, "Missing required field queryId.");
EntityTag eTag =
new EntityTag(Integer.toString(Joiner.on('-').join("contribution", queryId, fragmentId).hashCode()));
Object obj = checkAndAddCache(request, eTag);
if (obj instanceof Response) {
return (Response) obj;
}
ResponseBuilder response = (ResponseBuilder) obj;
response.type(MediaType.TEXT_PLAIN);
PipedOutputStream writerOutput = new PipedOutputStream();
PipedInputStream input;
try {
input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE);
} catch (IOException e) {
throw new DbException(e);
}
PipedStreamingOutput entity = new PipedStreamingOutput(input);
response.entity(entity);
TupleWriter writer = new CsvTupleWriter(writerOutput);
server.startContributionsStream(queryId, fragmentId, writer);
return response.build();
}
/**
* Get information about where tuples were sent.
*
* @param queryId query id.
* @param fragmentId the fragment id. < 0 means all
* @param request the current request.
* @return the profiling logs of the query across all workers
* @throws DbException if there is an error in the database.
*/
@GET
@Path("sent")
public Response getSentLogs(@QueryParam("queryId") final Long queryId,
@DefaultValue("-1") @QueryParam("fragmentId") final long fragmentId, @Context final Request request)
throws DbException {
Preconditions.checkArgument(queryId != null, "Missing required field queryId.");
EntityTag eTag = new EntityTag(Integer.toString(Joiner.on('-').join("sent", queryId, fragmentId).hashCode()));
Object obj = checkAndAddCache(request, eTag);
if (obj instanceof Response) {
return (Response) obj;
}
ResponseBuilder response = (ResponseBuilder) obj;
response.type(MediaType.TEXT_PLAIN);
PipedOutputStream writerOutput = new PipedOutputStream();
PipedInputStream input;
try {
input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE);
} catch (IOException e) {
throw new DbException(e);
}
PipedStreamingOutput entity = new PipedStreamingOutput(input);
response.entity(entity);
TupleWriter writer = new CsvTupleWriter(writerOutput);
server.startSentLogDataStream(queryId, fragmentId, writer);
return response.build();
}
/**
* @param queryId query id.
* @param fragmentId the fragment id.
* @param request the current request.
* @return the range for which we have profiling info
* @throws DbException if there is an error in the database.
*/
@GET
@Path("range")
public Response getRange(@QueryParam("queryId") final Long queryId, @QueryParam("fragmentId") final Long fragmentId,
@Context final Request request) throws DbException {
Preconditions.checkArgument(queryId != null, "Missing required field queryId.");
Preconditions.checkArgument(fragmentId != null, "Missing required field fragmentId.");
EntityTag eTag = new EntityTag(Integer.toString(Joiner.on('-').join("range", queryId, fragmentId).hashCode()));
Object obj = checkAndAddCache(request, eTag);
if (obj instanceof Response) {
return (Response) obj;
}
ResponseBuilder response = (ResponseBuilder) obj;
response.type(MediaType.TEXT_PLAIN);
PipedOutputStream writerOutput = new PipedOutputStream();
PipedInputStream input;
try {
input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE);
} catch (IOException e) {
throw new DbException(e);
}
PipedStreamingOutput entity = new PipedStreamingOutput(input);
response.entity(entity);
TupleWriter writer = new CsvTupleWriter(writerOutput);
server.startRangeDataStream(queryId, fragmentId, writer);
return response.build();
}
/**
* Get the number of workers working on a fragment based on profiling logs of a query for the root operators.
*
* @param queryId query id.
* @param fragmentId the fragment id.
* @param start the start of the range
* @param end the end of the range
* @param step the length of a step
* @param onlyRootOp return histogram for root operator, default is all
* @param request the current request.
* @return the profiling logs of the query across all workers
* @throws DbException if there is an error in the database.
*/
@GET
@Path("histogram")
public Response getHistogram(@QueryParam("queryId") final Long queryId,
@QueryParam("fragmentId") final Long fragmentId, @QueryParam("start") final Long start,
@QueryParam("end") final Long end, @QueryParam("step") final Long step,
@DefaultValue("true") @QueryParam("onlyRootOp") final boolean onlyRootOp, @Context final Request request)
throws DbException {
Preconditions.checkArgument(queryId != null, "Missing required field queryId.");
Preconditions.checkArgument(fragmentId != null, "Missing required field fragmentId.");
Preconditions.checkArgument(start != null, "Missing required field start.");
Preconditions.checkArgument(end != null, "Missing required field end.");
Preconditions.checkArgument(step != null, "Missing required field step.");
EntityTag eTag =
new EntityTag(Integer.toString(Joiner.on('-').join("histogram", queryId, fragmentId, start, end, step,
onlyRootOp).hashCode()));
Object obj = checkAndAddCache(request, eTag);
if (obj instanceof Response) {
return (Response) obj;
}
ResponseBuilder response = (ResponseBuilder) obj;
response.type(MediaType.TEXT_PLAIN);
PipedOutputStream writerOutput = new PipedOutputStream();
PipedInputStream input;
try {
input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE);
} catch (IOException e) {
throw new DbException(e);
}
PipedStreamingOutput entity = new PipedStreamingOutput(input);
response.entity(entity);
TupleWriter writer = new CsvTupleWriter(writerOutput);
server.startHistogramDataStream(queryId, fragmentId, start, end, step, onlyRootOp, writer);
return response.build();
}
/**
* Checks whether the response was cached by the client (checking eTag) and whether it is not too old (checking last
* modified). Returns a {@link Response} if the content is cached and a {@link ResponseBuilder} if not. In the second
* case, the caller needs to add to the builder and then return it.
*
* @param request the request
* @param eTag a unique identifier for the version of the resource to be cached
* @return {@link Response} if the content is cached and a {@link ResponseBuilder} otherwise
*/
private Object checkAndAddCache(final Request request, final EntityTag eTag) {
ResponseBuilder response =
request.evaluatePreconditions(new DateTime().minus(MyriaConstants.PROFILING_CACHE_AGE).toDate(), eTag);
if (response != null) {
return response.build();
}
return Response.ok().tag(eTag).lastModified(new Date());
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.command;
import com.sun.squawk.io.BufferedReader;
import com.sun.squawk.microedition.io.FileConnection;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import org.usfirst.frc330.Beachbot2013Java.commands.MarsRock;
/*
* $Log: AutoSpreadsheet.java,v $
* Revision 1.5 2013-02-18 04:33:24 jross
* delete comment about crashing, fixed crashing
*
* Revision 1.4 2013-02-18 00:41:06 jross
* try to fix crash when MarsRock called twice. needs to be tested
*
* Revision 1.3 2013-02-16 21:49:25 jross
* Made AutoSpreadsheetCommand an interface instead of an absctract class so that implementing classes can be found
*
* Revision 1.2 2013-02-14 03:58:29 jross
* update name of file
*
* Revision 1.1 2013-02-08 04:19:43 jross
* Add AutoSpreadsheet
*
* Revision 1.5 2013-01-30 05:01:13 echan
* Added the AutoSpreadsheetCommandGroup to command
*
* Revision 1.4 2013-01-30 04:24:35 jross
* Add AutoSpreadsheetCommandGroup to let CommandGroups execute in a script
*
* Revision 1.3 2013-01-19 22:16:21 jross
* Fix MarsRock crash
*
* Revision 1.2 2013-01-18 05:27:37 jross
* Move close to finally blocks
*
* Revision 1.1 2013-01-01 19:53:50 jross
* Import code from Beachbot2012JavaBeta Project
*
* Revision 1.6 2012-11-14 05:03:33 jross
* don't add commands if not found. Remove debug statements
*
* Revision 1.5 2012-11-13 04:34:39 jross
* Updates to fix crashes in AutoSpreadsheet. There are still some bugs
*
* Revision 1.4 2012-10-27 02:43:17 jross
* Only read script before execution
*
* Revision 1.3 2012-10-24 03:27:58 jross
* Add third parameter
*
* Revision 1.2 2012-10-21 22:12:18 jross
* Use copy method so that multiple instances of the same command can be used. Fix NPEs
*
* Revision 1.1 2012-10-21 04:02:23 jross
* Read autonomous scripts from csv file
*
*/
/**
*
* @author joe
*/
public class AutoSpreadsheet {
FileConnection file = null;
BufferedReader reader = null;
final String filename = "file:///2013AutoModesJava.csv";
SendableChooser autoChooser;
public AutoSpreadsheet()
{
// System.out.println("begin of AutoSpreadsheet Constructor");
autoChooser = new SendableChooser();
// System.out.println(MarsRock.class.getName());
autoChooser.addDefault("Mars Rock", new MarsRock());
// System.out.println("end of AutoSpreadsheet Constructor");
}
private Hashtable commandTable = new Hashtable();
public void addCommand(Command command)
{
commandTable.put(command.getName().toUpperCase(), command);
}
public void addCommand(AutoSpreadsheetCommandGroup command)
{
commandTable.put(command.getName().toUpperCase(), command);
}
public CommandGroup getSelected() {
if (autoChooser.getSelected() instanceof MarsRock)
{
CommandGroup cg = new CommandGroup();
cg.addSequential(new MarsRock());
return (CommandGroup)cg;
}
else
return buildScript((String)autoChooser.getSelected());
}
public void readScripts()
{
try {
file = (FileConnection) Connector.open(filename, Connector.READ);
reader = new BufferedReader(new InputStreamReader(file.openInputStream()));
String line;
String scriptName = null;
int comma1, comma2;
boolean scriptStarted = false;
while ((line = reader.readLine()) != null)
{
// System.out.println(line);
if (line.toUpperCase().startsWith("SCRIPT_NAME,"))
{
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
scriptName = line.substring(comma1+1,comma2).toUpperCase().trim();
// System.out.println("Found Script: " + scriptName);
scriptStarted = true;
autoChooser.addObject(scriptName, scriptName);
}
else if (line.toUpperCase().startsWith("END_OF_SPREAD_SHEET,"))
{
// System.out.println("End of Spreadsheet");
break;
}
}
SmartDashboard.putData("Autonomous mode", autoChooser);
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
try {
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public CommandGroup buildScript(String scriptToRead)
{
CommandGroup cg = null;
try {
file = (FileConnection) Connector.open(filename, Connector.READ);
reader = new BufferedReader(new InputStreamReader(file.openInputStream()));
String line;
String scriptName = null;
int comma1, comma2;
boolean scriptStarted = false;
String commandName = null;
double timeout, param1, param2, param3;
boolean stop;
boolean sequential;
Command command = null;
//search for specified script name
while ((line = reader.readLine()) != null)
{
// System.out.println(line);
if (line.toUpperCase().startsWith("SCRIPT_NAME,"))
{
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
scriptName = line.substring(comma1+1,comma2).toUpperCase().trim();
// System.out.println("Found Script: " + scriptName);
scriptStarted = true;
if (scriptName.equals(scriptToRead))
{
cg = new CommandGroup(scriptName);
break;
}
}
}
while ((line = reader.readLine()) != null)
{
if (line.toUpperCase().startsWith("END_OF_SPREAD_SHEET,"))
{
if (scriptStarted)
System.err.println("!!!End of Spreadsheet found while " + scriptName + " still open");
else
{
// System.out.println("End of Spreadsheet");
break;
}
}
else if (line.toUpperCase().startsWith("END,"))
{
// System.out.println("End of Script: " + scriptName);
scriptStarted = false;
break;
}
else if (line.startsWith(",")|| line.length() <= 2 )
{
//empty line
}
else
{
if (!scriptStarted)
System.err.println("!!!Command found while Script not open");
else
{
commandName = line.substring(0, line.indexOf(","));
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
if (line.substring(comma1+1).startsWith("S"))
sequential = true;
else
sequential = false;
line = line.substring(comma1+1);
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
timeout = Double.parseDouble(line.substring(comma1+1,comma2).toUpperCase().trim());
}
catch (NumberFormatException ex)
{
timeout = 0;
}
line = line.substring(comma2+1);
if (line.toUpperCase().startsWith("CONTINUE"))
stop = false;
else
stop = true;
// System.out.println("stop: " + stop + " " + line.toUpperCase());
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
param1 = Double.parseDouble(line.substring(comma1+1,comma2).trim());
}
catch (NumberFormatException ex)
{
param1 = 0;
}
comma1 = comma2;
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
param2 = Double.parseDouble(line.substring(comma1+1,comma2).trim());
}
catch (NumberFormatException ex)
{
param2 = 0;
}
comma1 = comma2;
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
param3 = Double.parseDouble(line.substring(comma1+1,comma2).trim());
}
catch (NumberFormatException ex)
{
param3 = 0;
}
command = (Command)commandTable.get(commandName.toUpperCase());
if (command == null)
{
System.err.println("Could not find command: " + commandName);
}
else if (command instanceof AutoSpreadsheetCommand)
{
command = ((AutoSpreadsheetCommand)command).copy();
((AutoSpreadsheetCommand)command).setStopAtEnd(stop);
((AutoSpreadsheetCommand)command).setParam1(param1);
((AutoSpreadsheetCommand)command).setParam2(param2);
((AutoSpreadsheetCommand)command).setParam3(param3);
(command).setTimeout(timeout);
if (sequential)
cg.addSequential(command);
else
cg.addParallel(command);
}
else if (command instanceof AutoSpreadsheetCommandGroup)
{
System.out.println("Found Command Group: " + command.getName());
command = ((AutoSpreadsheetCommandGroup)command).copy();
if (sequential)
cg.addSequential(command);
else
cg.addParallel(command);
}
else
{
System.err.println(commandName + " (" + command.getName() + ") is not instance of AutoSpreadsheetCommand");
}
// System.out.println("Command: " + commandName + " Timeout: " + timeout + " Continue: " + !stop + " Param1: " + param1 + " Param2: " + param2 + " Param3: " + param3);
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
try {
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return cg;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.command;
import com.sun.squawk.io.BufferedReader;
import com.sun.squawk.microedition.io.FileConnection;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import org.usfirst.frc330.Beachbot2013Java.commands.MarsRock;
import org.usfirst.frc330.Beachbot2013Java.commands.Wait;
/*
* $Log: AutoSpreadsheet.java,v $
* Revision 1.7 2013-02-19 11:00:43 jross
* add action item
*
* Revision 1.6 2013-02-19 03:48:07 jross
* rewrite previous history comment to avoid erroneous action item.
*
* Revision 1.5 2013-02-18 04:33:24 jross
* delete comment about crashing, fixed crashing
*
* Revision 1.4 2013-02-18 00:41:06 jross
* try to fix crash when MarsRock called twice. needs to be tested
*
* Revision 1.3 2013-02-16 21:49:25 jross
* Made AutoSpreadsheetCommand an interface instead of an absctract class so that implementing classes can be found
*
* Revision 1.2 2013-02-14 03:58:29 jross
* update name of file
*
* Revision 1.1 2013-02-08 04:19:43 jross
* Add AutoSpreadsheet
*
* Revision 1.5 2013-01-30 05:01:13 echan
* Added the AutoSpreadsheetCommandGroup to command
*
* Revision 1.4 2013-01-30 04:24:35 jross
* Add AutoSpreadsheetCommandGroup to let CommandGroups execute in a script
*
* Revision 1.3 2013-01-19 22:16:21 jross
* Fix MarsRock crash
*
* Revision 1.2 2013-01-18 05:27:37 jross
* Move close to finally blocks
*
* Revision 1.1 2013-01-01 19:53:50 jross
* Import code from Beachbot2012JavaBeta Project
*
* Revision 1.6 2012-11-14 05:03:33 jross
* don't add commands if not found. Remove debug statements
*
* Revision 1.5 2012-11-13 04:34:39 jross
* Updates to fix crashes in AutoSpreadsheet. There are still some bugs
*
* Revision 1.4 2012-10-27 02:43:17 jross
* Only read script before execution
*
* Revision 1.3 2012-10-24 03:27:58 jross
* Add third parameter
*
* Revision 1.2 2012-10-21 22:12:18 jross
* Use copy method so that multiple instances of the same command can be used. Fix NPEs
*
* Revision 1.1 2012-10-21 04:02:23 jross
* Read autonomous scripts from csv file
*
*/
/**
*
* @author joe
*/
public class AutoSpreadsheet {
FileConnection file = null;
BufferedReader reader = null;
final String filename = "file:///2013AutoModesJava.csv";
SendableChooser autoChooser;
public AutoSpreadsheet()
{
// System.out.println("begin of AutoSpreadsheet Constructor");
autoChooser = new SendableChooser();
// System.out.println(MarsRock.class.getName());
autoChooser.addDefault("Mars Rock", new MarsRock());
// System.out.println("end of AutoSpreadsheet Constructor");
}
private Hashtable commandTable = new Hashtable();
public void addCommand(Command command)
{
commandTable.put(command.getName().toUpperCase(), command);
}
public void addCommand(AutoSpreadsheetCommandGroup command)
{
commandTable.put(command.getName().toUpperCase(), command);
}
public CommandGroup getSelected() {
if (autoChooser.getSelected() instanceof MarsRock)
{
CommandGroup cg = new CommandGroup();
cg.addSequential(new MarsRock());
return (CommandGroup)cg;
}
else
return buildScript((String)autoChooser.getSelected());
}
public void readScripts()
{
try {
file = (FileConnection) Connector.open(filename, Connector.READ);
reader = new BufferedReader(new InputStreamReader(file.openInputStream()));
String line;
String scriptName = null;
int comma1, comma2;
boolean scriptStarted = false;
while ((line = reader.readLine()) != null)
{
// System.out.println(line);
if (line.toUpperCase().startsWith("SCRIPT_NAME,"))
{
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
scriptName = line.substring(comma1+1,comma2).toUpperCase().trim();
// System.out.println("Found Script: " + scriptName);
scriptStarted = true;
autoChooser.addObject(scriptName, scriptName);
}
else if (line.toUpperCase().startsWith("END_OF_SPREAD_SHEET,"))
{
// System.out.println("End of Spreadsheet");
break;
}
}
SmartDashboard.putData("Autonomous mode", autoChooser);
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
try {
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public CommandGroup buildScript(String scriptToRead)
{
CommandGroup cg = null;
try {
file = (FileConnection) Connector.open(filename, Connector.READ);
reader = new BufferedReader(new InputStreamReader(file.openInputStream()));
String line;
String scriptName = null;
int comma1, comma2;
boolean scriptStarted = false;
String commandName = null;
double timeout, param1, param2, param3;
boolean stop;
boolean sequential;
Command command = null;
//search for specified script name
while ((line = reader.readLine()) != null)
{
// System.out.println(line);
if (line.toUpperCase().startsWith("SCRIPT_NAME,"))
{
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
scriptName = line.substring(comma1+1,comma2).toUpperCase().trim();
// System.out.println("Found Script: " + scriptName);
scriptStarted = true;
if (scriptName.equals(scriptToRead))
{
cg = new CommandGroup(scriptName);
break;
}
}
}
while ((line = reader.readLine()) != null)
{
if (line.toUpperCase().startsWith("END_OF_SPREAD_SHEET,"))
{
if (scriptStarted)
System.err.println("!!!End of Spreadsheet found while " + scriptName + " still open");
else
{
// System.out.println("End of Spreadsheet");
break;
}
}
else if (line.toUpperCase().startsWith("END,"))
{
// System.out.println("End of Script: " + scriptName);
scriptStarted = false;
cg.addSequential(new Wait(15));
break;
}
else if (line.startsWith(",")|| line.length() <= 2 )
{
//empty line
}
else
{
if (!scriptStarted)
System.err.println("!!!Command found while Script not open");
else
{
commandName = line.substring(0, line.indexOf(","));
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
if (line.substring(comma1+1).startsWith("S"))
sequential = true;
else
sequential = false;
line = line.substring(comma1+1);
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
timeout = Double.parseDouble(line.substring(comma1+1,comma2).toUpperCase().trim());
}
catch (NumberFormatException ex)
{
timeout = 0;
}
line = line.substring(comma2+1);
if (line.toUpperCase().startsWith("CONTINUE"))
stop = false;
else
stop = true;
// System.out.println("stop: " + stop + " " + line.toUpperCase());
comma1 = line.indexOf(",");
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
param1 = Double.parseDouble(line.substring(comma1+1,comma2).trim());
}
catch (NumberFormatException ex)
{
param1 = 0;
}
comma1 = comma2;
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
param2 = Double.parseDouble(line.substring(comma1+1,comma2).trim());
}
catch (NumberFormatException ex)
{
param2 = 0;
}
comma1 = comma2;
comma2 = line.substring(comma1+1).indexOf(",")+comma1+1;
try
{
param3 = Double.parseDouble(line.substring(comma1+1,comma2).trim());
}
catch (NumberFormatException ex)
{
param3 = 0;
}
command = (Command)commandTable.get(commandName.toUpperCase());
if (command == null)
{
System.err.println("Could not find command: " + commandName);
}
else if (command instanceof AutoSpreadsheetCommand)
{
command = ((AutoSpreadsheetCommand)command).copy();
((AutoSpreadsheetCommand)command).setStopAtEnd(stop);
((AutoSpreadsheetCommand)command).setParam1(param1);
((AutoSpreadsheetCommand)command).setParam2(param2);
((AutoSpreadsheetCommand)command).setParam3(param3);
(command).setTimeout(timeout);
if (sequential)
cg.addSequential(command);
else
cg.addParallel(command);
}
else if (command instanceof AutoSpreadsheetCommandGroup)
{
System.out.println("Found Command Group: " + command.getName());
command = ((AutoSpreadsheetCommandGroup)command).copy();
if (sequential)
cg.addSequential(command);
else
cg.addParallel(command);
}
else
{
System.err.println(commandName + " (" + command.getName() + ") is not instance of AutoSpreadsheetCommand");
}
// System.out.println("Command: " + commandName + " Timeout: " + timeout + " Continue: " + !stop + " Param1: " + param1 + " Param2: " + param2 + " Param3: " + param3);
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
try {
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return cg;
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.interfaces.Potentiometer;
public class RobotTemplate extends SimpleRobot {
JoyStickCustom driveStick;
JoyStickCustom secondStick;
Talon frontLeft;
Talon rearLeft;
Talon frontRight;
Talon rearRight;
Talon winch;
Compressor compress;
RobotDrive mainDrive;
final double DEADZONE=.08;
Solenoid pistup;
Solenoid pistdown;
Solenoid winchEng;
Solenoid winchDis;
Pneumatics armJoint;
Pneumatics handJoint;
Pneumatics winchP;
Encoder winchStop;
Potentiometer armStop;
Potentiometer handStop;
//Counter for teleOp loops
int count=0;
public void robotInit(){
driveStick= new JoyStickCustom(1, DEADZONE);
secondStick=new JoyStickCustom(2, DEADZONE);
frontLeft= new Talon(1);
rearLeft= new Talon(2);
frontRight= new Talon(3);
rearRight= new Talon(4);
winch = new Talon(5);
mainDrive=new RobotDrive(frontLeft,rearLeft,frontRight,rearRight);
compress=new Compressor(1,1);
pistup=new Solenoid(1);
pistdown=new Solenoid(2);
armJoint=new Pneumatics(1,2);
winchP=new Pneumatics(3,4);
}
public void autonomous() {
}
public void operatorControl() {
while(isOperatorControl()&&isEnabled()){
driveStick.update();
secondStick.update();
compress.start();
//Cartesian Drive with Deadzones and Turning
mainDrive.mecanumDrive_Cartesian(
driveStick.getDeadAxisX(),
driveStick.getDeadAxisY(),
driveStick.getDeadTwist(),0);
moveArm();
//logger
/*if(count%500==0){System.out.println(count+": "+
frontLeft.getSpeed()+", "+
rearLeft.getSpeed()+", "+
frontRight.getSpeed()+", "+
rearRight.getSpeed());
}*/
//Increase number of teleop cycles
count++;
}
}
public void moveArm(){
if (secondStick.getDeadAxisX()>.5) {
/*pistup.set(true);
pistdown.set(false);*/
armJoint.up();
}
else if (secondStick.getDeadAxisX()<-.5) {
/*pistdown.set(true);
pistup.set(false);*/
armJoint.down();
}
else {
/*pistdown.set(false);
pistup.set(false); */
armJoint.stay();
}
}
public void moveHand(){
if (secondStick.getButtonPressed(3)&&!secondStick.getButtonPressed(2)) {
/*pistup.set(true);
pistdown.set(false);*/
handJoint.up();
}
else if (!secondStick.getButtonPressed(3)&&secondStick.getButtonPressed(2)) {
/*pistdown.set(true);
pistup.set(false);*/
handJoint.down();
}
else {
/*pistdown.set(false);
pistup.set(false); */
handJoint.stay();
}
}
public void winch(){
if(secondStick.getButtonReleased(5)){
winch.set(.30);
}
}
public void disabled(){
mainDrive.mecanumDrive_Cartesian(0, 0, 0, 0);
armJoint.stay();
pistup.set(false);
pistdown.set(false);
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Talon;
//Camera shit
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.image.BinaryImage;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.CriteriaCollection;
import edu.wpi.first.wpilibj.image.NIVision.MeasurementType;
import edu.wpi.first.wpilibj.image.NIVisionException;
import edu.wpi.first.wpilibj.image.ParticleAnalysisReport;
import edu.wpi.first.wpilibj.image.RGBImage;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Team1482Robot extends IterativeRobot {
//initialize loop counters
int m_disabledPeriodicLoops;
int m_autoPeriodicLoops;
int m_telePeriodicLoops;
int m_teleContinuousLoops;
int m_dsPacketsReceivedInCurrentSecond;
boolean m_liftstate;
boolean m_grabstate;
boolean m_anglestate;
//Set up Talons to do whatever (uncomment as needed)
Talon drive_left = new Talon(1);
Talon drive_right = new Talon(2);
//Talon pwm3_motor = new Talon(3);
//Talon pwm4_motor = new Talon(4);
//Talon pwm5_motor = new Talon(5);
//Talon pwm6_motor = new Talon(6);
//Set up 2 motor drive
RobotDrive drive = new RobotDrive(drive_left, drive_right);
//Set up 4 motor drive (uncomment as needed)
//RobotDrive drive = new Robotdrive(drive_left, drive_backleft, drive_right, drive_backright);
//Set up joystick
Joystick drivestick = new Joystick(1);
Joystick shootstick = new Joystick(2);
public static int NUM_JOYSTICK_BUTTONS = 16;
//Declare joystick buttons
boolean[] m_driveStickButtonState = new boolean[(NUM_JOYSTICK_BUTTONS+1)];
boolean[] m_shootStickButtonState = new boolean[(NUM_JOYSTICK_BUTTONS+1)];
String m_button_1;
//Set up air compressor and Solenoids
Compressor airCompressor = new Compressor(1,1);
Solenoid lift = new Solenoid(1);
Solenoid liftreset = new Solenoid(2);
Solenoid drop = new Solenoid(3);
Solenoid dropreset = new Solenoid(4);
Solenoid grab = new Solenoid(5);
Solenoid grabreset = new Solenoid(6);
Solenoid angle = new Solenoid(7);
Solenoid anglereset = new Solenoid(7);
//Set up camera
AxisCamera camera;
CriteriaCollection cc;
public Team1482Robot() {
System.out.println("BuiltinDefaultCode Constructor Started\n");
int buttonNum = 1;
for (buttonNum = 1; buttonNum <= NUM_JOYSTICK_BUTTONS; buttonNum++) {
m_driveStickButtonState[buttonNum] = false;
m_shootStickButtonState[buttonNum] = false;
}
}
/**
* This function is called once when entering autonomous
*/
public void autonomousInit() {
System.out.println("Autonomous started");
m_autoPeriodicLoops = 0; //resets loop counter on entering auto
getWatchdog().setEnabled(false);
getWatchdog().setExpiration(0.5);
//Set up lift pistons
lift.set(false);
liftreset.set(true);
m_liftstate = false;
//set up the garb pistons
grab.set(false);
grabreset.set(true);
m_grabstate = false;
//set the angle piston
angle.set(false);
anglereset.set(true);
m_anglestate = false;
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
// insert code here
}
/**
* This function is called once when entering teleop
*/
public void teleopInit() {
System.out.println("Starting Teleop");
m_telePeriodicLoops = 0;
m_teleContinuousLoops = 0; //resets loop counters on entering tele
getWatchdog().setEnabled(true);
getWatchdog().setExpiration(0.05);
airCompressor.start(); //start compressor
//Set up lift pistons
lift.set(false);
liftreset.set(true);
m_liftstate = false;
//set up the garb pistons
grab.set(false);
grabreset.set(true);
m_grabstate = true;
//set the angle piston
angle.set(false);
anglereset.set(true);
m_anglestate = false;
}
/**
* This function is called periodically during teleop
*/
public void teleopPeriodic() {
m_telePeriodicLoops++;
SmartDashboard.putBoolean("Grab state", m_grabstate);
SmartDashboard.putBoolean("Lift state", m_liftstate);
SmartDashboard.putBoolean("Angle State", m_anglestate);
SmartDashboard.putNumber("Teleop loops Continous", m_teleContinuousLoops);
SmartDashboard.putNumber("Teleop loops perodic", m_autoPeriodicLoops);
}
/**
* This function runs continuously during teleop
*/
public void teleopContinuous() {
if (isEnabled()) {
m_teleContinuousLoops++;
double drivestick_x = drivestick.getRawAxis(1);
double drivestick_y = drivestick.getRawAxis(2); //Axis values assuming XBox 360 controller
drive.arcadeDrive(drivestick_y, drivestick_x);
//Check button values (uncomment as needed)
//boolean drivestick_1 = drivestick.getRawButton(1);
//boolean drivestick_2 = drivestick.getRawButton(2);
//boolean drivestick_3 = drivestick.getRawButton(3);
//boolean drivestick_4 = drivestick.getRawButton(4); //etc etc
m_button_1 = ButtonToggle(shootstick, m_shootStickButtonState, 1);
if (m_button_1 == "pressed") {
System.out.println("Button 1 just pressed");
//When pressed
//If retracted extend
if (m_liftstate == false) {
lift.set(true);
liftreset.set(false);
m_liftstate = true;
} //If is not retracted retract
else {
lift.set(false);
liftreset.set(true);
m_liftstate = false;
}
}
getWatchdog().feed();
Timer.delay(0.005);
} else {
Timer.delay(0.01);
getWatchdog().feed();
}
} |
package com.civilizer.extra.tools;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
//import java.awt.event.MouseAdapter;
//import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
//import javax.swing.ImageIcon;
//import javax.swing.JMenuItem;
//import javax.swing.JPopupMenu;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import com.civilizer.config.Configurator;
import com.civilizer.utils.FsUtil;
public final class Launcher {
private static final String PORT = "civilizer.port";
private static final String STATUS = "civilizer.status";
private static final String BROWSE_AT_STARTUP = "civilizer.browse_at_startup";
private static final String STARTING = "Starting Civilizer...";
private static final String RUNNING = "Civilizer is running...";
private static Font fontForIcon;
private final Server server;
private final int port;
private enum LogType {
INFO,
WARN,
ERROR,
}
public static void main(String[] args) {
try {
System.setProperty(STATUS, STARTING);
System.setProperty(PORT, "");
setupSystemTray();
int port = 8080;
Arrays.sort(args);
final int iii = Arrays.binarySearch(args, "--port");
if (-1 < iii && iii < args.length-1) {
try {
port = Integer.parseInt(args[iii + 1]);
if (port <= 0)
throw new NumberFormatException();
} catch (NumberFormatException e) {
l(LogType.ERROR, "'" + port + "' is not a valid port number. exiting...");
System.exit(1);
}
}
new Launcher(port).startServer();
} catch (Exception e) {
l(LogType.ERROR, "An unhandled exception triggered. exiting...");
e.printStackTrace();
System.exit(1);
}
}
private static String getCvzUrl() {
final String portStr = System.getProperty(PORT);
assert portStr.isEmpty() == false;
int port = 0;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
throw new Error(e);
}
return "http://localhost:" + port + "/civilizer/app/home";
}
private static String getFullJarPath(final Pattern pattern){
for(final String element : System.getProperty("java.class.path", ".").split("[:;]")){
if (pattern.matcher(element).matches())
return element;
}
return null;
}
private static String getResourcePathFromJarFile(final File file, final Pattern pattern){
try (ZipFile zf = new ZipFile(file);){
final Enumeration<?> e = zf.entries();
while(e.hasMoreElements()){
final ZipEntry ze = (ZipEntry) e.nextElement();
final String fileName = ze.getName();
if(pattern.matcher(fileName).matches())
return fileName;
}
} catch(final IOException e){
e.printStackTrace();
throw new Error(e);
}
return "";
}
private static Font createFont() {
final String tgtJarPath = getFullJarPath(Pattern.compile(".*primefaces.*\\.jar"));
final String fontPath = getResourcePathFromJarFile(new File(tgtJarPath), Pattern.compile(".*/fontawesome-webfont\\.ttf"));
assert fontPath.isEmpty() == false;
final InputStream is = Launcher.class.getClassLoader().getResourceAsStream(fontPath);
assert is != null;
Font font;
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
throw new Error(e);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
return font.deriveFont(Font.PLAIN, 24f);
}
private static Point calcDrawPoint(Font font, String icon, int size, Graphics2D graphics) {
int center = size / 2; // Center X and Center Y are the same
Rectangle stringBounds = graphics.getFontMetrics().getStringBounds(icon, graphics).getBounds();
Rectangle visualBounds = font.createGlyphVector(graphics.getFontRenderContext(), icon).getVisualBounds().getBounds();
return new Point(center - stringBounds.width / 2, center - visualBounds.height / 2 - visualBounds.y);
}
private static Image createFontIcon(Font font, String code, Color clr) {
final int iconSize = 24;
final BufferedImage img = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setColor(clr);
graphics.setFont(font);
final String icon = code;
final Point pt = calcDrawPoint(font, icon, iconSize, graphics);
graphics.drawString(icon, pt.x, pt.y);
graphics.dispose();
return img;
}
private static boolean systemTraySupported() {
// [Note] Java's standard system tray is not well supported on some of Linux systems;
// (at least, on Linux Mint as of 2015/09/20)
// So we don't display the system tray icon on Linux (for now).
return (SystemTray.isSupported() && !System.getProperty("os.name").toLowerCase().contains("linux"));
}
private static void setupSystemTray() {
if (systemTraySupported() == false)
return;
fontForIcon = createFont();
final Image img = createFontIcon(fontForIcon, "\uf19c", new Color(0xff, 0x0, 0x0));
EventQueue.invokeLater(
new Runnable() {
public void run() {
final SystemTray tray = SystemTray.getSystemTray();
assert tray != null;
assert img != null;
// final TrayIcon trayIcon = new TrayIcon(img, STARTING, null);
// trayIcon.setImageAutoSize(true);
// final JPopupMenu jpopup = new JPopupMenu();
// JMenuItem javaCupMI = new JMenuItem("Example", new ImageIcon("javacup.gif"));
// jpopup.add(javaCupMI);
// jpopup.addSeparator();
// JMenuItem exitMI = new JMenuItem("Exit");
// jpopup.add(exitMI);
// trayIcon.addMouseListener(new MouseAdapter() {
// public void mouseReleased(MouseEvent e) {
// if (e.getButton() == MouseEvent.BUTTON1) {
// jpopup.setLocation(e.getX(), e.getY());
// jpopup.setInvoker(null);
// jpopup.setVisible(true);
PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(img, STARTING, popup);
trayIcon.setImageAutoSize(true);
MenuItem item;
item = new MenuItem("Shutdown");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
});
popup.add(item);
try {
tray.add(trayIcon);
trayIcon.displayMessage("Staring Civilizer...", "Please wait...", MessageType.INFO);
} catch (AWTException e) {
e.printStackTrace();
throw new Error(e);
}
}
}
); // EventQueue.invokeLater()
}
private static void updateSystemTray() {
if (systemTraySupported() == false)
return;
// We change appearance of the system tray icon to notify that the server is ready.
// Also add extra menus.
for (TrayIcon icon : SystemTray.getSystemTray().getTrayIcons()) {
if (icon.getToolTip().equals(STARTING)) {
assert fontForIcon != null;
final Image img = createFontIcon(fontForIcon, "\uf19c", new Color(0xf0, 0xff, 0xff));
icon.setImage(img);
icon.setToolTip(RUNNING);
MenuItem item = new MenuItem("Browse");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser();
}
});
icon.getPopupMenu().insert(item, 0);
icon.displayMessage(null, "Civilizer is ready...", MessageType.NONE);
break;
}
}
}
private static void openBrowser() {
if (System.getProperty(PORT).isEmpty() || ! System.getProperty(STATUS).equals(RUNNING))
return;
final String url = getCvzUrl();
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
private static void l(LogType type, String msg) {
System.out.println(MessageFormat.format("{0} : [{1}] {2}", Launcher.class.getSimpleName(), type.toString(), msg));
}
private Launcher(int port) {
assert 0 < port && port <= 0xffff;
server = new Server(port);
assert server != null;
this.port = port;
}
private boolean setupWebAppContextForDevelopment(WebAppContext waCtxt) {
if (!FsUtil.exists("pom.xml"))
return false;
final String webAppDir = FsUtil.concatPath("src", "main", "webapp");
final String tgtDir = "target";
final String webXmlFile = FsUtil.concatPath(webAppDir, "WEB-INF", "web.xml");
if (!FsUtil.exists(webAppDir) || !FsUtil.exists(tgtDir) || !FsUtil.exists(webXmlFile))
return false;
waCtxt.setBaseResource(new ResourceCollection(
new String[] { webAppDir, tgtDir }
));
waCtxt.setResourceAlias("/WEB-INF/classes/", "/classes/");
waCtxt.setDescriptor(webXmlFile);
l(LogType.INFO, "Running under the development environment...");
return true;
}
private boolean setupWebAppContextForProduction(WebAppContext waCtxt) {
final File usrDir = new File(System.getProperty("user.dir"));
final File[] pkgs = usrDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return (pathname.isDirectory() && pathname.getName().startsWith("civilizer"));
}
});
for (File pkg : pkgs) {
final String pkgPath = pkg.getAbsolutePath();
if (FsUtil.exists(pkgPath, "WEB-INF", "web.xml") == false
|| FsUtil.exists(pkgPath, "WEB-INF", "classes") == false
|| FsUtil.exists(pkgPath, "WEB-INF", "lib") == false
)
continue;
waCtxt.setWar(pkgPath);
return true;
}
return false;
}
private WebAppContext setupWebAppContext() {
final WebAppContext waCtxt = new WebAppContext();
waCtxt.setContextPath("/civilizer");
if (! setupWebAppContextForProduction(waCtxt))
if (! setupWebAppContextForDevelopment(waCtxt))
return null;
return waCtxt;
}
private void startServer() throws Exception {
assert server != null;
final WebAppContext waCtxt = setupWebAppContext();
assert waCtxt != null;
server.setHandler(waCtxt);
server.setStopAtShutdown(true);
server.start();
System.setProperty(STATUS, RUNNING);
System.setProperty(PORT, new Integer(port).toString());
assert System.getProperty(PORT).equals(new Integer(port).toString());
l(LogType.INFO, "Civilizer is running... access to " + getCvzUrl());
updateSystemTray();
if (Configurator.isTrue(BROWSE_AT_STARTUP)) {
openBrowser();
}
server.join();
}
} |
package gestock.resources.views.components;
import javax.swing.table.DefaultTableModel;
import java.util.Date;
public class TableModel extends DefaultTableModel {
public TableModel(String[] columnNames){
super(new Object[0][3],columnNames);
}
public Class<?> getColumnClass(int columnIndex) {
if(columnIndex == 1){
return Integer.class;
} else {
if (columnIndex == 3){
return Date.class;
} else {return String.class;}
}
}
} |
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot.clause;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import com.samskivert.jdbc.depot.Query;
import com.samskivert.jdbc.depot.expression.ColumnExp;
import com.samskivert.jdbc.depot.expression.SQLExpression;
/**
* Represents an ORDER BY clause.
*/
public class OrderBy
implements QueryClause
{
/** Indicates the order of the clause. */
public enum Order { ASC, DESC };
/**
* Creates and returns an ascending order by clause on the supplied column.
*/
public static OrderBy ascending (String column)
{
return ascending(new ColumnExp(null, column));
}
/**
* Creates and returns a descending order by clause on the supplied column.
*/
public static OrderBy descending (String column)
{
return descending(new ColumnExp(null, column));
}
/**
* Creates and returns an ascending order by clause on the supplied expression.
*/
public static OrderBy ascending (SQLExpression value)
{
return new OrderBy(new SQLExpression[] { value } , new Order[] { Order.ASC });
}
/**
* Creates and returns a descending order by clause on the supplied expression.
*/
public static OrderBy descending (SQLExpression value)
{
return new OrderBy(new SQLExpression[] { value }, new Order[] { Order.DESC });
}
public OrderBy (SQLExpression[] values, Order[] orders)
{
_values = values;
_orders = orders;
}
// from QueryClause
public Collection<Class> getClassSet ()
{
return null;
}
// from QueryClause
public void appendClause (Query query, StringBuilder builder)
{
builder.append(" order by ");
for (int ii = 0; ii < _values.length; ii++) {
if (ii > 0) {
builder.append(", ");
}
_values[ii].appendExpression(query, builder);
builder.append(" ").append(_orders[ii]);
}
}
// from QueryClause
public int bindArguments (PreparedStatement pstmt, int argIdx)
throws SQLException
{
for (int ii = 0; ii < _values.length; ii++) {
argIdx = _values[ii].bindArguments(pstmt, argIdx);
}
return argIdx;
}
/** The expressions that are generated for the clause. */
protected SQLExpression[] _values;
/** Whether the ordering is to be ascending or descending. */
protected Order[] _orders;
} |
package org.jsmpp.examples;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.PropertyConfigurator;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUStringException;
import org.jsmpp.bean.Alphabet;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.GeneralDataCoding;
import org.jsmpp.bean.MessageClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.session.SMPPSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author uudashr
*
*/
public class StressClient implements Runnable {
private static final String DEFAULT_PASSWORD = "jpwd";
private static final String DEFAULT_SYSID = "j";
private static final String DEFAULT_DESTADDR = "62161616";
private static final String DEFAULT_SOURCEADDR = "1616";
private static final Logger logger = LoggerFactory.getLogger(StressClient.class);
private static final String DEFAULT_LOG4J_PATH = "stress/client-log4j.properties";
private static final String DEFAULT_HOST = "localhost";
private static final Integer DEFAULT_PORT = 8056;
private static final Integer DEFAULT_BULK_SIZE = 100000;
private static final Integer DEFAULT_PROCESSOR_DEGREE = 3;
private static final Integer DEFAULT_MAX_OUTSTANDING = 1000;
private AtomicInteger requestCounter = new AtomicInteger();
private AtomicInteger totalRequestCounter = new AtomicInteger();
private AtomicInteger responseCounter = new AtomicInteger();
private AtomicInteger totalResponseCounter = new AtomicInteger();
private ExecutorService execService;
private String host;
private int port;
private int bulkSize;
private SMPPSession smppSession = new SMPPSession();
private AtomicBoolean exit = new AtomicBoolean();
private int id;
private String systemId;
private String password;
private String sourceAddr;
private String destinationAddr;
public StressClient(int id, String host, int port, int bulkSize,
String systemId, String password, String sourceAddr,
String destinationAddr, int pduProcessorDegree, int maxOutstanding) {
this.id = id;
this.host = host;
this.port = port;
this.bulkSize = bulkSize;
this.systemId = systemId;
this.password = password;
this.sourceAddr = sourceAddr;
this.destinationAddr = destinationAddr;
smppSession.setPduProcessorDegree(pduProcessorDegree);
execService = Executors.newFixedThreadPool(maxOutstanding);
}
private void shutdown() {
execService.shutdown();
exit.set(true);
}
public void run() {
try {
smppSession.connectAndBind(host, port, BindType.BIND_TRX, systemId,
password, "cln", TypeOfNumber.UNKNOWN,
NumberingPlanIndicator.UNKNOWN, null);
logger.info("Bound to " + host + ":" + port);
} catch (IOException e) {
logger.error("Failed initialize connection or bind", e);
return;
}
new TrafficWatcherThread().start();
logger.info("Starting send " + bulkSize + " bulk message...");
for (int i = 0; i < bulkSize && !exit.get(); i++) {
//execService.execute(newSendTask("Hello " + id + " idx=" + i));
newSendTask("Hello " + id + " idx=" + i).run();
}
while (!exit.get()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
logger.info("Done");
smppSession.unbindAndClose();
}
private Runnable newSendTask(final String message) {
return new Runnable() {
public void run() {
try {
requestCounter.incrementAndGet();
smppSession.submitShortMessage(null, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, sourceAddr,
TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, destinationAddr,
new ESMClass(), (byte)0, (byte)0,
null, null, new RegisteredDelivery(0),
(byte)0,
new GeneralDataCoding(true, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT),
(byte)0, message.getBytes());
responseCounter.incrementAndGet();
} catch (PDUStringException e) {
logger.error("Failed submit short message '" + message + "'", e);
shutdown();
} catch (ResponseTimeoutException e) {
logger.error("Failed submit short message '" + message + "'", e);
shutdown();
} catch (InvalidResponseException e) {
logger.error("Failed submit short message '" + message + "'", e);
shutdown();
} catch (NegativeResponseException e) {
logger.error("Failed submit short message '" + message + "'", e);
shutdown();
} catch (IOException e) {
logger.error("Failed submit short message '" + message + "'", e);
shutdown();
}
}
};
}
private class TrafficWatcherThread extends Thread {
@Override
public void run() {
logger.info("Starting traffic watcher...");
while (!exit.get()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
int requestPerSecond = requestCounter.getAndSet(0);
int responsePerSecond = responseCounter.getAndSet(0);
totalRequestCounter.addAndGet(requestPerSecond);
int total = totalResponseCounter.addAndGet(responsePerSecond);
logger.info("Request/Response per second : " + requestPerSecond + "/" + responsePerSecond + " of " + total);
if (total == bulkSize) {
shutdown();
}
}
}
}
public static void main(String[] args) {
String host = System.getProperty("jsmpp.client.host", DEFAULT_HOST);
String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID);
String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD);
String sourceAddr = System.getProperty("jsmpp.client.sourceAddr", DEFAULT_SOURCEADDR);
String destinationAddr = System.getProperty("jsmpp.client.destinationAddr", DEFAULT_DESTADDR);
int port;
try {
port = Integer.parseInt(System.getProperty("jsmpp.client.port", DEFAULT_PORT.toString()));
} catch (NumberFormatException e) {
port = DEFAULT_PORT;
}
int bulkSize;
try {
bulkSize = Integer.parseInt(System.getProperty("jsmpp.client.bulksize", DEFAULT_BULK_SIZE.toString()));
} catch (NumberFormatException e) {
bulkSize = DEFAULT_BULK_SIZE;
}
int processorDegree;
try {
processorDegree = Integer.parseInt(System.getProperty("jsmpp.client.procdegree", DEFAULT_PROCESSOR_DEGREE.toString()));
} catch (NumberFormatException e) {
processorDegree = DEFAULT_PROCESSOR_DEGREE;
}
int maxOutstanding;
try {
maxOutstanding = Integer.parseInt(System.getProperty("jsmpp.client.maxoutstanding", DEFAULT_MAX_OUTSTANDING.toString()));
} catch (NumberFormatException e) {
maxOutstanding = DEFAULT_MAX_OUTSTANDING;
}
String log4jPath = System.getProperty("jsmpp.log4j.path", DEFAULT_LOG4J_PATH);
PropertyConfigurator.configure(log4jPath);
logger.info("Target server {}:{}", host, port);
logger.info("System ID: {}", systemId);
logger.info("Password: {}", password);
logger.info("Source address: " + sourceAddr);
logger.info("Destination address: " + destinationAddr);
logger.info("Bulk size: {}", bulkSize);
logger.info("Max outstanding: {}", maxOutstanding);
logger.info("Processor degree: {}", processorDegree);
StressClient stressClient = new StressClient(0, host, port, bulkSize,
systemId, password, sourceAddr, destinationAddr,
processorDegree, maxOutstanding);
stressClient.run();
}
} |
package io.compgen.ngsutils.tabix;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import io.compgen.ngsutils.tabix.BGZFile.BGZBlock;
public class BGZInputStream extends InputStream {
protected BGZFile bgzf;
protected ByteArrayInputStream buf=null;
public BGZInputStream(String filename) throws IOException {
bgzf = new BGZFile(filename);
}
public BGZInputStream(BGZFile bgzf) throws IOException {
this.bgzf = bgzf;
}
public void close() throws IOException {
bgzf.close();
}
@Override
public int read() throws IOException {
if (buf == null || buf.available() == 0) {
BGZBlock block = bgzf.readCurrentBlock();
if (block == null) {
return -1;
}
byte[] cur = block.uBuf;
if (cur == null ) {
return -1;
}
buf = new ByteArrayInputStream(cur);
}
return buf.read();
}
} |
package org.apache.fop.svg;
import org.apache.batik.bridge.SVGImageElementBridge;
import org.apache.fop.image.JpegImage;
import org.apache.fop.image.FopImage;
import org.apache.fop.image.analyser.ImageReaderFactory;
import java.awt.Shape;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import org.w3c.dom.Element;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.gvt.AbstractGraphicsNode;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.ParsedURL;
/**
* Bridge class for the <image> element when jpeg images.
*
* @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a>
*/
public class PDFImageElementBridge extends SVGImageElementBridge {
/**
* Constructs a new bridge for the <image> element.
*/
public PDFImageElementBridge() { }
/**
* Create the raster image node.
* THis checks if it is a jpeg file and creates a jpeg node
* so the jpeg can be inserted directly into the pdf document.
* @param ctx the bridge context
* @param e the svg element for the image
* @param purl the parsed url for the image resource
* @return a new graphics node
*/
protected GraphicsNode createImageGraphicsNode
(BridgeContext ctx, Element e, ParsedURL purl) {
GraphicsNode origGN = super.createImageGraphicsNode
(ctx, e, purl);
try {
FopImage.ImageInfo ii = ImageReaderFactory.make
(purl.toString(), purl.openStream(), null);
if (ii.mimeType.toLowerCase() == "image/jpeg") {
JpegImage jpeg = new JpegImage(ii);
PDFJpegNode node = new PDFJpegNode(jpeg, origGN);
Rectangle2D imgBounds = getImageBounds(ctx, e);
Rectangle2D bounds = node.getPrimitiveBounds();
float [] vb = new float[4];
vb[0] = 0;
vb[1] = 0;
vb[2] = (float) bounds.getWidth(); // width
vb[3] = (float) bounds.getHeight(); // height
// handles the 'preserveAspectRatio', 'overflow' and 'clip'
// and sets the appropriate AffineTransform to the image node
initializeViewport(ctx, e, node, vb, imgBounds);
return node;
}
} catch (Exception ex) {
}
return origGN;
}
/**
* A PDF jpeg node.
* This holds a jpeg image so that it can be drawn into
* the PDFGraphics2D.
*/
public static class PDFJpegNode extends AbstractGraphicsNode {
private JpegImage jpeg;
private GraphicsNode origGraphicsNode ;
/**
* Create a new pdf jpeg node for drawing jpeg images
* into pdf graphics.
* @param j the jpeg image
*/
public PDFJpegNode(JpegImage j,
GraphicsNode origGraphicsNode) {
jpeg = j;
this.origGraphicsNode = origGraphicsNode;
}
/**
* Get the outline of this image.
* @return the outline shape which is the primitive bounds
*/
public Shape getOutline() {
return getPrimitiveBounds();
}
/**
* Paint this jpeg image.
* As this is used for inserting jpeg into pdf
* it adds the jpeg image to the PDFGraphics2D.
* @param g2d the graphics to draw the image on
*/
public void primitivePaint(Graphics2D g2d) {
if (g2d instanceof PDFGraphics2D) {
PDFGraphics2D pdfg = (PDFGraphics2D) g2d;
pdfg.setTransform(getTransform());
float x = 0;
float y = 0;
try {
float width = jpeg.getWidth();
float height = jpeg.getHeight();
pdfg.addJpegImage(jpeg, x, y, width, height);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Not going directly into PDF so use
// original implemtation so filters etc work.
origGraphicsNode.primitivePaint(g2d);
}
}
/**
* Get the geometrix bounds of the image.
* @return the primitive bounds
*/
public Rectangle2D getGeometryBounds() {
return getPrimitiveBounds();
}
/**
* Get the primitive bounds of this bridge element.
* @return the bounds of the jpeg image
*/
public Rectangle2D getPrimitiveBounds() {
try {
return new Rectangle2D.Double(0, 0, jpeg.getWidth(),
jpeg.getHeight());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returns the bounds of the sensitive area covered by this node,
* This includes the stroked area but does not include the effects
* of clipping, masking or filtering.
* @return the bounds of the sensitive area
*/
public Rectangle2D getSensitiveBounds() {
//No interactive features, just return primitive bounds
return getPrimitiveBounds();
}
}
} |
package org.jivesoftware.wildfire;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.wildfire.audit.AuditStreamIDFactory;
import org.jivesoftware.wildfire.auth.UnauthorizedException;
import org.jivesoftware.wildfire.component.ComponentSession;
import org.jivesoftware.wildfire.component.InternalComponentManager;
import org.jivesoftware.wildfire.container.BasicModule;
import org.jivesoftware.wildfire.event.SessionEventDispatcher;
import org.jivesoftware.wildfire.handler.PresenceUpdateHandler;
import org.jivesoftware.wildfire.server.IncomingServerSession;
import org.jivesoftware.wildfire.server.OutgoingServerSession;
import org.jivesoftware.wildfire.server.OutgoingSessionPromise;
import org.jivesoftware.wildfire.spi.BasicStreamIDFactory;
import org.jivesoftware.wildfire.user.UserManager;
import org.jivesoftware.wildfire.user.UserNotFoundException;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.Presence;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Manages the sessions associated with an account. The information
* maintained by the Session manager is entirely transient and does
* not need to be preserved between server restarts.
*
* @author Derek DeMoro
*/
public class SessionManager extends BasicModule {
public static final int NEVER_KICK = -1;
private PresenceUpdateHandler presenceHandler;
private PacketRouter router;
private String serverName;
private JID serverAddress;
private UserManager userManager;
private int conflictLimit;
private ClientSessionListener clientSessionListener = new ClientSessionListener();
private ComponentSessionListener componentSessionListener = new ComponentSessionListener();
private IncomingServerSessionListener incomingServerListener = new IncomingServerSessionListener();
private OutgoingServerSessionListener outgoingServerListener = new OutgoingServerSessionListener();
/**
* Map that holds sessions that has been created but haven't been authenticated yet. The Map
* will hold client sessions.
*/
private Map<String, ClientSession> preAuthenticatedSessions = new ConcurrentHashMap<String, ClientSession>();
/**
* Map of priority ordered SessionMap objects with username (toLowerCase) as key. The sessions
* contained in this Map are client sessions. For each username a SessionMap is kept which
* tracks the session for each user resource.
*/
private Map<String, SessionMap> sessions = new ConcurrentHashMap<String, SessionMap>();
/**
* Map of anonymous server sessions. They need to be treated separately as they
* have no associated user, and don't follow the normal routing rules for
* priority based fall over. The sessions contained in this Map are client sessions.
*/
private Map<String, ClientSession> anonymousSessions = new ConcurrentHashMap<String, ClientSession>();
/**
* The sessions contained in this List are component sessions. For each connected component
* this Map will keep the component's session.
*/
private List<ComponentSession> componentsSessions = new CopyOnWriteArrayList<ComponentSession>();
private final Map<String, List<IncomingServerSession>> incomingServerSessions =
new ConcurrentHashMap<String, List<IncomingServerSession>>();
/**
* The sessions contained in this Map are server sessions originated from this server to remote
* servers. These sessions can only send packets to the remote server but are not capable of
* receiving packets from the remote server. Sessions will be added to this collecion only
* after they were authenticated. The key of the Map is the hostname of the remote server.
*/
private Map<String, OutgoingServerSession> outgoingServerSessions = new ConcurrentHashMap<String, OutgoingServerSession>();
/**
* <p>Session manager must maintain the routing table as sessions are added and
* removed.</p>
*/
private RoutingTable routingTable;
private StreamIDFactory streamIDFactory;
/**
* Timer that will clean up dead or inactive sessions. Currently only outgoing server sessions
* will be analyzed.
*/
private Timer timer = new Timer("Sessions cleanup");
/**
* Task that closes idle server sessions.
*/
private ServerCleanupTask serverCleanupTask;
/**
* Returns the instance of <CODE>SessionManagerImpl</CODE> being used by the XMPPServer.
*
* @return the instance of <CODE>SessionManagerImpl</CODE> being used by the XMPPServer.
*/
public static SessionManager getInstance() {
return XMPPServer.getInstance().getSessionManager();
}
public SessionManager() {
super("Session Manager");
if (JiveGlobals.getBooleanProperty("xmpp.audit.active")) {
streamIDFactory = new AuditStreamIDFactory();
}
else {
streamIDFactory = new BasicStreamIDFactory();
}
String conflictLimitProp = JiveGlobals.getProperty("xmpp.session.conflict-limit");
if (conflictLimitProp == null) {
conflictLimit = 0;
JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
}
else {
try {
conflictLimit = Integer.parseInt(conflictLimitProp);
}
catch (NumberFormatException e) {
conflictLimit = 0;
JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
}
}
}
/**
* Simple data structure to track sessions for a single user (tracked by resource
* and priority).
*/
private class SessionMap {
private Map<String,ClientSession> resources = new ConcurrentHashMap<String,ClientSession>();
private final LinkedList<String> priorityList = new LinkedList<String>();
/**
* Add a session to the manager.
*
* @param session
*/
void addSession(ClientSession session) {
String resource = session.getAddress().getResource();
Presence presence = session.getPresence();
int priority = presence == null ? 0 : presence.getPriority();
resources.put(resource, session);
sortSession(resource, priority);
}
/**
* Sorts the session into the list based on priority
*
* @param resource The resource corresponding to the session to sort
* @param priority The priority to use for sorting
*/
private void sortSession(String resource, int priority) {
synchronized (priorityList) {
if (priorityList.size() > 0) {
Iterator<String> iter = priorityList.iterator();
for (int i = 0; iter.hasNext(); i++) {
ClientSession sess = resources.get(iter.next());
if (sess != null && sess.getPresence().getPriority() <= priority) {
priorityList.add(i, resource);
break;
}
}
}
if (!priorityList.contains(resource)) {
priorityList.addLast(resource);
}
}
}
/**
* Change the priority of a session associated with the sender.
*
* @param sender The sender who's session just changed priority
* @param priority The new priority for the session
*/
public void changePriority(JID sender, int priority) {
String resource = sender.getResource();
if (resources.containsKey(resource)) {
synchronized (priorityList) {
priorityList.remove(resource);
sortSession(resource, priority);
}
}
}
/**
* Remove a session from the manager.
*
* @param session The session to remove
*/
void removeSession(Session session) {
String resource = session.getAddress().getResource();
resources.remove(resource);
synchronized (priorityList) {
priorityList.remove(resource);
}
}
/**
* Gets the session for the given resource.
*
* @param resource The resource describing the particular session
* @return The session for that resource or null if none found (use getDefaultSession() to obtain default)
*/
ClientSession getSession(String resource) {
return resources.get(resource);
}
/**
* Checks to see if a session for the given resource exists.
*
* @param resource The resource of the session we're checking
* @return True if we have a session corresponding to that resource
*/
boolean hasSession(String resource) {
return resources.containsKey(resource);
}
/**
* Returns the default session for the user based on presence priority. It's possible to
* indicate if only available sessions (i.e. with an available presence) should be
* included in the search.
*
* @param filterAvailable flag that indicates if only available sessions should be
* considered.
* @return The default session for the user.
*/
ClientSession getDefaultSession(boolean filterAvailable) {
if (priorityList.isEmpty()) {
return null;
}
if (!filterAvailable) {
return resources.get(priorityList.getFirst());
}
else {
synchronized (priorityList) {
for (int i=0; i < priorityList.size(); i++) {
ClientSession s = resources.get(priorityList.get(i));
if (s != null && s.getPresence().isAvailable()) {
return s;
}
}
}
return null;
}
}
/**
* Determines if this map is empty or not.
*
* @return True if the map contains no entries
*/
boolean isEmpty() {
return resources.isEmpty();
}
/**
* Broadcast to all resources for the given user
*
* @param packet
*/
private void broadcast(Packet packet) throws UnauthorizedException, PacketException {
for (Session session : resources.values()) {
packet.setTo(session.getAddress());
session.process(packet);
}
}
/**
* Create an iterator over all sessions for the user.
* We create a new list to generate the iterator so other threads
* may safely alter the session map without affecting the iterator.
*
* @return An iterator of all sessions
*/
public Collection<ClientSession> getSessions() {
return resources.values();
}
/**
* Returns a collection of all the sessions whose presence is available.
*
* @return a collection of all the sessions whose presence is available.
*/
public Collection<ClientSession> getAvailableSessions() {
LinkedList<ClientSession> list = new LinkedList<ClientSession>();
for (ClientSession session : resources.values()) {
if (session.getPresence().isAvailable()) {
list.add(session);
}
}
return list;
}
/**
* This specified session has received an available presence so we need to recalculate the
* order of the sessions so we can have update the default session.
*
* @param session the session that received an available presence.
*/
public void sessionAvailable(ClientSession session) {
changePriority(session.getAddress(), session.getPresence().getPriority());
}
/**
* This specified session has received an unavailable presence so we need to recalculate the
* order of the sessions so we can have update the default session.
*
* @param session the session that received an unavailable presence.
*/
public void sessionUnavailable(ClientSession session) {
changePriority(session.getAddress(), 0);
}
}
/**
* Returns a randomly created ID to be used in a stream element.
*
* @return a randomly created ID to be used in a stream element.
*/
public StreamID nextStreamID() {
return streamIDFactory.createStreamID();
}
/**
* Creates a new <tt>ClientSession</tt>.
*
* @param conn the connection to create the session from.
* @return a newly created session.
* @throws UnauthorizedException
*/
public Session createClientSession(Connection conn) throws UnauthorizedException {
if (serverName == null) {
throw new UnauthorizedException("Server not initialized");
}
StreamID id = nextStreamID();
ClientSession session = new ClientSession(serverName, conn, id);
conn.init(session);
// Register to receive close notification on this session so we can
// remove and also send an unavailable presence if it wasn't
// sent before
conn.registerCloseListener(clientSessionListener, session);
// Add to pre-authenticated sessions.
preAuthenticatedSessions.put(session.getAddress().getResource(), session);
return session;
}
public Session createComponentSession(Connection conn) throws UnauthorizedException {
if (serverName == null) {
throw new UnauthorizedException("Server not initialized");
}
StreamID id = nextStreamID();
ComponentSession session = new ComponentSession(serverName, conn, id);
conn.init(session);
// Register to receive close notification on this session so we can
// remove the external component from the list of components
conn.registerCloseListener(componentSessionListener, session);
// Add to component session.
componentsSessions.add(session);
return session;
}
public IncomingServerSession createIncomingServerSession(Connection conn, StreamID id)
throws UnauthorizedException {
if (serverName == null) {
throw new UnauthorizedException("Server not initialized");
}
IncomingServerSession session = new IncomingServerSession(serverName, conn, id);
conn.init(session);
// Register to receive close notification on this session so we can
// remove its route from the sessions set
conn.registerCloseListener(incomingServerListener, session);
return session;
}
/**
* Notification message that a new OutgoingServerSession has been created. Register a listener
* that will react when the connection gets closed.
*
* @param session the newly created OutgoingServerSession.
*/
public void outgoingServerSessionCreated(OutgoingServerSession session) {
// Register to receive close notification on this session so we can
// remove its route from the sessions set
session.getConnection().registerCloseListener(outgoingServerListener, session);
}
/**
* Registers that a server session originated by a remote server is hosting a given hostname.
* Notice that the remote server may be hosting several subdomains as well as virtual hosts so
* the same IncomingServerSession may be associated with many keys. If the remote server
* creates many sessions to this server (eg. one for each subdomain) then associate all
* the sessions with the originating server that created all the sessions.
*
* @param hostname the hostname that is being served by the remote server.
* @param session the incoming server session to the remote server.
*/
public void registerIncomingServerSession(String hostname, IncomingServerSession session) {
synchronized (incomingServerSessions) {
List<IncomingServerSession> sessions = incomingServerSessions.get(hostname);
if (sessions == null || sessions.isEmpty()) {
// First session from the remote server to this server so create a
// new association
List<IncomingServerSession> value = new CopyOnWriteArrayList<IncomingServerSession>();
value.add(session);
incomingServerSessions.put(hostname, value);
}
else {
// Add new session to the existing list of sessions originated by
// the remote server
sessions.add(session);
}
}
}
/**
* Unregisters the server sessions originated by a remote server with the specified hostname.
* Notice that the remote server may be hosting several subdomains as well as virtual hosts so
* the same IncomingServerSession may be associated with many keys. The remote server may have
* many sessions established with this server (eg. to the server itself and to subdomains
* hosted by this server).
*
* @param hostname the hostname that is being served by the remote server.
*/
public void unregisterIncomingServerSessions(String hostname) {
synchronized (incomingServerSessions) {
incomingServerSessions.remove(hostname);
}
}
/**
* Unregisters the specified remote server session originiated by the specified remote server.
*
* @param hostname the hostname that is being served by the remote server.
* @param session the session to unregiser.
*/
private void unregisterIncomingServerSession(String hostname, IncomingServerSession session) {
synchronized (incomingServerSessions) {
List<IncomingServerSession> sessions = incomingServerSessions.get(hostname);
if (sessions != null) {
sessions.remove(session);
if (sessions.isEmpty()) {
// Remove key since there are no more sessions associated
incomingServerSessions.remove(hostname);
}
}
}
}
/**
* Registers that a server session originated by this server has been established to
* a remote server named hostname. This session will only be used for sending packets
* to the remote server and cannot receive packets. The {@link OutgoingServerSession}
* may have one or more domains, subdomains or virtual hosts authenticated with the
* remote server.
*
* @param hostname the hostname that is being served by the remote server.
* @param session the outgoing server session to the remote server.
*/
public void registerOutgoingServerSession(String hostname, OutgoingServerSession session) {
outgoingServerSessions.put(hostname, session);
}
/**
* Unregisters the server session that was originated by this server to a remote server
* named hostname. This session was only being used for sending packets
* to the remote server and not for receiving packets. The {@link OutgoingServerSession}
* may have one or more domains, subdomains or virtual hosts authenticated with the
* remote server.
*
* @param hostname the hostname that the session was connected with.
*/
public void unregisterOutgoingServerSession(String hostname) {
outgoingServerSessions.remove(hostname);
}
/**
* Add a new session to be managed.
*/
public void addSession(ClientSession session) {
String username = session.getAddress().getNode();
SessionMap resources;
synchronized (username.intern()) {
resources = sessions.get(username);
if (resources == null) {
resources = new SessionMap();
sessions.put(username, resources);
}
resources.addSession(session);
// Remove the pre-Authenticated session but remember to use the temporary ID as the key
preAuthenticatedSessions.remove(session.getStreamID().toString());
}
// Fire session created event.
SessionEventDispatcher
.dispatchEvent(session, SessionEventDispatcher.EventType.session_created);
}
/**
* Notification message sent when a client sent an available presence for the session. Making
* the session available means that the session is now eligible for receiving messages from
* other clients. Sessions whose presence is not available may only receive packets (IQ packets)
* from the server. Therefore, an unavailable session remains invisible to other clients.
*
* @param session the session that receieved an available presence.
*/
public void sessionAvailable(ClientSession session) {
if (anonymousSessions.containsValue(session)) {
// Anonymous session always have resources so we only need to add one route. That is
// the route to the anonymous session
routingTable.addRoute(session.getAddress(), session);
}
else {
// A non-anonymous session is now available
Session defaultSession;
try {
SessionMap sessionMap = sessions.get(session.getUsername());
if (sessionMap == null) {
Log.warn("No SessionMap found for session" + "\n" + session);
}
// Update the order of the sessions based on the new presence of this session
sessionMap.sessionAvailable(session);
defaultSession = sessionMap.getDefaultSession(true);
JID node = new JID(defaultSession.getAddress().getNode(),
defaultSession.getAddress().getDomain(), null);
// Add route to default session (used when no resource is specified)
routingTable.addRoute(node, defaultSession);
// Add route to the new session
routingTable.addRoute(session.getAddress(), session);
// Broadcast presence between the user's resources
broadcastPresenceToOtherResource(session);
}
catch (UserNotFoundException e) {
// Do nothing since the session is anonymous (? - shouldn't happen)
}
}
}
/**
* Broadcast initial presence from the user's new available resource to any of the user's
* existing available resources (if any).
*
* @param session the session that received the new presence and therefore will not receive
* the notification.
*/
private void broadcastPresenceToOtherResource(ClientSession session)
throws UserNotFoundException {
Presence presence;
Collection<ClientSession> availableSession;
SessionMap sessionMap = sessions.get(session.getUsername());
if (sessionMap != null) {
availableSession = new ArrayList<ClientSession>(sessionMap.getAvailableSessions());
for (ClientSession userSession : availableSession) {
if (userSession != session) {
// Send the presence of an existing session to the session that has just changed
// the presence
if (session.getPresence().isAvailable()) {
presence = userSession.getPresence().createCopy();
presence.setTo(session.getAddress());
session.process(presence);
}
// Send the presence of the session whose presence has changed to this other
// user's session
presence = session.getPresence().createCopy();
presence.setTo(userSession.getAddress());
userSession.process(presence);
}
}
}
}
/**
* Notification message sent when a client sent an unavailable presence for the session. Making
* the session unavailable means that the session is not eligible for receiving messages from
* other clients.
*
* @param session the session that receieved an unavailable presence.
*/
public void sessionUnavailable(ClientSession session) {
if (session.getAddress() != null && routingTable != null &&
session.getAddress().toBareJID().trim().length() != 0) {
// Remove route to the removed session (anonymous or not)
routingTable.removeRoute(session.getAddress());
try {
if (session.getUsername() == null) {
// Do nothing since this is an anonymous session
return;
}
SessionMap sessionMap = sessions.get(session.getUsername());
// If sessionMap is null, which is an irregular case, try to clean up the routes to
// the user from the routing table
if (sessionMap == null) {
JID userJID = new JID(session.getUsername(), serverName, "");
if (routingTable.getRoute(userJID) != null) {
// Remove the route for the session's BARE address
routingTable.removeRoute(new JID(session.getAddress().getNode(),
session.getAddress().getDomain(), ""));
}
}
// If all the user sessions are gone then remove the route to the default session
else if (sessionMap.getAvailableSessions().isEmpty()) {
// Remove the route for the session's BARE address
routingTable.removeRoute(new JID(session.getAddress().getNode(),
session.getAddress().getDomain(), ""));
// Broadcast presence between the user's resources
broadcastPresenceToOtherResource(session);
}
else {
// Update the order of the sessions based on the new presence of this session
sessionMap.sessionUnavailable(session);
// Update the route for the session's BARE address
Session defaultSession = sessionMap.getDefaultSession(true);
routingTable.addRoute(new JID(defaultSession.getAddress().getNode(),
defaultSession.getAddress().getDomain(), ""),
defaultSession);
// Broadcast presence between the user's resources
broadcastPresenceToOtherResource(session);
}
}
catch (UserNotFoundException e) {
// Do nothing since the session is anonymous
}
}
}
/**
* Change the priority of a session, that was already available, associated with the sender.
*
* @param sender The sender who's session just changed priority
* @param priority The new priority for the session
*/
public void changePriority(JID sender, int priority) {
if (sender.getNode() == null || !userManager.isRegisteredUser(sender.getNode())) {
// Do nothing if the session belongs to an anonymous user
return;
}
String username = sender.getNode();
synchronized (username.intern()) {
SessionMap resources = sessions.get(username);
if (resources == null) {
return;
}
resources.changePriority(sender, priority);
// Get the session with highest priority
Session defaultSession = resources.getDefaultSession(true);
// Update the route to the bareJID with the session with highest priority
routingTable.addRoute(new JID(defaultSession.getAddress().getNode(),
defaultSession.getAddress().getDomain(), ""),
defaultSession);
}
}
/**
* Retrieve the best route to deliver packets to this session given the recipient jid. If the
* requested JID does not have a node (i.e. username) then the best route will be looked up
* in the anonymous sessions list. Otherwise, try to find a root for the exact JID
* (i.e. including the resource) and if none is found then answer the deafult session if any.
*
* @param recipient The recipient ID to deliver packets to
* @return The XMPPAddress best suited to use for delivery to the recipient
*/
public ClientSession getBestRoute(JID recipient) {
// Return null if the JID belongs to a foreign server
if (serverName == null || !serverName.equals(recipient.getDomain())) {
return null;
}
ClientSession session = null;
String resource = recipient.getResource();
String username = recipient.getNode();
if (resource != null && (username == null || !userManager.isRegisteredUser(username))) {
session = anonymousSessions.get(resource);
if (session == null){
session = getSession(recipient);
}
}
else {
synchronized (username.intern()) {
SessionMap sessionMap = sessions.get(username);
if (sessionMap != null) {
if (resource == null) {
session = sessionMap.getDefaultSession(false);
}
else {
session = sessionMap.getSession(resource);
if (session == null) {
session = sessionMap.getDefaultSession(false);
}
}
}
}
}
// Sanity check - check if the underlying session connection is closed. Remove the session
// from the list of sessions if the session is closed and proceed to look for another route.
if (session != null && session.getConnection().isClosed()) {
removeSession(session);
return getBestRoute(recipient);
}
return session;
}
public boolean isAnonymousRoute(String username) {
// JID's node and resource are the same for anonymous sessions
return anonymousSessions.containsKey(username);
}
public boolean isActiveRoute(String username, String resource) {
boolean hasRoute = false;
// Check if there is an anonymous session
if (resource != null && resource.equals(username) &&
anonymousSessions.containsKey(resource)) {
hasRoute = true;
}
else {
// Check if there is a session for a registered user
username = username.toLowerCase();
Session session = null;
synchronized (username.intern()) {
SessionMap sessionMap = sessions.get(username);
if (sessionMap != null) {
if (resource == null) {
hasRoute = !sessionMap.isEmpty();
}
else {
if (sessionMap.hasSession(resource)) {
session = sessionMap.getSession(resource);
}
}
}
}
// Makes sure the session is still active
// Must occur outside of the lock since validation can cause
// the socket to close - deadlocking on session removal
if (session != null && !session.getConnection().isClosed()) {
hasRoute = session.getConnection().validate();
}
}
return hasRoute;
}
/**
* Returns the session responsible for this JID.
*
* @param from the sender of the packet.
* @return the <code>Session</code> associated with the JID.
*/
public ClientSession getSession(JID from) {
// Return null if the JID is null
if (from == null) {
return null;
}
return getSession(from.getNode(), from.getDomain(), from.getResource());
}
/**
* Returns the session responsible for this JID data. The returned Session may have never sent
* an available presence (thus not have a route) or could be a Session that hasn't
* authenticated yet (i.e. preAuthenticatedSessions).
*
* @param username the username of the JID.
* @param domain the username of the JID.
* @param resource the username of the JID.
* @return the <code>Session</code> associated with the JID data.
*/
public ClientSession getSession(String username, String domain, String resource) {
// Return null if the JID's data belongs to a foreign server. If the server is
// shutting down then serverName will be null so answer null too in this case.
if (serverName == null || !serverName.equals(domain)) {
return null;
}
ClientSession session = null;
// Initially Check preAuthenticated Sessions
if (resource != null) {
session = preAuthenticatedSessions.get(resource);
if(session != null){
return session;
}
}
if (resource == null) {
return null;
}
if (username == null || !userManager.isRegisteredUser(username)) {
session = anonymousSessions.get(resource);
}
else {
synchronized (username.intern()) {
SessionMap sessionMap = sessions.get(username);
if (sessionMap != null) {
session = sessionMap.getSession(resource);
}
}
}
return session;
}
/**
* Returns a list that contains all client sessions connected to the server. The list
* contains sessions of anonymous and non-anonymous users.
*
* @return a list that contains all client sessions connected to the server.
*/
public Collection<ClientSession> getSessions() {
List<ClientSession> allSessions = new ArrayList<ClientSession>();
copyUserSessions(allSessions);
copyAnonSessions(allSessions);
return allSessions;
}
public Collection<ClientSession> getSessions(SessionResultFilter filter) {
List<ClientSession> results = new ArrayList<ClientSession>();
if (filter != null) {
// Grab all the possible matching sessions by user
if (filter.getUsername() == null) {
// No user id filtering
copyAnonSessions(results);
copyUserSessions(results);
}
else {
try {
copyUserSessions(userManager.getUser(filter.getUsername()).getUsername(),
results);
}
catch (UserNotFoundException e) {
// Ignore.
}
}
Date createMin = filter.getCreationDateRangeMin();
Date createMax = filter.getCreationDateRangeMax();
Date activityMin = filter.getLastActivityDateRangeMin();
Date activityMax = filter.getLastActivityDateRangeMax();
// Now we have a copy of the references so we can spend some time
// doing the rest of the filtering without locking out session access
// so let's iterate and filter each session one by one
List<ClientSession> filteredResults = new ArrayList<ClientSession>();
for (ClientSession session : results) {
// Now filter on creation date if needed
if (createMin != null || createMax != null) {
if (!isBetweenDates(session.getCreationDate(), createMin, createMax)) {
session = null;
}
}
// Now filter on activity date if needed
if ((activityMin != null || activityMax != null) && session != null) {
if (!isBetweenDates(session.getLastActiveDate(), activityMin, activityMax)) {
session = null;
}
}
if (session != null) {
if (!isBetweenPacketCount(session.getNumClientPackets(),
filter.getClientPacketRangeMin(),
filter.getClientPacketRangeMax())) {
session = null;
}
}
if (session != null) {
if (!isBetweenPacketCount(session.getNumServerPackets(),
filter.getServerPacketRangeMin(),
filter.getServerPacketRangeMax())) {
session = null;
}
}
if (session != null) {
filteredResults.add(session);
}
}
// Sort list.
Collections.sort(filteredResults, filter.getSortComparator());
int maxResults = filter.getNumResults();
if (maxResults == SessionResultFilter.NO_RESULT_LIMIT) {
maxResults = filteredResults.size();
}
// Now generate the final list. I believe it's faster to to build up a new
// list than it is to remove items from head and tail of the sorted tree
List<ClientSession> finalResults = new ArrayList<ClientSession>();
int startIndex = filter.getStartIndex();
Iterator<ClientSession> sortedIter = filteredResults.iterator();
for (int i = 0; sortedIter.hasNext() && finalResults.size() < maxResults; i++) {
ClientSession result = sortedIter.next();
if (i >= startIndex) {
finalResults.add(result);
}
}
return finalResults;
}
return results;
}
/**
* Returns the list of sessions that were originated by a remote server. The list will be
* ordered chronologically. IncomingServerSession can only receive packets from the remote
* server but are not capable of sending packets to the remote server.
*
* @param hostname the name of the remote server.
* @return the sessions that were originated by a remote server.
*/
public List<IncomingServerSession> getIncomingServerSessions(String hostname) {
List<IncomingServerSession> sessions = incomingServerSessions.get(hostname);
if (sessions == null) {
return Collections.emptyList();
}
else {
return Collections.unmodifiableList(sessions);
}
}
/**
* Returns a session that was originated from this server to a remote server.
* OutgoingServerSession an only send packets to the remote server but are not capable of
* receiving packets from the remote server.
*
* @param hostname the name of the remote server.
* @return a session that was originated from this server to a remote server.
*/
public OutgoingServerSession getOutgoingServerSession(String hostname) {
return outgoingServerSessions.get(hostname);
}
/**
* <p>Determines if the given date is before the min date, or after the max date.</p>
* <p>The check is complicated somewhat by the fact that min can be null indicating
* no earlier date, and max can be null indicating no upper limit.</p>
*
* @param date The date to check
* @param min The date must be after min, or any if min is null
* @param max The date must be before max, or any if max is null
* @return True if the date is between min and max
*/
private boolean isBetweenDates(Date date, Date min, Date max) {
boolean between = true;
if (min != null) {
if (date.before(min)) {
between = false;
}
}
if (max != null && between) {
if (date.after(max)) {
between = false;
}
}
return between;
}
/**
* <p>Determines if the given count is before the min count, or after the max count.</p>
* <p>The check is complicated somewhat by the fact that min or max
* can be SessionResultFilter.NO_PACKET_LIMIT indicating no limit.</p>
*
* @param count The count to check
* @param min The count must be over min, or any if min is SessionResultFilter.NO_PACKET_LIMIT
* @param max The count must be under max, or any if max is SessionResultFilter.NO_PACKET_LIMIT
* @return True if the count is between min and max
*/
private boolean isBetweenPacketCount(long count, long min, long max) {
boolean between = true;
if (min != SessionResultFilter.NO_PACKET_LIMIT) {
if (count < min) {
between = false;
}
}
if (max != SessionResultFilter.NO_PACKET_LIMIT && between) {
if (count > max) {
between = false;
}
}
return between;
}
private void copyAnonSessions(List<ClientSession> sessions) {
// Add anonymous sessions
for (ClientSession session : anonymousSessions.values()) {
sessions.add(session);
}
}
private void copyUserSessions(List<ClientSession> sessions) {
// Get a copy of the sessions from all users
for (String username : getSessionUsers()) {
for (ClientSession session : getSessions(username)) {
sessions.add(session);
}
}
}
private void copyUserSessions(String username, List<ClientSession> sessionList) {
// Get a copy of the sessions from all users
SessionMap sessionMap = sessions.get(username);
if (sessionMap != null) {
for (ClientSession session : sessionMap.getSessions()) {
sessionList.add(session);
}
}
}
public Iterator getAnonymousSessions() {
return Arrays.asList(anonymousSessions.values().toArray()).iterator();
}
public Collection<ClientSession> getSessions(String username) {
List<ClientSession> sessionList = new ArrayList<ClientSession>();
if (username != null) {
copyUserSessions(username, sessionList);
}
return sessionList;
}
/**
* Returns number of client sessions that are connected to the server. Anonymous users
* are included too.
*
* @return number of client sessions that are connected to the server.
*/
public int getSessionCount() {
int sessionCount = 0;
for (String username : getSessionUsers()) {
sessionCount += getSessionCount(username);
}
sessionCount += anonymousSessions.size();
return sessionCount;
}
/**
* Returns number of client sessions that are available. Anonymous users
* are included too.
*
* @return number of client sessions that are available.
*/
public int getActiveSessionCount() {
int sessionCount = 0;
for (ClientSession session : getSessions()) {
if (session.getPresence().isAvailable()) {
sessionCount++;
}
}
return sessionCount;
}
public int getAnonymousSessionCount() {
return anonymousSessions.size();
}
public int getSessionCount(String username) {
if (username == null || !userManager.isRegisteredUser(username)) {
return 0;
}
int sessionCount = 0;
SessionMap sessionMap = sessions.get(username);
if (sessionMap != null) {
sessionCount = sessionMap.resources.size();
}
return sessionCount;
}
public Collection<String> getSessionUsers() {
return Collections.unmodifiableCollection(sessions.keySet());
}
/**
* Returns a collection with the established sessions from external components.
*
* @return a collection with the established sessions from external components.
*/
public Collection<ComponentSession> getComponentSessions() {
return Collections.unmodifiableCollection(componentsSessions);
}
/**
* Returns the session of the component whose domain matches the specified domain.
*
* @param domain the domain of the component session to look for.
* @return the session of the component whose domain matches the specified domain.
*/
public ComponentSession getComponentSession(String domain) {
for (ComponentSession session : componentsSessions) {
if (domain.equals(session.getAddress().getDomain())) {
return session;
}
}
return null;
}
/**
* Returns a collection with the hostnames of the remote servers that currently have an
* incoming server connection to this server.
*
* @return a collection with the hostnames of the remote servers that currently have an
* incoming server connection to this server.
*/
public Collection<String> getIncomingServers() {
return Collections.unmodifiableCollection(incomingServerSessions.keySet());
}
/**
* Returns a collection with the hostnames of the remote servers that currently may receive
* packets sent from this server.
*
* @return a collection with the hostnames of the remote servers that currently may receive
* packets sent from this server.
*/
public Collection<String> getOutgoingServers() {
return Collections.unmodifiableCollection(outgoingServerSessions.keySet());
}
/**
* Broadcasts the given data to all connected sessions. Excellent
* for server administration messages.
*
* @param packet The packet to be broadcast
*/
public void broadcast(Packet packet) throws UnauthorizedException {
for (SessionMap sessionMap : sessions.values()) {
sessionMap.broadcast(packet);
}
for (Session session : anonymousSessions.values()) {
session.process(packet);
}
}
/**
* Broadcasts the given data to all connected sessions for a particular
* user. Excellent for updating all connected resources for users such as
* roster pushes.
*
* @param packet The packet to be broadcast
*/
public void userBroadcast(String username, Packet packet) throws UnauthorizedException, PacketException {
SessionMap sessionMap = sessions.get(username);
if (sessionMap != null) {
sessionMap.broadcast(packet);
}
}
/**
* Removes a session.
*
* @param session the session.
*/
public void removeSession(ClientSession session) {
// TODO: Requires better error checking to ensure the session count is maintained
// TODO: properly (removal actually does remove).
// Do nothing if session is null or if the server is shutting down. Note: When the server
// is shutting down the serverName will be null.
if (session == null || serverName == null) {
return;
}
SessionMap sessionMap;
if (anonymousSessions.containsValue(session)) {
anonymousSessions.remove(session.getAddress().getResource());
// Fire session event.
SessionEventDispatcher.dispatchEvent(session,
SessionEventDispatcher.EventType.anonymous_session_destroyed);
}
else {
// If this is a non-anonymous session then remove the session from the SessionMap
if (session.getAddress() != null &&
userManager.isRegisteredUser(session.getAddress().getNode())) {
String username = session.getAddress().getNode();
synchronized (username.intern()) {
sessionMap = sessions.get(username);
if (sessionMap != null) {
sessionMap.removeSession(session);
if (sessionMap.isEmpty()) {
sessions.remove(username);
}
}
}
if (sessionMap != null) {
// Fire session event.
SessionEventDispatcher.dispatchEvent(session,
SessionEventDispatcher.EventType.session_destroyed);
}
}
}
// If the user is still available then send an unavailable presence
Presence presence = session.getPresence();
if (presence == null || presence.isAvailable()) {
Presence offline = new Presence();
offline.setFrom(session.getAddress());
offline.setTo(new JID(null, serverName, null));
offline.setType(Presence.Type.unavailable);
router.route(offline);
}
else if (preAuthenticatedSessions.containsValue(session)) {
// Remove the session from the pre-Authenticated sessions list
preAuthenticatedSessions.remove(session.getAddress().getResource());
}
}
public void addAnonymousSession(ClientSession session) {
anonymousSessions.put(session.getAddress().getResource(), session);
// Remove the session from the pre-Authenticated sessions list
preAuthenticatedSessions.remove(session.getAddress().getResource());
// Fire session event.
SessionEventDispatcher.dispatchEvent(session,
SessionEventDispatcher.EventType.anonymous_session_created);
}
public int getConflictKickLimit() {
return conflictLimit;
}
/**
* Returns the temporary keys used by the sessions that has not been authenticated yet. This
* is an utility method useful for debugging situations.
*
* @return the temporary keys used by the sessions that has not been authenticated yet.
*/
public Collection<String> getPreAuthenticatedKeys() {
return preAuthenticatedSessions.keySet();
}
public void setConflictKickLimit(int limit) {
conflictLimit = limit;
JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
}
private class ClientSessionListener implements ConnectionCloseListener {
/**
* Handle a session that just closed.
*
* @param handback The session that just closed
*/
public void onConnectionClose(Object handback) {
try {
ClientSession session = (ClientSession)handback;
try {
if (session.getPresence().isAvailable() || !session.wasAvailable()) {
// Send an unavailable presence to the user's subscribers
// Note: This gives us a chance to send an unavailable presence to the
// entities that the user sent directed presences
Presence presence = new Presence();
presence.setType(Presence.Type.unavailable);
presence.setFrom(session.getAddress());
presenceHandler.process(presence);
}
}
finally {
// Remove the session
removeSession(session);
}
}
catch (Exception e) {
// Can't do anything about this problem...
Log.error(LocaleUtils.getLocalizedString("admin.error.close"), e);
}
}
}
private class ComponentSessionListener implements ConnectionCloseListener {
/**
* Handle a session that just closed.
*
* @param handback The session that just closed
*/
public void onConnectionClose(Object handback) {
ComponentSession session = (ComponentSession)handback;
try {
// Unbind registered domains for this external component
for (String domain : session.getExternalComponent().getSubdomains()) {
String subdomain = domain.substring(0, domain.indexOf(serverName) - 1);
InternalComponentManager.getInstance().removeComponent(subdomain);
}
}
catch (Exception e) {
// Can't do anything about this problem...
Log.error(LocaleUtils.getLocalizedString("admin.error.close"), e);
}
finally {
// Remove the session
componentsSessions.remove(session);
}
}
}
private class IncomingServerSessionListener implements ConnectionCloseListener {
/**
* Handle a session that just closed.
*
* @param handback The session that just closed
*/
public void onConnectionClose(Object handback) {
IncomingServerSession session = (IncomingServerSession)handback;
// Remove all the hostnames that were registered for this server session
for (String hostname : session.getValidatedDomains()) {
unregisterIncomingServerSession(hostname, session);
}
}
}
private class OutgoingServerSessionListener implements ConnectionCloseListener {
/**
* Handle a session that just closed.
*
* @param handback The session that just closed
*/
public void onConnectionClose(Object handback) {
OutgoingServerSession session = (OutgoingServerSession)handback;
// Remove all the hostnames that were registered for this server session
for (String hostname : session.getHostnames()) {
unregisterOutgoingServerSession(hostname);
// Remove the route to the session using the hostname
XMPPServer.getInstance().getRoutingTable().removeRoute(new JID(hostname));
}
}
}
public void initialize(XMPPServer server) {
super.initialize(server);
presenceHandler = server.getPresenceUpdateHandler();
router = server.getPacketRouter();
userManager = server.getUserManager();
routingTable = server.getRoutingTable();
serverName = server.getServerInfo().getName();
serverAddress = new JID(serverName);
if (JiveGlobals.getBooleanProperty("xmpp.audit.active")) {
streamIDFactory = new AuditStreamIDFactory();
}
else {
streamIDFactory = new BasicStreamIDFactory();
}
String conflictLimitProp = JiveGlobals.getProperty("xmpp.session.conflict-limit");
if (conflictLimitProp == null) {
conflictLimit = 0;
JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
}
else {
try {
conflictLimit = Integer.parseInt(conflictLimitProp);
}
catch (NumberFormatException e) {
conflictLimit = 0;
JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
}
}
// Run through the server sessions every 5 minutes after a 5 minutes server
// startup delay (default values)
serverCleanupTask = new ServerCleanupTask();
timer.schedule(serverCleanupTask, getServerSessionTimeout(), getServerSessionTimeout());
}
/**
* Sends a message with a given subject and body to all the active user sessions in the server.
*
* @param subject the subject to broadcast.
* @param body the body to broadcast.
*/
public void sendServerMessage(String subject, String body) {
sendServerMessage(null, subject, body);
}
/**
* Sends a message with a given subject and body to one or more user sessions related to the
* specified address. If address is null or the address's node is null then the message will be
* sent to all the user sessions. But if the address includes a node but no resource then
* the message will be sent to all the user sessions of the requeted user (defined by the node).
* Finally, if the address is a full JID then the message will be sent to the session associated
* to the full JID. If no session is found then the message is not sent.
*
* @param address the address that defines the sessions that will receive the message.
* @param subject the subject to broadcast.
* @param body the body to broadcast.
*/
public void sendServerMessage(JID address, String subject, String body) {
Message packet = createServerMessage(subject, body);
try {
if (address == null || address.getNode() == null ||
!userManager.isRegisteredUser(address)) {
broadcast(packet);
}
else if (address.getResource() == null || address.getResource().length() < 1) {
userBroadcast(address.getNode(), packet);
}
else {
ClientSession session = getSession(address);
if (session != null) {
session.process(packet);
}
}
}
catch (UnauthorizedException e) {
// Ignore.
}
}
private Message createServerMessage(String subject, String body) {
Message message = new Message();
message.setFrom(serverAddress);
if (subject != null) {
message.setSubject(subject);
}
message.setBody(body);
return message;
}
public void stop() {
Log.debug("Stopping server");
// Stop threads that are sending packets to remote servers
OutgoingSessionPromise.getInstance().shutdown();
timer.cancel();
if (JiveGlobals.getBooleanProperty("shutdownMessage.enabled")) {
sendServerMessage(null, LocaleUtils.getLocalizedString("admin.shutdown.now"));
}
try {
// Send the close stream header to all connected connections
Set<Session> sessions = new HashSet<Session>();
sessions.addAll(getSessions());
sessions.addAll(getComponentSessions());
sessions.addAll(outgoingServerSessions.values());
for (List<IncomingServerSession> incomingSessions : incomingServerSessions.values()) {
sessions.addAll(incomingSessions);
}
for (Session session : sessions) {
try {
session.getConnection().close();
}
catch (Throwable t) {
// Ignore.
}
}
}
catch (Exception e) {
// Ignore.
}
serverName = null;
}
/**
* Returns true if remote servers are allowed to have more than one connection to this
* server. Having more than one connection may improve number of packets that can be
* transfered per second. This setting only used by the server dialback mehod.<p>
*
* It is highly recommended that {@link #getServerSessionTimeout()} is enabled so that
* dead connections to this server can be easily discarded.
*
* @return true if remote servers are allowed to have more than one connection to this
* server.
*/
public boolean isMultipleServerConnectionsAllowed() {
return JiveGlobals.getBooleanProperty("xmpp.server.session.allowmultiple", true);
}
/**
* Sets if remote servers are allowed to have more than one connection to this
* server. Having more than one connection may improve number of packets that can be
* transfered per second. This setting only used by the server dialback mehod.<p>
*
* It is highly recommended that {@link #getServerSessionTimeout()} is enabled so that
* dead connections to this server can be easily discarded.
*
* @param allowed true if remote servers are allowed to have more than one connection to this
* server.
*/
public void setMultipleServerConnectionsAllowed(boolean allowed) {
JiveGlobals.setProperty("xmpp.server.session.allowmultiple", Boolean.toString(allowed));
if (allowed && JiveGlobals.getIntProperty("xmpp.server.session.idle", 10 * 60 * 1000) <= 0)
{
Log.warn("Allowing multiple S2S connections for each domain, without setting a " +
"maximum idle timeout for these connections, is unrecommended! Either " +
"set xmpp.server.session.allowmultiple to 'false' or change " +
"xmpp.server.session.idle to a (large) positive value.");
}
}
/**
* Sets the number of milliseconds to elapse between clearing of idle server sessions.
*
* @param timeout the number of milliseconds to elapse between clearings.
*/
public void setServerSessionTimeout(int timeout) {
if (getServerSessionTimeout() == timeout) {
return;
}
// Cancel the existing task because the timeout has changed
if (serverCleanupTask != null) {
serverCleanupTask.cancel();
}
// Create a new task and schedule it with the new timeout
serverCleanupTask = new ServerCleanupTask();
timer.schedule(serverCleanupTask, getServerSessionTimeout(), getServerSessionTimeout());
// Set the new property value
JiveGlobals.setProperty("xmpp.server.session.timeout", Integer.toString(timeout));
}
/**
* Returns the number of milliseconds to elapse between clearing of idle server sessions.
*
* @return the number of milliseconds to elapse between clearing of idle server sessions.
*/
public int getServerSessionTimeout() {
return JiveGlobals.getIntProperty("xmpp.server.session.timeout", 5 * 60 * 1000);
}
public void setServerSessionIdleTime(int idleTime) {
if (getServerSessionIdleTime() == idleTime) {
return;
}
// Set the new property value
JiveGlobals.setProperty("xmpp.server.session.idle", Integer.toString(idleTime));
if (idleTime <= 0 && isMultipleServerConnectionsAllowed() )
{
Log.warn("Allowing multiple S2S connections for each domain, without setting a " +
"maximum idle timeout for these connections, is unrecommended! Either " +
"set xmpp.server.session.allowmultiple to 'false' or change " +
"xmpp.server.session.idle to a (large) positive value.");
}
}
public int getServerSessionIdleTime() {
return JiveGlobals.getIntProperty("xmpp.server.session.idle", 10 * 60 * 1000);
}
/**
* Task that closes the idle server sessions.
*/
private class ServerCleanupTask extends TimerTask {
/**
* Close outgoing server sessions that have been idle for a long time.
*/
public void run() {
// Do nothing if this feature is disabled
if (getServerSessionIdleTime() == -1) {
return;
}
final long deadline = System.currentTimeMillis() - getServerSessionIdleTime();
// Check outgoing server sessions
for (OutgoingServerSession session : outgoingServerSessions.values()) {
try {
if (session.getLastActiveDate().getTime() < deadline) {
session.getConnection().close();
}
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
// Check incoming server sessions
for (List<IncomingServerSession> sessions : incomingServerSessions.values()) {
for (IncomingServerSession session : sessions) {
try {
if (session.getLastActiveDate().getTime() < deadline) {
session.getConnection().close();
}
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
}
}
} |
package jetbrains.buildServer.agentsPlugin;
import jetbrains.buildServer.configuration.ChangeListener;
import jetbrains.buildServer.configuration.FileWatcher;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.serverSide.BuildAgentManager;
import jetbrains.buildServer.serverSide.SBuildAgent;
import jetbrains.buildServer.serverSide.ServerPaths;
import jetbrains.buildServer.util.Dates;
import jetbrains.buildServer.util.FileUtil;
import jetbrains.buildServer.util.ItemProcessor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public class AgentTasks {
public static final String CONFIG_FILE_NAME = "agentTasks.properties";
private List<Future> myTasks = new ArrayList<Future>();
private final ScheduledExecutorService myExecutorService;
private final BuildAgentManager myAgentManager;
public AgentTasks(ServerPaths serverPaths, ScheduledExecutorService executorService, BuildAgentManager agentManager) {
myAgentManager = agentManager;
myExecutorService = executorService;
final File configFile = new File(serverPaths.getConfigDir(), CONFIG_FILE_NAME);
loadConfiguration(configFile);
FileWatcher configFileWatcher = new FileWatcher(configFile);
configFileWatcher.start();
configFileWatcher.registerListener(new ChangeListener() {
public void changeOccured(String s) {
loadConfiguration(configFile);
}
});
}
// agents.task.N=<HH:mm>,<enable|disable>,<agent names regexp>
private void loadConfiguration(File configFile) {
Properties props = new Properties();
if (configFile.isFile()) {
Loggers.SERVER.info("Loading configuration from file: " + configFile.getAbsolutePath());
FileInputStream fis = null;
try {
fis = new FileInputStream(configFile);
props.load(fis);
} catch (IOException e) {
Loggers.SERVER.warn("Failed to load configuration from file: " + configFile.getAbsolutePath() + ", error: " + e.toString());
} finally {
FileUtil.close(fis);
}
}
List<TaskDescriptor> tasks = new ArrayList<TaskDescriptor>();
for (String p: props.stringPropertyNames()) {
String taskDef = (String) props.get(p);
String[] splitted = taskDef.split(",");
try {
String[] timeStr = splitted[0].split(":");
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeStr[0]));
c.set(Calendar.MINUTE, Integer.parseInt(timeStr[1]));
c.set(Calendar.SECOND, 0);
final Date time = c.getTime();
final String taskName = splitted[1];
final Pattern regexp = Pattern.compile(splitted[2]);
Loggers.SERVER.info("Loaded task: " + taskName + " agents matching " + splitted[2] + " on " + splitted[0]);
TaskDescriptor td = new TaskDescriptor() {
public Date getScheduledTime() {
return time;
}
public ItemProcessor<SBuildAgent> getAgentsProcessor() {
return new ItemProcessor<SBuildAgent>() {
public boolean processItem(SBuildAgent sBuildAgent) {
if (regexp.matcher(sBuildAgent.getName()).find()) {
if ("enable".equals(taskName)) {
sBuildAgent.setEnabled(true, null, "Enabled by agent tasks plugin");
}
if ("disable".equals(taskName)) {
sBuildAgent.setEnabled(false, null, "Disabled by agent tasks plugin");
}
}
return true;
}
};
}
};
tasks.add(td);
} catch (Exception e) {
Loggers.SERVER.warn("Failed to load task definition: " + taskDef + ", error: " + e.toString());
}
}
scheduleTasks(tasks);
}
private synchronized void scheduleTasks(List<TaskDescriptor> tasks) {
for (Future t: myTasks) t.cancel(true);
myTasks.clear();
for (final TaskDescriptor td: tasks) {
Date now = Dates.now();
Date scheduled = td.getScheduledTime();
long diff = scheduled.getTime() - now.getTime();
if (diff < 0) diff += Dates.ONE_DAY;
final long delay = diff;
myTasks.add(myExecutorService.scheduleAtFixedRate(new Runnable() {
public void run() {
Set<SBuildAgent> allAgents = new HashSet<SBuildAgent>(myAgentManager.getRegisteredAgents());
allAgents.addAll(myAgentManager.getUnregisteredAgents());
for (SBuildAgent agent : allAgents) {
boolean result = td.getAgentsProcessor().processItem(agent);
if (!result) break; // stop processing if item processor asked for this
}
}
}, delay, Dates.ONE_DAY, TimeUnit.MILLISECONDS)); // run task every day
}
}
} |
package com.izforge.izpack.installer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.MetalTheme;
import com.izforge.izpack.GUIPrefs;
import com.izforge.izpack.LocaleDatabase;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.IzPackMetalTheme;
/**
* The IzPack graphical installer class.
*
* @author Julien Ponge
*/
public class GUIInstaller extends InstallerBase
{
/** The installation data. */
private InstallData installdata;
/** The L&F. */
protected String lnf;
/**
* The constructor.
*
* @exception Exception Description of the Exception
*/
public GUIInstaller() throws Exception
{
super();
this.installdata = new InstallData();
// Loads the installation data
loadInstallData(installdata);
// add the GUI install data
loadGUIInstallData();
// Sets up the GUI L&F
loadLookAndFeel();
// Checks the Java version
checkJavaVersion();
// Loads the suitable langpack
loadLangPack();
// create the resource manager (after the language selection!)
ResourceManager.create(this.installdata);
// We launch the installer GUI
loadGUI();
}
/**
* Load GUI preference information.
*
* @throws Exception
*/
public void loadGUIInstallData() throws Exception
{
InputStream in = GUIInstaller.class.getResourceAsStream("/GUIPrefs");
ObjectInputStream objIn = new ObjectInputStream(in);
this.installdata.guiPrefs = (GUIPrefs) objIn.readObject();
objIn.close();
}
/**
* Checks the Java version.
*
* @exception Exception Description of the Exception
*/
private void checkJavaVersion() throws Exception
{
String version = System.getProperty("java.version");
String required = this.installdata.info.getJavaVersion();
if (version.compareTo(required) < 0)
{
StringBuffer msg = new StringBuffer();
msg.append("The application that you are trying to install requires a ");
msg.append(required);
msg.append(" version or later of the Java platform.\n");
msg.append("You are running a ");
msg.append(version);
msg.append(" version of the Java platform.\n");
msg.append("Please upgrade to a newer version.");
System.out.println(msg.toString());
JOptionPane.showMessageDialog(null, msg.toString(), "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
/**
* Loads the suitable langpack.
*
* @exception Exception Description of the Exception
*/
private void loadLangPack() throws Exception
{
// Initialisations
List availableLangPacks = getAvailableLangPacks();
int npacks = availableLangPacks.size();
if (npacks == 0) throw new Exception("no language pack available");
String selectedPack;
// Dummy Frame
JFrame frame = new JFrame();
frame.setIconImage( new ImageIcon(
this.getClass().getResource( "/img/JFrameIcon.png" )).getImage() );
Dimension frameSize = frame.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2 - 10);
// We get the langpack name
if (npacks != 1)
{
LanguageDialog picker = new LanguageDialog(frame, availableLangPacks.toArray());
picker.setSelection(Locale.getDefault().getISO3Country().toLowerCase());
picker.setModal(true);
picker.toFront();
frame.show();
picker.show();
frame.hide();
selectedPack = (String) picker.getSelection();
if (selectedPack == null) throw new Exception("installation canceled");
}
else
selectedPack = (String) availableLangPacks.get(0);
// We add an xml data information
this.installdata.xmlData.setAttribute("langpack", selectedPack);
// We load the langpack
installdata.localeISO3 = selectedPack;
installdata.setVariable(ScriptParser.ISO3_LANG, installdata.localeISO3);
InputStream in = getClass().getResourceAsStream(
"/langpacks/" + selectedPack + ".xml");
this.installdata.langpack = new LocaleDatabase(in);
}
/**
* Returns an ArrayList of the available langpacks ISO3 codes.
*
* @return The available langpacks list.
* @exception Exception Description of the Exception
*/
private List getAvailableLangPacks() throws Exception
{
// We read from the langpacks file in the jar
InputStream in = getClass().getResourceAsStream("/langpacks.info");
ObjectInputStream objIn = new ObjectInputStream(in);
List available = (List) objIn.readObject();
objIn.close();
return available;
}
/**
* Loads the suitable L&F.
*
* @exception Exception Description of the Exception
*/
protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String sysos = System.getProperty("os.name");
String syskey = "unix";
if (sysos.regionMatches(true, 0, "windows", 0, 7))
{
syskey = "windows";
}
else if (sysos.regionMatches(true, 0, "mac", 0, 3))
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
ButtonFactory.useButtonIcons();
if (laf == null)
{
if (!syskey.equals("mac"))
{
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
if (laf.equals("kunststoff"))
{
ButtonFactory.useHighlightButtons();
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class
.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
if (laf.equals("liquid"))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map)installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String)params.get("decorate.frames");
if (value.equals("yes"))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String)params.get("decorate.dialogs");
if (value.equals("yes"))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
if (laf.equals("metouia"))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
if (laf.equals("looks"))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel ");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String)variants.get("plasticXP");
Map params = (Map)installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String)params.get("variant");
if (variants.containsKey(param))
{
variant = (String)variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
/**
* Loads the GUI.
*
* @exception Exception Description of the Exception
*/
private void loadGUI() throws Exception
{
UIManager.put("OptionPane.yesButtonText", installdata.langpack
.getString("installer.yes"));
UIManager.put("OptionPane.noButtonText", installdata.langpack
.getString("installer.no"));
UIManager.put("OptionPane.cancelButtonText", installdata.langpack
.getString("installer.cancel"));
String title = installdata.langpack.getString("installer.title")
+ this.installdata.info.getAppName();
new InstallerFrame(title, this.installdata);
}
/**
* Used to prompt the user for the language.
*
* @author Julien Ponge
*/
private final class LanguageDialog extends JDialog implements ActionListener
{
/** The combo box. */
private JComboBox comboBox;
/** The ok button. */
private JButton okButton;
/**
* The constructor.
*
* @param items The items to display in the box.
*/
public LanguageDialog(JFrame frame, Object[] items)
{
super(frame);
try
{
loadLookAndFeel();
}
catch (Exception err)
{
err.printStackTrace();
}
// We build the GUI
addWindowListener(new WindowHandler());
JPanel contentPane = (JPanel) getContentPane();
setTitle("Language selection");
GridBagLayout layout = new GridBagLayout();
contentPane.setLayout(layout);
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.CENTER;
gbConstraints.insets = new Insets(5, 5, 5, 5);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.gridx = 0;
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 1.0;
ImageIcon img = getImage();
JLabel imgLabel = new JLabel(img);
gbConstraints.gridy = 0;
contentPane.add(imgLabel);
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
JLabel label1 = new JLabel("Please select your language (ISO3 code)",
SwingConstants.CENTER);
gbConstraints.gridy = 1;
gbConstraints.insets = new Insets(5, 5, 0, 5);
layout.addLayoutComponent(label1, gbConstraints);
contentPane.add(label1);
JLabel label2 = new JLabel("for install instructions:",
SwingConstants.CENTER);
gbConstraints.gridy = 2;
gbConstraints.insets = new Insets(0, 5, 5, 5);
layout.addLayoutComponent(label2, gbConstraints);
contentPane.add(label2);
gbConstraints.insets = new Insets(5, 5, 5, 5);
comboBox = new JComboBox(items);
comboBox.setRenderer(new FlagRenderer());
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.gridy = 3;
layout.addLayoutComponent(comboBox, gbConstraints);
contentPane.add(comboBox);
okButton = new JButton("Ok");
okButton.addActionListener(this);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.gridy = 4;
gbConstraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(okButton, gbConstraints);
contentPane.add(okButton);
getRootPane().setDefaultButton(okButton);
// Packs and centers
// Fix for bug "Installer won't show anything on OSX"
if (System.getProperty("mrj.version") == null)
pack();
else
setSize(getPreferredSize());
Dimension frameSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2 - 10);
setResizable(true);
}
/**
* Loads an image.
*
* @return The image icon.
*/
public ImageIcon getImage()
{
ImageIcon img;
try
{
img = new ImageIcon(LanguageDialog.class.getResource(
"/res/installer.langsel.img"));
}
catch (NullPointerException err)
{
img = null;
}
return img;
}
/**
* Gets the selected object.
*
* @return The selected item.
*/
public Object getSelection()
{
return comboBox.getSelectedItem();
}
/**
* Sets the selection.
*
* @param item The item to be selected.
*/
public void setSelection(Object item)
{
comboBox.setSelectedItem(item);
}
/**
* Closer.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
dispose();
}
/**
* The window events handler.
*
* @author Julien Ponge
*/
private class WindowHandler extends WindowAdapter
{
/**
* We can't avoid the exit here, so don't call exit anywhere else.
*
* @param e the event.
*/
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
/**
* A list cell renderer that adds the flags on the display.
*
* @author Julien Ponge
*/
private static class FlagRenderer extends JLabel implements ListCellRenderer
{
/** Icons cache. */
private TreeMap icons = new TreeMap();
/** Grayed icons cache. */
private TreeMap grayIcons = new TreeMap();
public FlagRenderer()
{
setOpaque(true);
}
/**
* Returns a suitable cell.
*
* @param list The list.
* @param value The object.
* @param index The index.
* @param isSelected true if it is selected.
* @param cellHasFocus Description of the Parameter
* @return The cell.
*/
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
// We put the label
String iso3 = (String) value;
setText(iso3);
if (isSelected)
{
setForeground(list.getSelectionForeground());
setBackground(list.getSelectionBackground());
}
else
{
setForeground(list.getForeground());
setBackground(list.getBackground());
}
// We put the icon
if (!icons.containsKey(iso3))
{
ImageIcon icon;
icon = new ImageIcon(this.getClass().getResource("/res/flag." + iso3));
icons.put(iso3, icon);
icon = new ImageIcon(GrayFilter.createDisabledImage(icon.getImage()));
grayIcons.put(iso3, icon);
}
if (isSelected || index == -1)
setIcon((ImageIcon) icons.get(iso3));
else
setIcon((ImageIcon) grayIcons.get(iso3));
// We return
return this;
}
}
} |
package agaricus.mods.oredupefix;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.ItemData;
import cpw.mods.fml.relauncher.ReflectionHelper;
import ic2.api.Ic2Recipes;
import ic2.core.AdvRecipe;
import ic2.core.AdvShapelessRecipe;
import ic2.core.item.ItemScrapbox;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.*;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.ConfigCategory;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import java.util.*;
import java.util.logging.Level;
@Mod(modid = "OreDupeFix", name = "OreDupeFix", version = "2.0-1.4.7") // TODO: version from resource
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class OreDupeFix {
/**
* Map from ore name to mod ID preferred by user
*/
public static HashMap<String, String> oreName2PreferredMod;
/**
* Map from ore name to ItemStack preferred by user, from their preferred mod
*/
public static HashMap<String, ItemStack> oreName2PreferredItem;
private static boolean shouldDumpOreDict;
private static boolean verbose;
private static boolean replaceCrafting;
private static boolean replaceFurnace;
private static boolean replaceFurnaceInsensitive;
private static boolean replaceDungeonLoot;
private static boolean replaceIC2Compressor;
private static boolean replaceIC2Extractor;
private static boolean replaceIC2Macerator;
private static boolean replaceIC2Scrapbox;
@PreInit
public static void preInit(FMLPreInitializationEvent event) {
oreName2PreferredMod = new HashMap<String, String>();
Configuration cfg = new Configuration(event.getSuggestedConfigurationFile());
FMLLog.log(Level.FINE, "OreDupeFix loading config");
try {
cfg.load();
if (cfg.categories.size() == 0) {
loadDefaults(cfg);
}
ConfigCategory category = cfg.getCategory("PreferredOres");
for (Map.Entry<String, Property> entry : category.entrySet()) {
String name = entry.getKey();
Property property = entry.getValue();
if (property.value.length() == 0) {
// not set
continue;
}
oreName2PreferredMod.put(name, property.value);
}
shouldDumpOreDict = cfg.get(Configuration.CATEGORY_GENERAL, "dumpOreDict", true).getBoolean(true);
verbose = cfg.get(Configuration.CATEGORY_GENERAL, "verbose", true).getBoolean(true);
// TODO: refactor
replaceCrafting = cfg.get(Configuration.CATEGORY_GENERAL, "replaceCrafting", true).getBoolean(true);
replaceFurnace = cfg.get(Configuration.CATEGORY_GENERAL, "replaceFurnace", true).getBoolean(true);
replaceFurnaceInsensitive = cfg.get(Configuration.CATEGORY_GENERAL, "replaceFurnaceInsensitive", true).getBoolean(true);
replaceDungeonLoot = cfg.get(Configuration.CATEGORY_GENERAL, "replaceDungeonLoot", true).getBoolean(true);
replaceIC2Compressor = cfg.get(Configuration.CATEGORY_GENERAL, "replaceIC2Compressor", true).getBoolean(true);
replaceIC2Extractor = cfg.get(Configuration.CATEGORY_GENERAL, "replaceIC2Extractor", true).getBoolean(true);
replaceIC2Macerator = cfg.get(Configuration.CATEGORY_GENERAL, "replaceIC2Macerator", true).getBoolean(true);
replaceIC2Scrapbox = cfg.get(Configuration.CATEGORY_GENERAL, "replaceIC2Scrapbox", true).getBoolean(true);
} catch (Exception e) {
FMLLog.log(Level.SEVERE, e, "OreDupeFix had a problem loading it's configuration");
} finally {
cfg.save();
}
}
@PostInit
public static void postInit(FMLPostInitializationEvent event) {
log("Loading OreDupeFix...");
if (shouldDumpOreDict) {
dumpOreDict();
}
loadPreferredOres();
if (replaceCrafting) replaceCraftingRecipes();
if (replaceFurnace) replaceFurnaceRecipes();
if (replaceFurnaceInsensitive) replaceFurnaceRecipesInsensitive();
if (replaceDungeonLoot) replaceDungeonLoot();
// IC2 machines
try {
if (replaceIC2Compressor) replaceIC2MachineRecipes(Ic2Recipes.getCompressorRecipes());
if (replaceIC2Extractor) replaceIC2MachineRecipes(Ic2Recipes.getExtractorRecipes());
if (replaceIC2Macerator) replaceIC2MachineRecipes(Ic2Recipes.getMaceratorRecipes());
if (replaceIC2Scrapbox) replaceIC2ScrapboxDrops();
} catch (Throwable t) {
t.printStackTrace();
FMLLog.log(Level.WARNING, "Failed to replace IC2 machine recipes: "+t.getLocalizedMessage()+", fix this (update?) or turn off replaceIC2* in config");
}
// TE machines
/*
// TODO - check TE API for 'replaceable recipes' setting
ICrucibleRecipe[] iCrucibleRecipes = CraftingManagers.crucibleManager.getRecipeList();
IFurnaceRecipe[] iFurnaceRecipes = CraftingManagers.furnaceManager.getRecipeList();
IPulverizerRecipe[] iPulverizerRecipes = CraftingManagers.pulverizerManager.getRecipeList();
ISawmillRecipe[] iSawmillRecipes = CraftingManagers.sawmillManager.getRecipeList();
ISmelterRecipe[] iSmelterRecipes = CraftingManagers.smelterManager.getRecipeList();
//ISmelterRecipe[] iFillRecipes F= CraftingManagers.transposerManager.getFillRecipeList(); // TODO
*/
}
public static void log(String message) {
if (verbose) {
System.out.println(message);
}
}
public static void loadDefaults(Configuration cfg) {
ConfigCategory category = cfg.getCategory("PreferredOres");
FMLLog.log(Level.FINE, "OreDupeFix initializing defaults");
HashMap<String, String> m = new HashMap<String, String>();
// populate with all ore names for documentation purposes, no overrides
Map<Integer, ItemData> idMap = ReflectionHelper.getPrivateValue(GameData.class, null, "idMap");
List<String> oreNames = Arrays.asList(OreDictionary.getOreNames());
Collections.sort(oreNames);
for (String oreName : oreNames) {
m.put(oreName, "");
}
// a reasonable set of defaults
m.put("ingotCopper", "RedPowerBase");
m.put("ingotTin", "RedPowerBase");
m.put("ingotBronze", "IC2");
m.put("ingotSilver", "RedPowerBase");
m.put("ingotLead", "ThermalExpansion");
m.put("dustBronze", "ThermalExpansion");
m.put("dustIron", "ThermalExpansion");
m.put("dustTin", "ThermalExpansion");
m.put("dustSilver", "ThermalExpansion");
m.put("dustCopper", "ThermalExpansion");
m.put("dustGold", "ThermalExpansion");
m.put("dustObsidian", "ThermalExpansion");
m.put("nuggetTin", "ThermalExpansion");
m.put("nuggetCopper", "Thaumcraft");
m.put("nuggetIron", "Thaumcraft");
m.put("nuggetSilver", "Thaumcraft");
m.put("nuggetTin", "Thaumcraft");
m.put("oreCopper", "IC2");
m.put("oreSilver", "ThermalExpansion");
m.put("oreTin", "IC2");
for (Map.Entry<String, String> entry : m.entrySet()) {
String oreName = entry.getKey();
String modID = entry.getValue();
category.put(oreName, new Property(oreName, modID, Property.Type.STRING));
}
}
public static void loadPreferredOres() {
oreName2PreferredItem = new HashMap<String, ItemStack>();
// Get registered ores and associated mods
Map<Integer, ItemData> idMap = ReflectionHelper.getPrivateValue(GameData.class, null, "idMap");
// Map ore dict name to preferred item, given mod ID
for (Map.Entry<String, String> entry : oreName2PreferredMod.entrySet()) {
String oreName = entry.getKey();
String preferredModID = entry.getValue();
ArrayList<ItemStack> oreItems = OreDictionary.getOres(oreName);
boolean found = false;
for (ItemStack oreItem : oreItems) {
ItemData itemData = idMap.get(oreItem.itemID);
String modID = itemData.getModId();
if (preferredModID.equals(modID)) {
oreName2PreferredItem.put(oreName, oreItem);
found = true;
break;
}
}
if (!found) {
log("No mod '"+preferredModID+"' found for ore '"+oreName+"'! Skipping");
}
}
// Show ore preferences
for (String oreName : oreName2PreferredMod.keySet()) {
String modID = oreName2PreferredMod.get(oreName);
ItemStack itemStack = oreName2PreferredItem.get(oreName);
if (itemStack != null) {
System.out.println("Preferring ore name "+oreName+" from mod "+modID+" = "+itemStack.itemID+":"+ itemStack.getItemDamage());
}
}
}
/**
* Dump ore dictionary
*/
public static void dumpOreDict() {
Map<Integer, ItemData> idMap = ReflectionHelper.getPrivateValue(GameData.class, null, "idMap");
List<String> oreNames = Arrays.asList(OreDictionary.getOreNames());
Collections.sort(oreNames);
for (String oreName : oreNames) {
System.out.print("ore: " + oreName + ": ");
ArrayList<ItemStack> oreItems = OreDictionary.getOres(oreName);
for (ItemStack oreItem : oreItems) {
ItemData itemData = idMap.get(oreItem.itemID);
String modID = itemData.getModId();
System.out.print(oreItem.itemID + ":" + oreItem.getItemDamage() + "=" + modID + ", ");
}
System.out.println("");
}
}
/**
* Get an equivalent but preferred item
* @param output The existing ore dictionary item
* @return A new ore dictionary item, for the name ore but preferred by the user
*/
public static ItemStack getPreferredOre(ItemStack output) {
int oreID = OreDictionary.getOreID(output);
if (oreID == -1) {
// this isn't an ore
return null;
}
String oreName = OreDictionary.getOreName(oreID);
ItemStack newOutputType = oreName2PreferredItem.get(oreName);
if (newOutputType == null) {
// no preference, do not replace
return null;
}
// replace with new stack of same size but new type
ItemStack newOutput = new ItemStack(newOutputType.itemID, output.stackSize, newOutputType.getItemDamage());
return newOutput;
}
public static void replaceCraftingRecipes() {
// Crafting recipes
List recipeList = CraftingManager.getInstance().getRecipeList();
for(Object recipe: recipeList) {
if (!(recipe instanceof IRecipe)) {
continue;
}
IRecipe iRecipe = (IRecipe)recipe;
ItemStack output = iRecipe.getRecipeOutput();
if (output == null) {
// some recipes require computing the output with getCraftingResult()
continue;
}
ItemStack newOutput = getPreferredOre(output);
if (newOutput == null) {
// do not replace
continue;
}
log("Modifying recipe "+iRecipe+" replacing "+output.itemID+":"+output.getItemDamage()+" -> "+newOutput.itemID+":"+newOutput.getItemDamage());
setCraftingRecipeOutput(iRecipe, newOutput);
}
}
public static void setCraftingRecipeOutput(IRecipe iRecipe, ItemStack output) {
if (iRecipe instanceof ShapedRecipes) {
ReflectionHelper.setPrivateValue(ShapedRecipes.class,(ShapedRecipes)iRecipe, output, "e"/*"recipeOutput"*/); // TODO: avoid hardcoding obf
} else if (iRecipe instanceof ShapelessRecipes) {
ReflectionHelper.setPrivateValue(ShapelessRecipes.class,(ShapelessRecipes)iRecipe, output, "a"/*"recipeOutput"*/);
} else if (iRecipe instanceof ShapelessOreRecipe) {
ReflectionHelper.setPrivateValue(ShapelessOreRecipe.class,(ShapelessOreRecipe)iRecipe, output, "output");
} else if (iRecipe instanceof ShapedOreRecipe) {
ReflectionHelper.setPrivateValue(ShapedOreRecipe.class,(ShapedOreRecipe)iRecipe, output, "output");
// IndustrialCraft^2
} else if (iRecipe instanceof AdvRecipe) {
// thanks IC2 for making this field public.. even if recipes aren't in the API
((AdvRecipe)iRecipe).output = output;
} else if (iRecipe instanceof AdvShapelessRecipe) {
((AdvShapelessRecipe)iRecipe).output = output;
}
}
public static void replaceFurnaceRecipes() {
// Furnace recipes
Map<List<Integer>, ItemStack> metaSmeltingList = FurnaceRecipes.smelting().getMetaSmeltingList(); // metadata-sensitive; (itemID,metadata) to ItemStack
for (Map.Entry<List<Integer>, ItemStack> entry : metaSmeltingList.entrySet()) {
List<Integer> inputItemPlusData = entry.getKey();
ItemStack output = entry.getValue();
ItemStack newOutput = getPreferredOre(output);
if (newOutput != null) {
entry.setValue(newOutput);
}
}
}
@SuppressWarnings("unchecked")
public static void replaceFurnaceRecipesInsensitive() {
Map<Integer, ItemStack> smeltingList = (Map<Integer, ItemStack>)FurnaceRecipes.smelting().getSmeltingList(); // itemID to ItemStack
for (Map.Entry<Integer, ItemStack> entry : smeltingList.entrySet()) {
int itemID = entry.getKey();
ItemStack output = entry.getValue();
ItemStack newOutput = getPreferredOre(output);
if (newOutput != null) {
entry.setValue(newOutput);
}
}
}
public static void replaceDungeonLoot() {
try {
HashMap<String, ChestGenHooks> chestInfo = ReflectionHelper.getPrivateValue(ChestGenHooks.class, null, "chestInfo");
for (Map.Entry<String, ChestGenHooks> entry : chestInfo.entrySet()) {
ChestGenHooks chestGenHooks = entry.getValue();
ArrayList<WeightedRandomChestContent> contents = ReflectionHelper.getPrivateValue(ChestGenHooks.class, chestGenHooks, "contents");
for (WeightedRandomChestContent weightedRandomChestContent : contents) {
ItemStack output = weightedRandomChestContent.theItemId;
ItemStack newOutput = getPreferredOre(output);
if (newOutput == null) {
continue;
}
log("Modifying dungeon loot in "+entry.getKey()+", replacing "+output.itemID+":"+output.getItemDamage()+" -> "+newOutput.itemID+":"+newOutput.getItemDamage());
weightedRandomChestContent.theItemId = newOutput;
}
}
} catch (Throwable t) {
System.out.println("Failed to replace dungeon loot: " + t);
}
}
public static void replaceIC2MachineRecipes(List<Map.Entry<ItemStack, ItemStack>> machineRecipes) {
for (int i = 0; i < machineRecipes.size(); i += 1) {
Map.Entry<ItemStack, ItemStack> entry = machineRecipes.get(i);
ItemStack input = entry.getKey();
ItemStack output = entry.getValue();
ItemStack newOutput = getPreferredOre(output);
if (newOutput != null) {
entry.setValue(newOutput);
}
}
}
public static void replaceIC2ScrapboxDrops() {
// Replace scrapbox drops in the item itself -- cannot use the API
// Ic2Recipes.getScrapboxDrops() call since it returns a copy :(
try {
List dropList = ItemScrapbox.dropList;
// 'Drop' inner class
Class dropClass = ItemScrapbox.class.getDeclaredClasses()[0];
for (int i = 0; i < dropList.size(); i++) {
Object drop = dropList.get(i);
ItemStack output = ReflectionHelper.getPrivateValue((Class<? super Object>)dropClass, drop, 0);
ItemStack newOutput = getPreferredOre(output);
if (newOutput == null) {
continue;
}
log("Modifying IC2 scrapbox drop, replacing "+output.itemID+":"+output.getItemDamage()+" -> "+newOutput.itemID+":"+newOutput.getItemDamage());
ReflectionHelper.setPrivateValue(dropClass, drop, newOutput, 0);
}
} catch (Throwable t) {
System.out.println("Failed to replace IC2 scrapbox drops: "+t);
}
}
} |
package at.ngmpps.fjsstt.rest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.ngmpps.fjsstt.factory.ModelFactory;
import at.ngmpps.fjsstt.factory.ProblemParser;
import at.ngmpps.fjsstt.model.ProblemSet;
import at.ngmpps.fjsstt.model.problem.FJSSTTproblem;
import at.ngmpps.fjsstt.model.problem.Solution;
import at.profactor.NgMPPS.ActorHelper;
import at.profactor.NgMPPS.Actors.Messages.MainSolveProtocol.SolutionReady;
@Path("/asyncresource")
public class AsyncResource {
private static int numberOfSuccessResponses = 0;
private static int numberOfFailures = 0;
private static Throwable lastException = null;
final static Logger log = LoggerFactory.getLogger(AsyncResource.class);
final static Map<Integer, Solution> solutions = Collections.synchronizedMap(new HashMap<>());
ActorHelper ah = null;
Integer lastRequestId = -1;
@GET
public void asyncGetWithTimeout(@Suspended final AsyncResponse asyncResponse) {
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
if (throwable == null) {
// no throwable - the processing ended successfully
// (response already written to the client)
numberOfSuccessResponses++;
} else {
numberOfFailures++;
lastException = throwable;
}
}
});
// no problem Set paramenter =>> use default problem // do not set lastRequestId, keep old one (unless actor is started)
checkStartActors(ModelFactory.createSrfgProblemSet());
// using last requestId
getSolution(asyncResponse,lastRequestId);
}
public Integer checkStartActors(ProblemSet problemSet) {
if (ah == null) {
// reuse lastRequestId
synchronized (lastRequestId) {
lastRequestId = problemSet.hashCode();
FJSSTTproblem problem = ProblemParser.parseStrings(problemSet.getFjs(), problemSet.getProperties(), problemSet.getTransport());
// make sure we have the right ID!!
problem.setProblemId(lastRequestId);
log.info("problem set parsed (hash: {})", lastRequestId);
// do not wait for end result but take return the first one found =>
// false
ah = new ActorHelper(problem, problem.getConfigurations(), false);
}
}
return lastRequestId;
}
public Solution getSolution(AsyncResponse asyncResponse, Integer requestId) {
new Thread(new TriggerSolution(ah, requestId)).start();
synchronized (solutions) {
// we assuming - might be wrong - that this is about the last request
final Solution oldS = solutions.get(lastRequestId);
if (oldS != null)
asyncResponse.resume(oldS);
else
asyncResponse.resume(new Throwable("nothing found sofar :-( maybe a bit later"));
return oldS;
}
}
/**
* Method handling HTTP GET requests. The returned object will be sent to the
* client as "application/json" media type.
*
* @param problemSet:
* a problem set parsed from JSON input
* @return the SolutionSet, which can be parsed into a JSON Object
*/
@POST
@Path("/problem")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void calcSolution(final ProblemSet problemSet, @Suspended final AsyncResponse asyncResponse) throws InterruptedException {
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
if (throwable == null) {
// no throwable - the processing ended successfully
// (response already written to the client)
numberOfSuccessResponses++;
} else {
numberOfFailures++;
lastException = throwable;
}
}
});
lastRequestId = checkStartActors(problemSet);
// using last requestId
getSolution(asyncResponse,lastRequestId);
}
class TriggerSolution implements Runnable {
final Integer problemId;
final ActorHelper ah;
public TriggerSolution(final ActorHelper ah, final Integer problemId) {
this.problemId = problemId;
this.ah = ah;
}
@Override
public void run() {
SolutionReady sr = ah.getCurrentSolution(problemId);
// nothing found?
if (sr == null)
// this might cause problems on a slow or occupied server,
// starting the algo all the time (timeout is ~10secs)
// solve might return the first solution found or wait for the
// final result -> see last param in ActorHelper()
sr = ah.solve(500);
if (sr != null) {
// return a Solution object (not a SolutionSet)
solutions.put(problemId, sr.getMinUpperBoundSolution());
}
}
}
} |
package au.gov.ga.geodesy.domain.model;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Version;
import au.gov.ga.geodesy.igssitelog.domain.model.EffectiveDates;
@Entity
@Table(name = "NODE")
public class Node {
@Version
private Integer version;
/**
* RDBMS surrogate key
*/
@Id
@Column(name = "ID")
@GeneratedValue(generator = "surrogateKeyGenerator")
@SequenceGenerator(name = "surrogateKeyGenerator", sequenceName = "seq_surrogate_keys")
protected Integer id;
@Column(name = "SITE_ID", nullable = false)
private Integer siteId;
@Column(name = "SETUP_ID")
private Integer setupId;
@Embedded
private EffectiveDates effectivePeriod;
@SuppressWarnings("unused") // used by hibernate
private Node() {
}
public Node(Integer siteId, EffectiveDates p) {
setSiteId(siteId);
setEffectivePeriod(p);
}
public Node(Integer siteId, EffectiveDates p, Integer setupId) {
this(siteId, p);
setSetupId(setupId);
}
// TODO: public id
public Integer getId() {
return id;
}
public Integer getSiteId() {
return siteId;
}
public void setSiteId(Integer siteId) {
this.siteId = siteId;
}
public Integer getSetupId() {
return setupId;
}
public void setSetupId(Integer setupId) {
this.setupId = setupId;
}
public EffectiveDates getEffectivePeriod() {
return effectivePeriod;
}
private void setEffectivePeriod(EffectiveDates effectivePeriod) {
this.effectivePeriod = effectivePeriod;
}
} |
package br.edu.utfpr.recipes.dao;
import br.edu.utfpr.recipes.entidade.Receita;
import java.util.List;
import org.hibernate.Query;
/**
*
* @author mairieliw
*/
public class DaoReceita extends DaoGenerics<Receita> {
public DaoReceita() {
super.clazz = Receita.class;
}
public List<Receita> buscaReceitaPorIngredientes(List<String> nomesIngrediente) {
session = getsession();
String sql = "SELECT * "
+ "FROM Receita r "
+ "WHERE r.status = true "
+ "AND r.id IN ("
+ " select distinct i.receita_id from itemReceita i where i.ingrediente_id in ("
+ " select id from Ingrediente where nome = '" + nomesIngrediente.get(0) + "') "
+ ") ";
nomesIngrediente.remove(0);
for (String nomeIngrediente : nomesIngrediente) {
sql += " AND r.id IN ("
+ " select distinct i.receita_id from itemReceita i where i.ingrediente_id in ("
+ " select id from Ingrediente where nome = '" + nomeIngrediente + "') "
+ ") ";
}
Query query = session.createSQLQuery(sql).addEntity(Receita.class);
return query.list();
}
public List<Receita> buscaReceitaPorIngredientesEspecificos(List<String> nomesIngrediente) {
session = getsession();
String ingredientesSelecionados = " (select id from Ingrediente where nome = '" + nomesIngrediente.get(0) + "'";
nomesIngrediente.remove(0);
for (String nomeIngrediente : nomesIngrediente) {
ingredientesSelecionados += " or nome = '" + nomeIngrediente + "' ";
}
ingredientesSelecionados += ") ";
String sql = "SELECT * FROM Receita r "
+ "WHERE r.status = true AND r.id IN "
+ " (SELECT DISTINCT IR.receita_id FROM itemReceita IR "
+ " WHERE NOT EXISTS "
+ " (SELECT * FROM "
+ " (SELECT Ingrediente.id FROM Ingrediente "
+ " WHERE Ingrediente.id IN "
+ " " + ingredientesSelecionados + ") AS I "
+ " WHERE NOT EXISTS "
+ " (SELECT * FROM itemReceita IR2 "
+ " WHERE IR.receita_id = IR2.receita_id AND IR2.ingrediente_Id = I.id) "
+ ") AND r.id IN "
+ " (SELECT DISTINCT temp.id FROM "
+ " (SELECT r.id FROM Receita AS r, itemReceita AS ir "
+ " WHERE r.id = ir.receita_id "
+ " AND ir.ingrediente_id IN " + ingredientesSelecionados + ") AS temp "
+ " WHERE NOT EXISTS "
+ " (SELECT * FROM itemReceita AS it "
+ " WHERE it.ingrediente_id NOT IN " + ingredientesSelecionados
+ " AND temp.id=it.receita_id)"
+ " )"
+ ")";
Query query = session.createSQLQuery(sql).addEntity(Receita.class);
return query.list();
}
} |
package ca.wescook.nutrition.utility;
import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.effects.EffectsList;
import ca.wescook.nutrition.effects.JsonEffect;
import ca.wescook.nutrition.nutrients.JsonNutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import net.minecraftforge.common.config.Configuration;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class Config {
private static final Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();
// Public config values
public static boolean enableDecay;
public static float decayMultiplier;
public static int deathPenaltyMin;
public static int deathPenaltyLoss;
public static boolean allowOverEating;
public static int lossPerNutrient;
public static float nutritionMultiplier;
public static int startingNutrition;
public static boolean enableGui;
public static boolean enableGuiButton;
public static boolean enableTooltips;
public static boolean enableLogging;
// Categories
private static final String CATEGORY_NUTRITION = "Nutrition";
private static final String CATEGORY_DECAY = "Nutrition Decay";
private static final String CATEGORY_DEATH_PENALTY = "Death Penalty";
private static final String CATEGORY_GUI = "Gui";
private static final String CATEGORY_LOGGING = "Logging";
public static void registerConfigs(File configDirectory) {
// Register primary config
registerPrimaryConfig(configDirectory);
// Nutrients
List<String> nutrientFiles = Lists.newArrayList("dairy.json", "example.json", "fruit.json", "grain.json", "protein.json", "vegetable.json");
File nutrientDirectory = new File(configDirectory, Nutrition.MODID + "/nutrients");
createConfigurationDirectory("assets/nutrition/configs/nutrients", nutrientDirectory, nutrientFiles);
NutrientList.register(readConfigurationDirectory(JsonNutrient.class, nutrientDirectory));
// Effects
List<String> effectsFiles = Lists.newArrayList("example.json", "mining_fatigue.json", "resistance.json", "strength.json", "toughness.json", "weakness.json");
File effectsDirectory = new File(configDirectory, Nutrition.MODID + "/effects");
createConfigurationDirectory("assets/nutrition/configs/effects", effectsDirectory, effectsFiles);
EffectsList.register(readConfigurationDirectory(JsonEffect.class, effectsDirectory));
}
private static void registerPrimaryConfig(File configDirectory) {
// Create or load from file
Configuration configFile = new Configuration(new File(configDirectory.getPath() + "/nutrition/nutrition.cfg"));
configFile.load();
// Get Values
enableDecay = configFile.getBoolean("EnableDecay", CATEGORY_DECAY, true, "Enable nutrition decay when hunger drains.");
decayMultiplier = configFile.getFloat("DecayMultiplier", CATEGORY_DECAY, 1, 0, 100, "Value to multiply decay rate by (eg. 0.5 halves the rate, 2.0 doubles it).");
deathPenaltyMin = configFile.getInt("DeathPenaltyMin", CATEGORY_DEATH_PENALTY, 30, 0, 100, "The minimum nutrition value that the death penalty may reduce to.");
deathPenaltyLoss = configFile.getInt("DeathPenaltyLoss", CATEGORY_DEATH_PENALTY, 15, 0, 100, "The nutrition value subtracted from each nutrient upon death.");
nutritionMultiplier = configFile.getFloat("NutritionMultiplier", CATEGORY_NUTRITION, 1, 0, 100, "Value to multiply base nutrition by for each food (eg. 0.5 to halve nutrition gain).");
startingNutrition = configFile.getInt("StartingNutrition", CATEGORY_NUTRITION, 50, 0, 100, "The starting nutrition level for new players.");
lossPerNutrient = configFile.getInt("LossPerNutrient", CATEGORY_NUTRITION, 15, 0, 100,
"The nutrition value subtracted from foods per additional nutrient, as a percentage.\n" +
"This is to prevent large, complex foods from being too powerful.\n" +
"(eg. 1 nutrient = 0% loss, 2 nutrients = 15% loss, 3 nutrients = 30% loss)");
allowOverEating = configFile.getBoolean("AllowOverEating", CATEGORY_NUTRITION, false, "Allow player to continue eating even while full.\n" +
"This setting may upset balance, but is necessary for playing in peaceful mode.");
enableGui = configFile.getBoolean("EnableGui", CATEGORY_GUI, true, "If the nutrition GUI should be enabled");
enableGuiButton = configFile.getBoolean("EnableGuiButton", CATEGORY_GUI, true, "If the nutrition button should be shown on player inventory (hotkey will still function).");
enableTooltips = configFile.getBoolean("EnableTooltips", CATEGORY_GUI, true, "If foods should show their nutrients on hover.");
enableLogging = configFile.getBoolean("EnableLogging", CATEGORY_LOGGING, false, "Enable logging of missing or invalid foods.");
// Update file
if (configFile.hasChanged())
configFile.save();
}
// Copies files from internal resources to external files. Accepts an input resource path, output directory, and list of files
private static void createConfigurationDirectory(String inputDirectory, File outputDirectory, List<String> files) {
// Make no changes if directory already exists
if (outputDirectory.exists())
return;
// Create config directory
outputDirectory.mkdir();
// Copy each file over
ClassLoader loader = Thread.currentThread().getContextClassLoader(); // Can access resources via class loader
for (String file : files) {
try (InputStream inputStream = loader.getResourceAsStream(inputDirectory + "/" + file)) { // Get input stream of resource
Files.copy(inputStream, new File(outputDirectory + "/" + file).toPath()); // Create files from stream
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Reads in JSON as objects. Accepts object to serialize into, and directory to read json files. Returns array of JSON objects.
private static <T> List<T> readConfigurationDirectory(Class<T> classImport, File configDirectory) {
File[] files = configDirectory.listFiles(); // List json files
List<T> jsonObjectList = new ArrayList<>(); // List json objects
for (File file : files) {
if (FilenameUtils.isExtension(file.getName(), "json")) {
try {
JsonReader jsonReader = new JsonReader(new FileReader(file)); // Read in JSON
jsonObjectList.add(gson.fromJson(jsonReader, classImport)); // Deserialize with GSON and store for later processing
} catch (IOException | com.google.gson.JsonSyntaxException e) {
Log.fatal("The file " + file.getName() + " has invalid JSON and could not be loaded.");
throw new IllegalArgumentException("Unable to load " + file.getName() + ". Is the JSON valid?", e);
}
}
}
return jsonObjectList;
}
} |
package com.cisco.trex.stateless;
import com.cisco.trex.stateless.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import org.pcap4j.packet.*;
import org.pcap4j.packet.namednumber.*;
import org.pcap4j.util.ByteArrays;
import org.pcap4j.util.MacAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.ZMQException;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class TRexClient {
private static final Logger logger = LoggerFactory.getLogger(TRexClient.class);
private static String JSON_RPC_VERSION = "2.0";
private static Integer API_VERSION_MAJOR = 3;
private static Integer API_VERSION_MINOR = 0;
private TRexTransport transport;
private Gson gson = new Gson();
private String host;
private String port;
private String asyncPort;
private String api_h;
private String userName = "";
private Integer session_id = 123456789;
private Map<Integer, String> portHandlers = new HashMap<>();
private List<String> supportedCmds = new ArrayList<>();
public TRexClient(String host, String port, String userName) {
this.host = host;
this.port = port;
this.userName = userName;
supportedCmds.add("api_sync");
supportedCmds.add("get_supported_cmds");
}
public String callMethod(String methodName, Map<String, Object> payload) {
logger.info("Call {} method.", methodName);
if (!supportedCmds.contains(methodName)) {
logger.error("Unsupported {} method.", methodName);
throw new UnsupportedOperationException();
}
String req = buildRequest(methodName, payload);
return call(req);
}
private String buildRequest(String methodName, Map<String, Object> payload) {
if (payload == null) {
payload = new HashMap<>();
}
Map<String, Object> parameters = new HashMap<>();
parameters.put("id", "aggogxls");
parameters.put("jsonrpc", JSON_RPC_VERSION);
parameters.put("method", methodName);
payload.put("api_h", api_h);
parameters.put("params", payload);
return gson.toJson(parameters);
}
private String call(String json) {
logger.info("JSON Req: " + json);
byte[] msg = transport.sendJson(json);
if (msg == null) {
int errNumber = transport.getSocket().base().errno();
String errMsg = "Unable to receive message from socket";
ZMQException zmqException = new ZMQException(errMsg, errNumber);
logger.error(errMsg, zmqException);
throw zmqException;
}
String response = new String(msg);
logger.info("JSON Resp: " + response);
return response;
}
public <T> TRexClientResult<T> callMethod(String methodName, Map<String, Object> parameters, Class<T> responseType) {
logger.info("Call {} method.", methodName);
if (!supportedCmds.contains(methodName)) {
logger.error("Unsupported {} method.", methodName);
throw new UnsupportedOperationException();
}
TRexClientResult<T> result = new TRexClientResult<>();
try {
RPCResponse response = transport.sendCommand(buildCommand(methodName, parameters));
if (!response.isFailed()) {
T resutlObject = new ObjectMapper().readValue(response.getResult(), responseType);
result.set(resutlObject);
} else {
result.setError(response.getError().getMessage());
}
} catch (IOException e) {
String errorMsg = "Error occurred during processing '"+methodName+"' method with params: " +parameters.toString();
logger.error(errorMsg, e);
result.setError(errorMsg);
return result;
}
return result;
}
private TRexCommand buildCommand(String methodName, Map<String, Object> parameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put("api_h", api_h);
Map<String, Object> payload = new HashMap<>();
payload.put("id", "aggogxls");
payload.put("jsonrpc", JSON_RPC_VERSION);
payload.put("method", methodName);
if(parameters.containsKey("port_id")) {
Integer portId = (Integer) parameters.get("port_id");
String handler = portHandlers.get(portId);
if (handler != null) {
parameters.put("handler", handler);
}
}
payload.put("params", parameters);
return new TRexCommand(methodName, payload);
}
public void connect() {
transport = new TRexTransport(this.host, this.port, 3000);
serverAPISync();
supportedCmds.addAll(getSupportedCommands());
}
private String getConnectionAddress() {
return "tcp://"+host+":"+port;
}
private void serverAPISync() {
logger.info("Sync API with the TRex");
Map<String, Object> apiVers = new HashMap<>();
apiVers.put("type", "core");
apiVers.put("major", API_VERSION_MAJOR);
apiVers.put("minor", API_VERSION_MINOR);
Map<String, Object> parameters = new HashMap<>();
parameters.put("api_vers", Arrays.asList(apiVers));
TRexClientResult<ApiVersion> result = callMethod("api_sync", parameters, ApiVersion.class);
api_h = result.get().getApi_h();
logger.info("Received api_H: {}", api_h);
}
public void disconnect() {
if (transport != null) {
transport.getSocket().close();
transport = null;
logger.info("Disconnected");
} else {
logger.info("Already disconnected");
}
}
public void reconnect() {
disconnect();
connect();
}
// TODO: move to upper layer
public List<Port> getPorts() {
logger.info("Getting ports list.");
List<Port> ports = getSystemInfo().getPorts();
ports.stream().forEach(port -> {
TRexClientResult<PortStatus> result = getPortStatus(port.getIndex());
if (result.isFailed()) {
return;
}
PortStatus status = result.get();
L2Configuration l2config = status.getAttr().getLayerConiguration().getL2Configuration();
port.hw_mac = l2config.getSrc();
port.dst_macaddr = l2config.getDst();
});
return ports;
}
public TRexClientResult<PortStatus> getPortStatus(int portIdx) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("port_id", portIdx);
return callMethod("get_port_status", parameters, PortStatus.class);
}
public PortStatus acquirePort(int portIndex, Boolean force) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("session_id", session_id);
payload.put("user", userName);
payload.put("force", force);
String json = callMethod("acquire", payload);
JsonElement response = new JsonParser().parse(json);
String handler = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsString();
portHandlers.put(portIndex, handler);
return getPortStatus(portIndex).get();
}
public void resetPort(int portIndex) {
acquirePort(portIndex, true);
stopTraffic(portIndex);
removeAllStreams(portIndex);
removeRxQueue(portIndex);
serviceMode(portIndex, false);
releasePort(portIndex);
}
private Map<String, Object> createPayload(int portIndex) {
Map<String, Object> payload = new HashMap<>();
payload.put("port_id", portIndex);
payload.put("api_h", api_h);
String handler = portHandlers.get(portIndex);
if (handler != null) {
payload.put("handler", handler);
}
return payload;
}
public PortStatus releasePort(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("user", userName);
String result = callMethod("release", payload);
portHandlers.remove(portIndex);
return getPortStatus(portIndex).get();
}
public List<String> getSupportedCommands() {
Map<String, Object> payload = new HashMap<>();
payload.put("api_h", api_h);
String json = callMethod("get_supported_cmds", payload);
JsonElement response = new JsonParser().parse(json);
JsonArray cmds = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray();
return StreamSupport.stream(cmds.spliterator(), false)
.map(JsonElement::getAsString)
.collect(Collectors.toList());
}
public PortStatus serviceMode(int portIndex, Boolean isOn) {
logger.info("Set service mode : {}", isOn ? "on" : "off");
Map<String, Object> payload = createPayload(portIndex);
payload.put("enabled", isOn);
String result = callMethod("service", payload);
return getPortStatus(portIndex).get();
}
public void addStream(int portIndex, Stream stream) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_id", stream.getId());
payload.put("stream", stream);
callMethod("add_stream", payload);
}
public Stream getStream(int portIndex, int streamId) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("get_pkt", true);
payload.put("stream_id", streamId);
String json = callMethod("get_stream", payload);
JsonElement response = new JsonParser().parse(json);
JsonObject stream = response.getAsJsonArray().get(0)
.getAsJsonObject().get("result")
.getAsJsonObject().get("stream")
.getAsJsonObject();
return gson.fromJson(stream, Stream.class);
}
public void removeStream(int portIndex, int streamId) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("stream_id", streamId);
callMethod("remove_stream", payload);
}
public void removeAllStreams(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
callMethod("remove_all_streams", payload);
}
public List<Integer> getStreamIds(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
String json = callMethod("get_stream_list", payload);
JsonElement response = new JsonParser().parse(json);
JsonArray ids = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray();
return StreamSupport.stream(ids.spliterator(), false)
.map(JsonElement::getAsInt)
.collect(Collectors.toList());
}
public SystemInfo getSystemInfo() {
String json = callMethod("get_system_info", null);
SystemInfoResponse response = gson.fromJson(json, SystemInfoResponse[].class)[0];
return response.getResult();
}
public void startTraffic(int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("core_mask", coreMask);
payload.put("mul", mul);
payload.put("duration", duration);
payload.put("force", force);
callMethod("start_traffic", payload);
}
public void setRxQueue(int portIndex, int size) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("type", "queue");
payload.put("enabled", true);
payload.put("size", size);
callMethod("set_rx_feature", payload);
}
public void removeRxQueue(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("type", "queue");
payload.put("enabled", false);
callMethod("set_rx_feature", payload);
}
public void sendPacket(int portIndex, Packet pkt) {
Stream stream = build1PktSingleBurstStream(pkt);
removeAllStreams(portIndex);
addStream(portIndex, stream);
Map<String, Object> mul = new HashMap<>();
mul.put("op", "abs");
mul.put("type", "pps");
mul.put("value", 1.0);
startTraffic(portIndex, 1, true, mul, 1);
stopTraffic(portIndex);
}
public String resolveArp(int portIndex, String srcIp, String dstIp) {
removeRxQueue(portIndex);
setRxQueue(portIndex, 1000);
String srcMac = getPorts().get(portIndex).hw_mac;
EthernetPacket pkt = buildArpPkt(srcMac, srcIp, dstIp);
sendPacket(portIndex, pkt);
Predicate<EthernetPacket> arpReplyFilter = etherPkt -> {
if(etherPkt.contains(ArpPacket.class)) {
ArpPacket arp = (ArpPacket) etherPkt.getPayload();
ArpOperation arpOp = arp.getHeader().getOperation();
String replyDstMac = arp.getHeader().getDstHardwareAddr().toString();
return ArpOperation.REPLY.equals(arpOp) && replyDstMac.equals(srcMac);
}
return false;
};
List<org.pcap4j.packet.Packet> pkts = new ArrayList<>();
try {
int steps = 10;
while (steps > 0) {
steps -= 1;
Thread.sleep(500);
pkts.addAll(getRxQueue(portIndex, arpReplyFilter));
if(pkts.size() > 0) {
ArpPacket arpPacket = (ArpPacket) pkts.get(0).getPayload();
return arpPacket.getHeader().getSrcHardwareAddr().toString();
}
}
logger.info("Unable to get ARP reply in {} seconds", steps);
} catch (InterruptedException ignored) {}
finally {
removeRxQueue(portIndex);
}
return null;
}
private static EthernetPacket buildArpPkt(String srcMac, String srcIp, String dstIp) {
ArpPacket.Builder arpBuilder = new ArpPacket.Builder();
MacAddress srcMacAddress = MacAddress.getByName(srcMac);
try {
arpBuilder
.hardwareType(ArpHardwareType.ETHERNET)
.protocolType(EtherType.IPV4)
.hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES)
.protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES)
.operation(ArpOperation.REQUEST)
.srcHardwareAddr(srcMacAddress)
.srcProtocolAddr(InetAddress.getByName(srcIp))
.dstHardwareAddr(MacAddress.getByName("00:00:00:00:00:00"))
.dstProtocolAddr(InetAddress.getByName(dstIp));
} catch (UnknownHostException e) {
throw new IllegalArgumentException(e);
}
EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
etherBuilder.dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS)
.srcAddr(srcMacAddress)
.type(EtherType.ARP)
.payloadBuilder(arpBuilder)
.paddingAtBuild(true);
return etherBuilder.build();
}
private Stream build1PktSingleBurstStream(Packet pkt) {
int stream_id = (int) (Math.random() * 1000);
return new Stream(
stream_id,
true,
3,
0.0,
new StreamMode(
1,
1,
1,
1.0,
new StreamModeRate(
StreamModeRate.Type.pps,
1.0
),
StreamMode.Type.single_burst
),
-1,
pkt,
new StreamRxStats(true, true, true, stream_id),
new StreamVM("", Collections.<VMInstruction>emptyList()),
true
);
}
public List<Packet> getRxQueue(int portIndex, Predicate<EthernetPacket> filter) {
Map<String, Object> payload = createPayload(portIndex);
String json = callMethod("get_rx_queue_pkts", payload);
JsonElement response = new JsonParser().parse(json);
JsonArray pkts = response.getAsJsonArray().get(0)
.getAsJsonObject().get("result")
.getAsJsonObject()
.getAsJsonArray("pkts");
return StreamSupport.stream(pkts.spliterator(), false)
.map(this::buildEthernetPkt)
.filter(filter)
.collect(Collectors.toList());
}
private EthernetPacket buildEthernetPkt(JsonElement jsonElement) {
try {
byte[] binary = Base64.getDecoder().decode(jsonElement.getAsJsonObject().get("binary").getAsString());
EthernetPacket pkt = EthernetPacket.newPacket(binary, 0, binary.length);
logger.info("Received pkt: {}", pkt.toString());
return pkt;
} catch (IllegalRawDataException e) {
return null;
}
}
public boolean setL3Mode(int portIndex, String nextHopMac, String sourceIp, String destinationIp) {
Map<String, Object> payload = createPayload(portIndex);
payload.put("src_addr", sourceIp);
payload.put("dst_addr", destinationIp);
if (nextHopMac != null) {
payload.put("resolved_mac", nextHopMac);
}
callMethod("set_l3", payload);
return true;
}
public void updatePortHandler(int portID, String handler) {
portHandlers.put(portID, handler);
}
public void invalidatePortHandler(int portID) {
portHandlers.remove(portID);
}
// TODO: move to upper layer
public EthernetPacket sendIcmpEcho(int portIndex, String host, int reqId, int seqNumber, long waitResponse) throws UnknownHostException {
Port port = getPorts().get(portIndex);
PortStatus portStatus = getPortStatus(portIndex).get();
String srcIp = portStatus.getAttr().getLayerConiguration().getL3Configuration().getSrc();
EthernetPacket icmpRequest = buildIcmpV4Request(port.hw_mac, port.dst_macaddr, srcIp, host, reqId, seqNumber);
removeAllStreams(portIndex);
setRxQueue(portIndex, 1000);
sendPacket(portIndex, icmpRequest);
try {
Thread.sleep(waitResponse);
} catch (InterruptedException ignored) {}
try {
List<Packet> receivedPkts = getRxQueue(portIndex, etherPkt -> etherPkt.contains(IcmpV4EchoReplyPacket.class));
if (!receivedPkts.isEmpty()) {
return (EthernetPacket) receivedPkts.get(0);
}
return null;
} finally {
removeRxQueue(portIndex);
}
}
// TODO: move to upper layer
private EthernetPacket buildIcmpV4Request(String srcMac, String dstMac, String srcIp, String dstIp, int reqId, int seqNumber) throws UnknownHostException {
IcmpV4EchoPacket.Builder icmpReqBuilder = new IcmpV4EchoPacket.Builder();
icmpReqBuilder.identifier((short) reqId);
icmpReqBuilder.sequenceNumber((short) seqNumber);
IcmpV4CommonPacket.Builder icmpv4CommonPacketBuilder = new IcmpV4CommonPacket.Builder();
icmpv4CommonPacketBuilder.type(IcmpV4Type.ECHO)
.code(IcmpV4Code.NO_CODE)
.correctChecksumAtBuild(true)
.payloadBuilder(icmpReqBuilder);
IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder();
ipv4Builder.version(IpVersion.IPV4)
.tos(IpV4Rfc791Tos.newInstance((byte) 0))
.ttl((byte) 64)
.protocol(IpNumber.ICMPV4)
.srcAddr((Inet4Address) Inet4Address.getByName(srcIp))
.dstAddr((Inet4Address) Inet4Address.getByName(dstIp))
.correctChecksumAtBuild(true)
.correctLengthAtBuild(true)
.payloadBuilder(icmpv4CommonPacketBuilder);
EthernetPacket.Builder eb = new EthernetPacket.Builder();
eb.srcAddr(MacAddress.getByName(srcMac))
.dstAddr(MacAddress.getByName(dstMac))
.type(EtherType.IPV4)
.paddingAtBuild(true)
.payloadBuilder(ipv4Builder);
return eb.build();
}
public void stopTraffic(int portIndex) {
Map<String, Object> payload = createPayload(portIndex);
callMethod("stop_traffic", payload);
}
private class ApiVersionResponse {
private String id;
private String jsonrpc;
private ApiVersionResult result;
private class ApiVersionResult {
private List<Map<String, String>> api_vers;
public ApiVersionResult(List<Map<String, String>> api_vers) {
this.api_vers = api_vers;
}
public String getApi_h() {
return api_vers.get(0).get("api_h");
}
}
public ApiVersionResponse(String id, String jsonrpc, ApiVersionResult result) {
this.id = id;
this.jsonrpc = jsonrpc;
this.result = result;
}
public String getApi_h() {
return result.getApi_h();
}
}
private class SystemInfoResponse {
private String id;
private String jsonrpc;
private SystemInfo result;
public SystemInfo getResult() {
return result;
}
}
} |
package com.codeborne.selenide;
import static com.codeborne.selenide.ClickMethod.DEFAULT;
import static com.codeborne.selenide.ClickMethod.JS;
public class ClickOptions {
private final int offsetX;
private final int offsetY;
private final ClickMethod clickMethod;
private ClickOptions(ClickMethod clickMethod, int offsetX, int offsetY) {
this.clickMethod = clickMethod;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
public static ClickOptions usingDefaultMethod() {
return new ClickOptions(DEFAULT, 0, 0);
}
public static ClickOptions usingJavaScript() {
return new ClickOptions(JS, 0, 0);
}
public int offsetX() {
return offsetX;
}
public int offsetY() {
return offsetY;
}
public ClickMethod clickOption() {
return clickMethod;
}
public ClickOptions offsetX(int offsetX) {
return new ClickOptions(clickMethod, offsetX, offsetY);
}
public ClickOptions offsetY(int offsetY) {
return new ClickOptions(clickMethod, offsetX, offsetY);
}
public ClickOptions offset(int offsetX, int offsetY) {
return new ClickOptions(clickMethod, offsetX, offsetY);
}
} |
package com.comandante.creeper;
import com.comandante.creeper.Items.*;
import com.comandante.creeper.entity.EntityManager;
import com.comandante.creeper.managers.GameManager;
import com.comandante.creeper.merchant.*;
import com.comandante.creeper.merchant.GrimulfWizard;
import com.comandante.creeper.npc.Npc;
import com.comandante.creeper.npc.NpcExporter;
import com.comandante.creeper.spawner.ItemSpawner;
import com.comandante.creeper.spawner.NpcSpawner;
import com.comandante.creeper.spawner.SpawnRule;
import com.comandante.creeper.spawner.SpawnRuleBuilder;
import com.comandante.creeper.spells.*;
import com.comandante.creeper.world.Area;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ConfigureNpc {
public static void configureAllNpcs(GameManager gameManager) throws FileNotFoundException {
EntityManager entityManager = gameManager.getEntityManager();
List<Npc> npcsFromFile = NpcExporter.getNpcsFromFile(gameManager);
for (Npc npc: npcsFromFile) {
Main.startUpMessage("Added " + npc.getName());
entityManager.addEntity(npc);
Set<SpawnRule> spawnRules = npc.getSpawnRules();
for (SpawnRule spawnRule: spawnRules) {
entityManager.addEntity(new NpcSpawner(npc, gameManager, spawnRule));
}
}
}
public static void configure(EntityManager entityManager, GameManager gameManager) throws FileNotFoundException {
configureAllNpcs(gameManager);
Main.startUpMessage("Adding beer");
ItemSpawner itemSpawner = new ItemSpawner(ItemType.BEER, new SpawnRuleBuilder().setArea(Area.NEWBIE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(100).setMaxPerRoom(5).setRandomPercent(40).createSpawnRule(), gameManager);
ItemSpawner itemSpawner1 = new ItemSpawner(ItemType.BEER, new SpawnRuleBuilder().setArea(Area.FANCYHOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(12).setMaxPerRoom(2).setRandomPercent(50).createSpawnRule(), gameManager);
ItemSpawner itemSpawner2 = new ItemSpawner(ItemType.BEER, new SpawnRuleBuilder().setArea(Area.HOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(12).setMaxPerRoom(2).setRandomPercent(50).createSpawnRule(), gameManager);
ItemSpawner itemSpawner3 = new ItemSpawner(ItemType.PURPLE_DRANK, new SpawnRuleBuilder().setArea(Area.FANCYHOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(30).setMaxPerRoom(5).setRandomPercent(50).createSpawnRule(), gameManager);
ItemSpawner itemSpawner4 = new ItemSpawner(ItemType.PURPLE_DRANK, new SpawnRuleBuilder().setArea(Area.HOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(30).setMaxPerRoom(5).setRandomPercent(50).createSpawnRule(), gameManager);
ItemSpawner itemSpawner5 = new ItemSpawner(ItemType.KEY, new SpawnRuleBuilder().setArea(Area.LOBBY).setSpawnIntervalTicks(600).setMaxInstances(1).setMaxPerRoom(1).setRandomPercent(5).createSpawnRule(), gameManager);
entityManager.addEntity(itemSpawner);
entityManager.addEntity(itemSpawner1);
entityManager.addEntity(itemSpawner2);
entityManager.addEntity(itemSpawner3);
entityManager.addEntity(itemSpawner4);
entityManager.addEntity(itemSpawner5);
Map<Integer, MerchantItemForSale> itemsForSale = Maps.newLinkedHashMap();
itemsForSale.put(1, new MerchantItemForSale(ItemType.BEER, 8));
itemsForSale.put(2, new MerchantItemForSale(ItemType.PURPLE_DRANK, 80));
itemsForSale.put(3, new MerchantItemForSale(ItemType.LEATHER_SATCHEL, 25000));
itemsForSale.put(4, new MerchantItemForSale(ItemType.BIGGERS_SKIN_SATCHEL, 250000));
itemsForSale.put(5, new MerchantItemForSale(ItemType.STRENGTH_ELIXIR, 2000));
itemsForSale.put(6, new MerchantItemForSale(ItemType.CHRONIC_JOOSE, 4000));
itemsForSale.put(7, new MerchantItemForSale(ItemType.GUCCI_PANTS, 80000000));
LloydBartender lloydBartender = new LloydBartender(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), itemsForSale);
gameManager.getRoomManager().addMerchant(64, lloydBartender);
Map<Integer, MerchantItemForSale> nigelForSale = Maps.newLinkedHashMap();
nigelForSale.put(1, new MerchantItemForSale(ItemType.BEER, 6));
NigelBartender nigelBartender = new NigelBartender(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), nigelForSale);
gameManager.getRoomManager().addMerchant(377, nigelBartender);
Map<Integer, MerchantItemForSale> blacksmithItems = Maps.newHashMap();
blacksmithItems.put(1, new MerchantItemForSale(ItemType.BROAD_SWORD, 1000));
blacksmithItems.put(2, new MerchantItemForSale(ItemType.IRON_BOOTS, 800));
blacksmithItems.put(3, new MerchantItemForSale(ItemType.IRON_BRACERS, 400));
blacksmithItems.put(4, new MerchantItemForSale(ItemType.IRON_HELMET, 500));
blacksmithItems.put(5, new MerchantItemForSale(ItemType.IRON_CHEST_PLATE, 1500));
blacksmithItems.put(6, new MerchantItemForSale(ItemType.IRON_LEGGINGS, 1100));
blacksmithItems.put(7, new MerchantItemForSale(ItemType.PHANTOM_SWORD, 7000));
blacksmithItems.put(8, new MerchantItemForSale(ItemType.PHANTOM_HELMET, 3500));
blacksmithItems.put(9, new MerchantItemForSale(ItemType.PHANTOM_BOOTS, 3000));
blacksmithItems.put(10, new MerchantItemForSale(ItemType.PHANTOM_BRACERS, 1500));
blacksmithItems.put(11, new MerchantItemForSale(ItemType.PHANTOM_LEGGINGS, 4000));
blacksmithItems.put(12, new MerchantItemForSale(ItemType.MITHRIL_SWORD, 14000));
blacksmithItems.put(13, new MerchantItemForSale(ItemType.MITHRIL_HELMET, 7000));
blacksmithItems.put(14, new MerchantItemForSale(ItemType.MITHRIL_CHESTPLATE, 10000));
blacksmithItems.put(15, new MerchantItemForSale(ItemType.MITHRIL_BOOTS, 6000));
blacksmithItems.put(16, new MerchantItemForSale(ItemType.MITHRIL_BRACERS, 4000));
blacksmithItems.put(17, new MerchantItemForSale(ItemType.MITHRIL_LEGGINGS, 8000));
blacksmithItems.put(18, new MerchantItemForSale(ItemType.PYAMITE_SWORD, 20000));
blacksmithItems.put(19, new MerchantItemForSale(ItemType.PYAMITE_HELMET, 14000));
blacksmithItems.put(20, new MerchantItemForSale(ItemType.PYAMITE_CHESTPLATE, 20000));
blacksmithItems.put(21, new MerchantItemForSale(ItemType.PYAMITE_BOOTS, 12000));
blacksmithItems.put(22, new MerchantItemForSale(ItemType.PYAMITE_BRACERS, 8000));
blacksmithItems.put(23, new MerchantItemForSale(ItemType.PYAMITE_LEGGINGS, 16000));
blacksmithItems.put(24, new MerchantItemForSale(ItemType.VULCERIUM_SWORD, 160000));
blacksmithItems.put(25, new MerchantItemForSale(ItemType.VULCERIUM_HELMET, 37000));
blacksmithItems.put(26, new MerchantItemForSale(ItemType.VULCERIUM_CHESTPLATE, 52000));
blacksmithItems.put(27, new MerchantItemForSale(ItemType.VULCERIUM_BOOTS, 38000));
blacksmithItems.put(28, new MerchantItemForSale(ItemType.VULCERIUM_BRACERS, 29000));
blacksmithItems.put(29, new MerchantItemForSale(ItemType.VULCERIUM_LEGGINGS, 52000));
blacksmithItems.put(30, new MerchantItemForSale(ItemType.BISMUTH_SWORD, 3000000));
blacksmithItems.put(31, new MerchantItemForSale(ItemType.BISMUTH_HELMET, 2400000));
blacksmithItems.put(32, new MerchantItemForSale(ItemType.LEATHER_SATCHEL, 25000));
Map<Integer, MerchantItemForSale> grimulfItems = Maps.newHashMap();
grimulfItems.put(1, new MerchantItemForSale(ItemType.MARIJUANA, 100));
grimulfItems.put(2, new MerchantItemForSale(ItemType.TAPPERHET_SWORD, 60000));
grimulfItems.put(3, new MerchantItemForSale(ItemType.BIGGERS_SKIN_SATCHEL, 250000));
grimulfItems.put(4, new MerchantItemForSale(ItemType.DWARF_BOOTS_OF_AGILITY, 10000));
// grimulfItems.put(5, new MerchantItemForSale(ItemType.GOLDEN_WAND, 4000000000));
grimulfItems.put(5, new MerchantItemForSale(ItemType.MITHAEM_LEAF, 1400000000));
Map<Integer, MerchantItemForSale> ketilItems = Maps.newHashMap();
ketilItems.put(1, new MerchantItemForSale(ItemType.BEER, 12));
ketilItems.put(2, new MerchantItemForSale(ItemType.PURPLE_DRANK, 120));
ketilItems.put(3, new MerchantItemForSale(ItemType.MARIJUANA, 100));
ketilItems.put(4, new MerchantItemForSale(ItemType.PYAMITE_ICEAXE, 10000000));
ketilItems.put(5, new MerchantItemForSale(ItemType.STRENGTH_ELIXIR, 3000));
ketilItems.put(6, new MerchantItemForSale(ItemType.CHRONIC_JOOSE, 5500));
Blacksmith blacksmith = new Blacksmith(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), blacksmithItems);
gameManager.getRoomManager().addMerchant(66, blacksmith);
gameManager.getRoomManager().addMerchant(253, blacksmith);
JimBanker jimBanker = new JimBanker(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), null);
gameManager.getRoomManager().addMerchant(65, jimBanker);
gameManager.getRoomManager().addMerchant(209, jimBanker);
LockerRoomGuy lockerRoomGuy = new LockerRoomGuy(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), null);
gameManager.getRoomManager().addMerchant(63, lockerRoomGuy);
GrimulfWizard grimulfWizard = new GrimulfWizard(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), grimulfItems);
gameManager.getRoomManager().addMerchant(102, grimulfWizard);
KetilCommissary ketilCommissary = new KetilCommissary(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), ketilItems);
gameManager.getRoomManager().addMerchant(420, ketilCommissary);
ForageBuilder marijuanaForageBuilder = new ForageBuilder();
marijuanaForageBuilder.setItemType(ItemType.MARIJUANA);
marijuanaForageBuilder.setMinAmt(1);
marijuanaForageBuilder.setMaxAmt(3);
marijuanaForageBuilder.setPctOfSuccess(40);
marijuanaForageBuilder.setForageExperience(4);
marijuanaForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.WESTERN9_ZONE, marijuanaForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH3_ZONE, marijuanaForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE2_ZONE, marijuanaForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE1_ZONE, marijuanaForageBuilder);
ForageBuilder hazeForageBuilder = new ForageBuilder();
hazeForageBuilder.setItemType(ItemType.HAZE);
hazeForageBuilder.setMinAmt(1);
hazeForageBuilder.setMaxAmt(3);
hazeForageBuilder.setPctOfSuccess(5);
hazeForageBuilder.setForageExperience(10);
hazeForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE8_ZONE, hazeForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE9_ZONE, hazeForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE10_ZONE, hazeForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH12_ZONE, hazeForageBuilder);
gameManager.getForageManager().addForageToArea(Area.SOUTH2_ZONE, hazeForageBuilder);
gameManager.getForageManager().addForageToArea(Area.SOUTH3_ZONE, hazeForageBuilder);
gameManager.getForageManager().addForageToArea(Area.SOUTH4_ZONE, hazeForageBuilder);
ForageBuilder aexirianForageBuilder = new ForageBuilder();
aexirianForageBuilder.setItemType(ItemType.AEXIRIAN_ROOT);
aexirianForageBuilder.setMinAmt(1);
aexirianForageBuilder.setMaxAmt(3);
aexirianForageBuilder.setPctOfSuccess(5);
aexirianForageBuilder.setForageExperience(10);
aexirianForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.WESTERN4_ZONE, aexirianForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN5_ZONE, aexirianForageBuilder);
ForageBuilder mithaemForageBuilder = new ForageBuilder();
mithaemForageBuilder.setItemType(ItemType.MITHAEM_LEAF);
mithaemForageBuilder.setMinAmt(1);
mithaemForageBuilder.setMaxAmt(3);
mithaemForageBuilder.setPctOfSuccess(5);
mithaemForageBuilder.setForageExperience(10);
mithaemForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.TISLAND3_ZONE, mithaemForageBuilder);
gameManager.getForageManager().addForageToArea(Area.TISLAND4_ZONE, mithaemForageBuilder);
ForageBuilder duriccaForageBuilder = new ForageBuilder();
duriccaForageBuilder.setItemType(ItemType.DURICCA_ROOT);
duriccaForageBuilder.setMinAmt(1);
duriccaForageBuilder.setMaxAmt(3);
duriccaForageBuilder.setPctOfSuccess(5);
duriccaForageBuilder.setForageExperience(10);
duriccaForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.TOFT1_ZONE, duriccaForageBuilder);
gameManager.getForageManager().addForageToArea(Area.TOFT2_ZONE, duriccaForageBuilder);
ForageBuilder pondeselForageBuilder = new ForageBuilder();
pondeselForageBuilder.setItemType(ItemType.PONDESEL_BERRY);
pondeselForageBuilder.setMinAmt(1);
pondeselForageBuilder.setMaxAmt(3);
pondeselForageBuilder.setPctOfSuccess(5);
pondeselForageBuilder.setForageExperience(10);
pondeselForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.TISLAND6_ZONE, pondeselForageBuilder);
gameManager.getForageManager().addForageToArea(Area.TISLAND7_ZONE, pondeselForageBuilder);
ForageBuilder vikalionusForageBuilder = new ForageBuilder();
vikalionusForageBuilder.setItemType(ItemType.VIKALIONUS_CAP);
vikalionusForageBuilder.setMinAmt(1);
vikalionusForageBuilder.setMaxAmt(3);
vikalionusForageBuilder.setPctOfSuccess(5);
vikalionusForageBuilder.setForageExperience(10);
vikalionusForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.NORTH12_ZONE, vikalionusForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH13_ZONE, vikalionusForageBuilder);
ForageBuilder loornsForageBuilder = new ForageBuilder();
loornsForageBuilder.setItemType(ItemType.LOORNS_LACE);
loornsForageBuilder.setMinAmt(1);
loornsForageBuilder.setMaxAmt(3);
loornsForageBuilder.setPctOfSuccess(5);
loornsForageBuilder.setForageExperience(10);
loornsForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE4_ZONE, loornsForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE5_ZONE, loornsForageBuilder);
ForageBuilder tournearesForageBuilder = new ForageBuilder();
tournearesForageBuilder.setItemType(ItemType.TOURNEARES_LEAF);
tournearesForageBuilder.setMinAmt(1);
tournearesForageBuilder.setMaxAmt(3);
tournearesForageBuilder.setPctOfSuccess(5);
tournearesForageBuilder.setForageExperience(10);
tournearesForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE6_ZONE, tournearesForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE7_ZONE, tournearesForageBuilder);
ForageBuilder haussianForageBuilder = new ForageBuilder();
haussianForageBuilder.setItemType(ItemType.HAUSSIAN_BERRY);
haussianForageBuilder.setMinAmt(1);
haussianForageBuilder.setMaxAmt(3);
haussianForageBuilder.setPctOfSuccess(5);
haussianForageBuilder.setForageExperience(10);
haussianForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.WESTERN2_ZONE, haussianForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN3_ZONE, haussianForageBuilder);
ForageBuilder pertilliumForageBuilder = new ForageBuilder();
pertilliumForageBuilder.setItemType(ItemType.PERTILLIUM_ROOT);
pertilliumForageBuilder.setMinAmt(1);
pertilliumForageBuilder.setMaxAmt(3);
pertilliumForageBuilder.setPctOfSuccess(5);
pertilliumForageBuilder.setForageExperience(10);
pertilliumForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.WESTERN4_ZONE, pertilliumForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN5_ZONE, pertilliumForageBuilder);
ForageBuilder hycianthisForageBuilder = new ForageBuilder();
hycianthisForageBuilder.setItemType(ItemType.HYCIANTHIS_BARK);
hycianthisForageBuilder.setMinAmt(1);
hycianthisForageBuilder.setMaxAmt(3);
hycianthisForageBuilder.setPctOfSuccess(5);
hycianthisForageBuilder.setForageExperience(10);
hycianthisForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.NORTH10_ZONE, hycianthisForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH11_ZONE, hycianthisForageBuilder);
ForageBuilder punilareForageBuilder = new ForageBuilder();
punilareForageBuilder.setItemType(ItemType.PUNILARE_FERN);
punilareForageBuilder.setMinAmt(1);
punilareForageBuilder.setMaxAmt(3);
punilareForageBuilder.setPctOfSuccess(5);
punilareForageBuilder.setForageExperience(10);
punilareForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.SOUTH1_ZONE, punilareForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE14_ZONE, punilareForageBuilder);
ForageBuilder keakiarForageBuilder = new ForageBuilder();
keakiarForageBuilder.setItemType(ItemType.KEAKIAR_CAP);
keakiarForageBuilder.setMinAmt(1);
keakiarForageBuilder.setMaxAmt(3);
keakiarForageBuilder.setPctOfSuccess(5);
keakiarForageBuilder.setForageExperience(10);
keakiarForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE15_ZONE, keakiarForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH14_ZONE, keakiarForageBuilder);
ForageBuilder dirtyBombForageBuilder = new ForageBuilder();
dirtyBombForageBuilder.setItemType(ItemType.DIRTY_BOMB);
dirtyBombForageBuilder.setMinAmt(1);
dirtyBombForageBuilder.setMaxAmt(3);
dirtyBombForageBuilder.setPctOfSuccess(2);
dirtyBombForageBuilder.setForageExperience(100);
dirtyBombForageBuilder.setCoolDownTicks(600);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE15_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH14_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.SOUTH1_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE14_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH10_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.NORTH11_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN4_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN5_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN2_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.WESTERN3_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE6_ZONE, dirtyBombForageBuilder);
gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE7_ZONE, dirtyBombForageBuilder);
SpellRegistry.addSpell(new LightningSpell(gameManager));
SpellRegistry.addSpell(new ClumsinessSpell(gameManager));
SpellRegistry.addSpell(new RestoreSpell(gameManager));
SpellRegistry.addSpell(new AidsSpell(gameManager));
}
} |
package com.dbsys.rs.client;
import com.dbsys.rs.client.tableModel.PelayananTableModel;
import com.dbsys.rs.client.tableModel.PemakaianTableModel;
import com.dbsys.rs.connector.ServiceException;
import com.dbsys.rs.connector.TokenHolder;
import com.dbsys.rs.connector.service.PasienService;
import com.dbsys.rs.connector.service.PelayananService;
import com.dbsys.rs.connector.service.PemakaianService;
import com.dbsys.rs.connector.service.TokenService;
import com.dbsys.rs.lib.entity.BahanHabisPakai;
import com.dbsys.rs.lib.entity.Pasien;
import com.dbsys.rs.lib.entity.Pelayanan;
import com.dbsys.rs.lib.entity.Pemakaian;
import com.dbsys.rs.lib.entity.Tindakan;
import com.dbsys.rs.lib.entity.Unit;
import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author Bramwell Kasaedja
*/
public class FramePoliklinik extends javax.swing.JFrame implements BhpTableFrame, TindakanTableFrame {
private final TokenService tokenService = TokenService.getInstance(EventController.host);
private final PasienService pasienService = PasienService.getInstance(EventController.host);
private final PemakaianService pemakaianBhpService = PemakaianService.getInstance(EventController.host);
private final PelayananService pelayananService = PelayananService.getInstance(EventController.host);
private Pasien pasien;
/**
* Creates new form Poliklinik
* @param unit
*/
public FramePoliklinik(Unit unit) {
super();
initComponents();
lblOperator.setText(TokenHolder.getNamaOperator());
lblUnit.setText(TokenHolder.getNamaUnit());
if (Unit.TipeUnit.POLIKLINIK.equals(unit.getTipe())) {
// TODO ubah background
} else if (Unit.TipeUnit.PENUNJANG_MEDIK.equals(unit.getTipe())) {
// TODO ubah background
}
}
private void setDetailPasien(final Pasien pasien) {
txtPasienKodePenduduk.setText(pasien.getKodePenduduk());
txtPasienNik.setText(pasien.getNik());
txtPasienNama.setText(pasien.getNama());
txtPasienKelamin.setText(pasien.getKelamin().toString());
txtPasienTanggalLahir.setText(pasien.getTanggalLahir().toString());
txtPasienDarah.setText(pasien.getDarah());
txtPasienAgama.setText(pasien.getAgama());
txtPasienTelepon.setText(pasien.getTelepon());
txtPasienTanggungan.setText(pasien.getPenanggung().toString());
txtPasienStatus.setText(pasien.getStatus().toString());
txtPasienTanggalMasuk.setText(pasien.getTanggalMasuk().toString());
txtPasienTipe.setText(pasien.getTipePerawatan().toString());
}
private void loadTabelTindakan(final Pasien pasien) throws ServiceException {
if (pasien == null)
return;
List<Pelayanan> listPelayanan = pelayananService.getByPasien(pasien.getId());
PelayananTableModel tableModel = new PelayananTableModel(listPelayanan);
tblTindakan.setModel(tableModel);
}
@Override
public void reloadTableTindakan() {
try {
loadTabelTindakan(pasien);
} catch (ServiceException ex) {}
}
private Pelayanan getPelayanan() throws ComponentSelectionException {
int index = tblTindakan.getSelectedRow();
if (index < 0)
throw new ComponentSelectionException("Silahkan memilih data pada tabel terlebih dahulu");
PelayananTableModel tableModel = (PelayananTableModel)tblTindakan.getModel();
return tableModel.getPelayanan(index);
}
private void loadTabelBhp(final Pasien pasien) throws ServiceException {
if (pasien == null)
return;
List<Pemakaian> listPemakaian = pemakaianBhpService.getByPasien(pasien.getId());
PemakaianTableModel tableModel = new PemakaianTableModel(listPemakaian);
tblBhp.setModel(tableModel);
}
@Override
public void reloadTableBhp() {
try {
loadTabelBhp(pasien);
} catch (ServiceException ex) {}
}
private Pemakaian getPemakaianBhp() throws ComponentSelectionException {
int index = tblBhp.getSelectedRow();
if (index < 0)
throw new ComponentSelectionException("Silahkan memilih data pada tabel terlebih dahulu");
PemakaianTableModel tableModel = (PemakaianTableModel)tblBhp.getModel();
return tableModel.getPemakaian(index);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
jLabel13 = new javax.swing.JLabel();
lblOperator = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
lblUnit = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JToolBar.Separator();
btnLogout = new javax.swing.JButton();
tabPane = new javax.swing.JTabbedPane();
pnlTindakan = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblTindakan = new javax.swing.JTable();
btnTindakanTambah = new javax.swing.JButton();
btnTindakanUpdate = new javax.swing.JButton();
btnTindakanHapus = new javax.swing.JButton();
pnlBhp = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tblBhp = new javax.swing.JTable();
btnBhpTambah = new javax.swing.JButton();
btnBhpUpdate = new javax.swing.JButton();
btnBhpHapus = new javax.swing.JButton();
pnlCari = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtPasienKode = new javax.swing.JTextField();
pnlDetail = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
txtPasienKodePenduduk = new javax.swing.JTextField();
txtPasienNik = new javax.swing.JTextField();
txtPasienNama = new javax.swing.JTextField();
txtPasienTanggalLahir = new javax.swing.JTextField();
txtPasienDarah = new javax.swing.JTextField();
txtPasienAgama = new javax.swing.JTextField();
txtPasienTelepon = new javax.swing.JTextField();
txtPasienKelamin = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
txtPasienStatus = new javax.swing.JTextField();
txtPasienTanggalMasuk = new javax.swing.JTextField();
txtPasienTanggungan = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
txtPasienTipe = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("RUMAH SAKIT LIUN KENDAGE");
setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
getContentPane().setLayout(null);
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
jLabel13.setText("ANDA LOGIN SEBAGAI : ");
jToolBar1.add(jLabel13);
lblOperator.setText("jLabel1");
jToolBar1.add(lblOperator);
jLabel2.setText(" - UNIT : ");
jToolBar1.add(jLabel2);
lblUnit.setText("jLabel3");
jToolBar1.add(lblUnit);
jToolBar1.add(jSeparator1);
btnLogout.setText("LOGOUT");
btnLogout.setFocusable(false);
btnLogout.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnLogout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnLogout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLogoutActionPerformed(evt);
}
});
jToolBar1.add(btnLogout);
getContentPane().add(jToolBar1);
jToolBar1.setBounds(0, 770, 1270, 30);
tabPane.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tabPaneMouseClicked(evt);
}
});
pnlTindakan.setLayout(null);
tblTindakan.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(tblTindakan);
pnlTindakan.add(jScrollPane1);
jScrollPane1.setBounds(10, 11, 690, 530);
btnTindakanTambah.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_Tambah(small).png"))); // NOI18N
btnTindakanTambah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTindakanTambahActionPerformed(evt);
}
});
pnlTindakan.add(btnTindakanTambah);
btnTindakanTambah.setBounds(710, 10, 90, 30);
btnTindakanUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_Update(small).png"))); // NOI18N
btnTindakanUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTindakanUpdateActionPerformed(evt);
}
});
pnlTindakan.add(btnTindakanUpdate);
btnTindakanUpdate.setBounds(710, 50, 90, 30);
btnTindakanHapus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_hapus(small).png"))); // NOI18N
btnTindakanHapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTindakanHapusActionPerformed(evt);
}
});
pnlTindakan.add(btnTindakanHapus);
btnTindakanHapus.setBounds(710, 90, 90, 30);
tabPane.addTab("TINDAKAN", pnlTindakan);
pnlBhp.setLayout(null);
tblBhp.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(tblBhp);
pnlBhp.add(jScrollPane2);
jScrollPane2.setBounds(10, 11, 700, 530);
btnBhpTambah.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_Tambah(small).png"))); // NOI18N
btnBhpTambah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBhpTambahActionPerformed(evt);
}
});
pnlBhp.add(btnBhpTambah);
btnBhpTambah.setBounds(720, 10, 80, 30);
btnBhpUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_Update(small).png"))); // NOI18N
btnBhpUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBhpUpdateActionPerformed(evt);
}
});
pnlBhp.add(btnBhpUpdate);
btnBhpUpdate.setBounds(720, 50, 80, 30);
btnBhpHapus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_hapus(small).png"))); // NOI18N
btnBhpHapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBhpHapusActionPerformed(evt);
}
});
pnlBhp.add(btnBhpHapus);
btnBhpHapus.setBounds(720, 90, 80, 30);
tabPane.addTab("BAHAN HABIS PAKAI", pnlBhp);
getContentPane().add(tabPane);
tabPane.setBounds(20, 180, 810, 580);
pnlCari.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlCari.setLayout(null);
jLabel1.setText("No. Pasien");
pnlCari.add(jLabel1);
jLabel1.setBounds(20, 10, 110, 14);
txtPasienKode.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
txtPasienKodeFocusLost(evt);
}
});
pnlCari.add(txtPasienKode);
txtPasienKode.setBounds(140, 10, 240, 20);
getContentPane().add(pnlCari);
pnlCari.setBounds(840, 130, 400, 40);
pnlDetail.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)), "Detail Pasien"));
pnlDetail.setBackground(new Color(0,0,0,20));
pnlDetail.setLayout(null);
jLabel4.setText("NO. MEDREK");
pnlDetail.add(jLabel4);
jLabel4.setBounds(20, 30, 110, 14);
jLabel5.setText("NIK");
pnlDetail.add(jLabel5);
jLabel5.setBounds(20, 60, 110, 14);
jLabel6.setText("NAMA");
pnlDetail.add(jLabel6);
jLabel6.setBounds(20, 90, 110, 14);
jLabel7.setText("KELAMIN");
pnlDetail.add(jLabel7);
jLabel7.setBounds(20, 120, 110, 14);
jLabel8.setText("TANGGAL LAHIR");
pnlDetail.add(jLabel8);
jLabel8.setBounds(20, 150, 110, 14);
jLabel9.setText("GOL. DARAH");
pnlDetail.add(jLabel9);
jLabel9.setBounds(20, 180, 110, 14);
jLabel10.setText("AGAMA");
pnlDetail.add(jLabel10);
jLabel10.setBounds(20, 210, 110, 14);
jLabel11.setText("TELEPON");
pnlDetail.add(jLabel11);
jLabel11.setBounds(20, 240, 110, 14);
txtPasienKodePenduduk.setEditable(false);
txtPasienKodePenduduk.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienKodePenduduk);
txtPasienKodePenduduk.setBounds(140, 30, 240, 20);
txtPasienNik.setEditable(false);
txtPasienNik.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienNik);
txtPasienNik.setBounds(140, 60, 240, 20);
txtPasienNama.setEditable(false);
txtPasienNama.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienNama);
txtPasienNama.setBounds(140, 90, 240, 20);
txtPasienTanggalLahir.setEditable(false);
txtPasienTanggalLahir.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienTanggalLahir);
txtPasienTanggalLahir.setBounds(140, 150, 240, 20);
txtPasienDarah.setEditable(false);
txtPasienDarah.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienDarah);
txtPasienDarah.setBounds(140, 180, 240, 20);
txtPasienAgama.setEditable(false);
txtPasienAgama.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienAgama);
txtPasienAgama.setBounds(140, 210, 240, 20);
txtPasienTelepon.setEditable(false);
txtPasienTelepon.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienTelepon);
txtPasienTelepon.setBounds(140, 240, 240, 20);
txtPasienKelamin.setEditable(false);
txtPasienKelamin.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienKelamin);
txtPasienKelamin.setBounds(140, 120, 240, 20);
jLabel12.setText("TANGGUNGAN");
pnlDetail.add(jLabel12);
jLabel12.setBounds(20, 270, 110, 14);
jLabel16.setText("STATUS");
pnlDetail.add(jLabel16);
jLabel16.setBounds(20, 300, 110, 14);
jLabel15.setText("TANGGAL MASUK");
pnlDetail.add(jLabel15);
jLabel15.setBounds(20, 330, 110, 14);
txtPasienStatus.setEditable(false);
txtPasienStatus.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienStatus);
txtPasienStatus.setBounds(140, 300, 240, 18);
txtPasienTanggalMasuk.setEditable(false);
txtPasienTanggalMasuk.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienTanggalMasuk);
txtPasienTanggalMasuk.setBounds(140, 330, 240, 18);
txtPasienTanggungan.setEditable(false);
txtPasienTanggungan.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlDetail.add(txtPasienTanggungan);
txtPasienTanggungan.setBounds(140, 270, 240, 18);
jLabel14.setText("PERAWATAN");
pnlDetail.add(jLabel14);
jLabel14.setBounds(20, 360, 110, 14);
txtPasienTipe.setEditable(false);
pnlDetail.add(txtPasienTipe);
txtPasienTipe.setBounds(140, 360, 240, 20);
getContentPane().add(pnlDetail);
pnlDetail.setBounds(840, 180, 400, 400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/poliklinik.jpg"))); // NOI18N
getContentPane().add(jLabel3);
jLabel3.setBounds(0, 0, 1280, 800);
pack();
}// </editor-fold>//GEN-END:initComponents
private void tabPaneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabPaneMouseClicked
int index = tabPane.getSelectedIndex();
try {
switch(index) {
case 0: loadTabelTindakan(pasien);
break;
case 1: loadTabelBhp(pasien);
break;
default: break;
}
} catch (ServiceException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_tabPaneMouseClicked
private void btnBhpHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBhpHapusActionPerformed
try {
Pemakaian pemakaianBhp = getPemakaianBhp();
int pilihan = JOptionPane.showConfirmDialog(this, String.format("Anda yakin ingin menghapus pemakaian %s pada tanggal %s",
pemakaianBhp.getBarang().getNama(), pemakaianBhp.getTanggal()));
if (JOptionPane.YES_OPTION == pilihan) {
JOptionPane.showMessageDialog(this, "Belum bisa");
}
} catch (ComponentSelectionException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_btnBhpHapusActionPerformed
private void btnBhpTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBhpTambahActionPerformed
new FrameTambahObject(this, BahanHabisPakai.class, pasien).setVisible(true);
}//GEN-LAST:event_btnBhpTambahActionPerformed
private void btnBhpUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBhpUpdateActionPerformed
try {
Pemakaian pemakaianBhp = getPemakaianBhp();
new FrameTambahObject(this, pasien, pemakaianBhp).setVisible(true);
} catch (ComponentSelectionException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_btnBhpUpdateActionPerformed
private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed
try {
tokenService.lock(TokenHolder.getKode());
new FrameLogin().setVisible(true);
this.dispose();
} catch (ServiceException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_btnLogoutActionPerformed
private void btnTindakanTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTindakanTambahActionPerformed
new FrameTambahObject(this, Tindakan.class, pasien).setVisible(true);
}//GEN-LAST:event_btnTindakanTambahActionPerformed
private void btnTindakanUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTindakanUpdateActionPerformed
try {
Pelayanan pelayanan = getPelayanan();
new FrameTambahObject(this, pasien, pelayanan).setVisible(true);
} catch (ComponentSelectionException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_btnTindakanUpdateActionPerformed
private void btnTindakanHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTindakanHapusActionPerformed
try {
Pelayanan pelayanan = getPelayanan();
int pilihan = JOptionPane.showConfirmDialog(this, String.format("Anda yakin ingin menghapus pelayanan %s pada tanggal %s",
pelayanan.getTindakan().getNama(), pelayanan.getTanggal()));
if (JOptionPane.YES_OPTION == pilihan) {
JOptionPane.showMessageDialog(this, "Belum bisa");
}
} catch (ComponentSelectionException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_btnTindakanHapusActionPerformed
private void txtPasienKodeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasienKodeFocusLost
String keyword = txtPasienKode.getText();
if (keyword.equals(""))
return;
try {
pasien = pasienService.get(keyword);
setDetailPasien(pasien);
loadTabelTindakan(pasien);
} catch (ServiceException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_txtPasienKodeFocusLost
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBhpHapus;
private javax.swing.JButton btnBhpTambah;
private javax.swing.JButton btnBhpUpdate;
private javax.swing.JButton btnLogout;
private javax.swing.JButton btnTindakanHapus;
private javax.swing.JButton btnTindakanTambah;
private javax.swing.JButton btnTindakanUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JToolBar.Separator jSeparator1;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JLabel lblOperator;
private javax.swing.JLabel lblUnit;
private javax.swing.JPanel pnlBhp;
private javax.swing.JPanel pnlCari;
private javax.swing.JPanel pnlDetail;
private javax.swing.JPanel pnlTindakan;
private javax.swing.JTabbedPane tabPane;
private javax.swing.JTable tblBhp;
private javax.swing.JTable tblTindakan;
private javax.swing.JTextField txtPasienAgama;
private javax.swing.JTextField txtPasienDarah;
private javax.swing.JTextField txtPasienKelamin;
private javax.swing.JTextField txtPasienKode;
private javax.swing.JTextField txtPasienKodePenduduk;
private javax.swing.JTextField txtPasienNama;
private javax.swing.JTextField txtPasienNik;
private javax.swing.JTextField txtPasienStatus;
private javax.swing.JTextField txtPasienTanggalLahir;
private javax.swing.JTextField txtPasienTanggalMasuk;
private javax.swing.JTextField txtPasienTanggungan;
private javax.swing.JTextField txtPasienTelepon;
private javax.swing.JTextField txtPasienTipe;
// End of variables declaration//GEN-END:variables
} |
package com.facebook.litho;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.litho.displaylist.DisplayListException;
import com.facebook.litho.reference.BorderColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec;
import static com.facebook.litho.Component.isMountSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentLifecycle.MountType.NONE;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS;
import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT;
import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE;
import static com.facebook.litho.MountState.ROOT_HOST_ID;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.litho.SizeSpec.EXACTLY;
/**
* The main role of {@link LayoutState} is to hold the output of layout calculation. This includes
* mountable outputs and visibility outputs. A centerpiece of the class is {@link
* #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs
* based on the provided {@link InternalNode} for later use in {@link MountState}.
*/
class LayoutState {
static final Comparator<LayoutOutput> sTopsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsTop = lhs.getBounds().top;
final int rhsTop = rhs.getBounds().top;
return lhsTop < rhsTop
? -1
: lhsTop > rhsTop
? 1
// Hosts should be higher for tops so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? -1 : 1;
}
};
static final Comparator<LayoutOutput> sBottomsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsBottom = lhs.getBounds().bottom;
final int rhsBottom = rhs.getBounds().bottom;
return lhsBottom < rhsBottom
? -1
: lhsBottom > rhsBottom
? 1
// Hosts should be lower for bottoms so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? 1 : -1;
}
};
private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled};
private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{};
private ComponentContext mContext;
private TransitionContext mTransitionContext;
private Component<?> mComponent;
private int mWidthSpec;
private int mHeightSpec;
private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8);
private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8);
private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8);
private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator;
private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>();
private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>();
private final List<TestOutput> mTestOutputs;
private InternalNode mLayoutRoot;
private DiffNode mDiffTreeRoot;
// Reference count will be initialized to 1 in init().
private final AtomicInteger mReferenceCount = new AtomicInteger(-1);
private int mWidth;
private int mHeight;
private int mCurrentX;
private int mCurrentY;
private int mCurrentLevel = 0;
// Holds the current host marker in the layout tree.
private long mCurrentHostMarker = -1;
private int mCurrentHostOutputPosition = -1;
private boolean mShouldDuplicateParentState = true;
private boolean mShouldGenerateDiffTree = false;
private int mComponentTreeId = -1;
private AccessibilityManager mAccessibilityManager;
private boolean mAccessibilityEnabled = false;
private StateHandler mStateHandler;
LayoutState() {
mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator();
mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null;
}
/**
* Acquires a new layout output for the internal node and its associated component. It returns
* null if there's no component associated with the node as the mount pass only cares about nodes
* that will potentially mount content into the component host.
*/
@Nullable
private static LayoutOutput createGenericLayoutOutput(
InternalNode node,
LayoutState layoutState) {
final Component<?> component = node.getComponent();
// Skip empty nodes and layout specs because they don't mount anything.
if (component == null || component.getLifecycle().getMountType() == NONE) {
return null;
}
return createLayoutOutput(
component,
layoutState,
node,
true /* useNodePadding */,
node.getImportantForAccessibility(),
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) {
final LayoutOutput hostOutput = createLayoutOutput(
HostComponent.create(),
layoutState,
node,
false /* useNodePadding */,
node.getImportantForAccessibility(),
node.isDuplicateParentStateEnabled());
hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey());
return hostOutput;
}
private static LayoutOutput createDrawableLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node) {
return createLayoutOutput(
component,
layoutState,
node,
false /* useNodePadding */,
IMPORTANT_FOR_ACCESSIBILITY_NO,
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node,
boolean useNodePadding,
int importantForAccessibility,
boolean duplicateParentState) {
final boolean isMountViewSpec = isMountViewSpec(component);
final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput();
layoutOutput.setComponent(component);
layoutOutput.setImportantForAccessibility(importantForAccessibility);
// The mount operation will need both the marker for the target host and its matching
// parent host to ensure the correct hierarchy when nesting the host views.
layoutOutput.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutState.mCurrentHostOutputPosition >= 0) {
final LayoutOutput hostOutput =
layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition);
final Rect hostBounds = hostOutput.getBounds();
layoutOutput.setHostTranslationX(hostBounds.left);
layoutOutput.setHostTranslationY(hostBounds.top);
}
int l = layoutState.mCurrentX + node.getX();
int t = layoutState.mCurrentY + node.getY();
int r = l + node.getWidth();
int b = t + node.getHeight();
final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0;
final int paddingTop = useNodePadding ? node.getPaddingTop() : 0;
final int paddingRight = useNodePadding ? node.getPaddingRight() : 0;
final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0;
// View mount specs are able to set their own attributes when they're mounted.
// Non-view specs (drawable and layout) always transfer their view attributes
// to their respective hosts.
// Moreover, if the component mounts a view, then we apply padding to the view itself later on.
// Otherwise, apply the padding to the bounds of the layout output.
if (isMountViewSpec) {
layoutOutput.setNodeInfo(node.getNodeInfo());
// Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput.
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection());
viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b);
layoutOutput.setViewNodeInfo(viewNodeInfo);
viewNodeInfo.release();
} else {
l += paddingLeft;
t += paddingTop;
r -= paddingRight;
b -= paddingBottom;
}
layoutOutput.setBounds(l, t, r, b);
int flags = 0;
if (duplicateParentState) {
flags |= FLAG_DUPLICATE_PARENT_STATE;
}
layoutOutput.setFlags(flags);
return layoutOutput;
}
/**
* Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information
* stored in the {@link InternalNode}.
*/
private static VisibilityOutput createVisibilityOutput(
InternalNode node,
LayoutState layoutState) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final EventHandler visibleHandler = node.getVisibleHandler();
final EventHandler focusedHandler = node.getFocusedHandler();
final EventHandler fullImpressionHandler = node.getFullImpressionHandler();
final EventHandler invisibleHandler = node.getInvisibleHandler();
final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput();
final Component<?> handlerComponent;
// Get the component from the handler that is not null. If more than one is not null, then
// getting the component from any of them works.
if (visibleHandler != null) {
handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher;
} else if (focusedHandler != null) {
handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher;
} else if (fullImpressionHandler != null) {
handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher;
} else {
handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher;
}
visibilityOutput.setComponent(handlerComponent);
visibilityOutput.setBounds(l, t, r, b);
visibilityOutput.setVisibleEventHandler(visibleHandler);
visibilityOutput.setFocusedEventHandler(focusedHandler);
visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler);
visibilityOutput.setInvisibleEventHandler(invisibleHandler);
return visibilityOutput;
}
private static TestOutput createTestOutput(
InternalNode node,
LayoutState layoutState,
LayoutOutput layoutOutput) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final TestOutput output = ComponentsPools.acquireTestOutput();
output.setTestKey(node.getTestKey());
output.setBounds(l, t, r, b);
output.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutOutput != null) {
output.setLayoutOutputId(layoutOutput.getId());
}
return output;
}
private static boolean isLayoutDirectionRTL(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if ((SDK_INT >= JELLY_BEAN_MR1)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) {
int layoutDirection = getLayoutDirection(context);
return layoutDirection == View.LAYOUT_DIRECTION_RTL;
}
return false;
}
@TargetApi(JELLY_BEAN_MR1)
private static int getLayoutDirection(Context context) {
return context.getResources().getConfiguration().getLayoutDirection();
}
/**
* Determine if a given {@link InternalNode} within the context of a given {@link LayoutState}
* requires to be wrapped inside a view.
*
* @see #needsHostView(InternalNode, LayoutState)
*/
private static boolean hasViewContent(InternalNode node, LayoutState layoutState) {
final Component<?> component = node.getComponent();
final NodeInfo nodeInfo = node.getNodeInfo();
final boolean implementsAccessibility =
(nodeInfo != null && nodeInfo.hasAccessibilityHandlers())
|| (component != null && component.getLifecycle().implementsAccessibility());
final int importantForAccessibility = node.getImportantForAccessibility();
// A component has accessibility content if:
// 1. Accessibility is currently enabled.
// 2. Accessibility hasn't been explicitly disabled on it
// i.e. IMPORTANT_FOR_ACCESSIBILITY_NO.
// 3. Any of these conditions are true:
// - It implements accessibility support.
// - It has a content description.
// - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES
// or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.
// IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host
// so that such flag is applied in the resulting view hierarchy after the component
// tree is mounted. Click handling is also considered accessibility content but
// this is already covered separately i.e. click handler is not null.
final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled
&& importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO
&& (implementsAccessibility
|| (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription()))
|| importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO);
final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers());
final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null);
final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null);
final boolean isFocusableSetTrue =
(nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE);
return hasTouchEventHandlers
|| hasViewTag
|| hasViewTags
|| hasAccessibilityContent
|| isFocusableSetTrue;
}
/**
* Collects layout outputs and release the layout tree. The layout outputs hold necessary
* information to be used by {@link MountState} to mount components into a {@link ComponentHost}.
* <p/>
* Whenever a component has view content (view tags, click handler, etc), a new host 'marker'
* is added for it. The mount pass will use the markers to decide which host should be used
* for each layout output. The root node unconditionally generates a layout output corresponding
* to the root host.
* <p/>
* The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts
* will be created at the right order when mounting. The host markers will be define which host
* each mounted artifacts will be attached to.
* <p/>
* At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled
* will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the
* host and the contents (including background/foreground). In all other cases instead we'll only
* try to re-use the hosts. In some cases the host's structure might change between two updates
* even if the component is of the same type. This can happen for example when a click listener is
* added. To avoid trying to re-use the wrong host type we explicitly check that after all the
* children for a subtree have been added (this is when the actual host type is resolved). If the
* host type changed compared to the one in the DiffNode we need to refresh the ids for the whole
* subtree in order to ensure that the MountState will unmount the subtree and mount it again on
* the correct host.
* <p/>
*
* @param node InternalNode to process.
* @param layoutState the LayoutState currently operating.
* @param parentDiffNode whether this method also populates the diff tree and assigns the root
* to mDiffTreeRoot.
*/
private static void collectResults(
InternalNode node,
LayoutState layoutState,
DiffNode parentDiffNode) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
final Component<?> component = node.getComponent();
// Early return if collecting results of a node holding a nested tree.
if (node.isNestedTreeHolder()) {
// If the nested tree is defined, it has been resolved during a measure call during
// layout calculation.
InternalNode nestedTree = resolveNestedTree(
node,
SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY),
SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY));
if (nestedTree == NULL_LAYOUT) {
return;
}
// Account for position of the holder node.
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
collectResults(nestedTree, layoutState, parentDiffNode);
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
return;
}
final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree;
final DiffNode currentDiffNode = node.getDiffNode();
final boolean shouldUseCachedOutputs =
isMountSpec(component) && currentDiffNode != null;
final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid();
final DiffNode diffNode;
if (shouldGenerateDiffTree) {
diffNode = createDiffNode(node, parentDiffNode);
if (parentDiffNode == null) {
layoutState.mDiffTreeRoot = diffNode;
}
} else {
diffNode = null;
}
final boolean needsHostView = needsHostView(node, layoutState);
final long currentHostMarker = layoutState.mCurrentHostMarker;
final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition;
int hostLayoutPosition = -1;
// 1. Insert a host LayoutOutput if we have some interactive content to be attached to.
if (needsHostView) {
hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode);
layoutState.mCurrentLevel++;
layoutState.mCurrentHostMarker =
layoutState.mMountableOutputs.get(hostLayoutPosition).getId();
layoutState.mCurrentHostOutputPosition = hostLayoutPosition;
}
// We need to take into account flattening when setting duplicate parent state. The parent after
// flattening may no longer exist. Therefore the value of duplicate parent state should only be
// true if the path between us (inclusive) and our inner/root host (exclusive) all are
// duplicate parent state.
final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState;
layoutState.mShouldDuplicateParentState =
needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled());
// Generate the layoutOutput for the given node.
final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState);
if (layoutOutput != null) {
final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
layoutOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_CONTENT,
previousId,
isCachedOutputUpdated);
}
// If we don't need to update this output we can safely re-use the display list from the
// previous output.
if (isCachedOutputUpdated) {
layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList());
}
// 2. Add background if defined.
final Reference<? extends Drawable> background = node.getBackground();
if (background != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) {
layoutOutput.getViewNodeInfo().setBackground(background);
} else {
final LayoutOutput convertBackground = (currentDiffNode != null)
? currentDiffNode.getBackground()
: null;
final LayoutOutput backgroundOutput = addDrawableComponent(
node,
layoutState,
convertBackground,
background,
LayoutOutput.TYPE_BACKGROUND);
if (diffNode != null) {
diffNode.setBackground(backgroundOutput);
}
}
}
// 3. Now add the MountSpec (either View or Drawable) to the Outputs.
if (isMountSpec(component)) {
// Notify component about its final size.
component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component);
addMountableOutput(layoutState, layoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
layoutOutput,
layoutState.mMountableOutputs.size() - 1);
if (diffNode != null) {
diffNode.setContent(layoutOutput);
}
}
// 4. Add border color if defined.
if (node.shouldDrawBorders()) {
final LayoutOutput convertBorder = (currentDiffNode != null)
? currentDiffNode.getBorder()
: null;
final LayoutOutput borderOutput = addDrawableComponent(
node,
layoutState,
convertBorder,
getBorderColorDrawable(node),
LayoutOutput.TYPE_BORDER);
if (diffNode != null) {
diffNode.setBorder(borderOutput);
}
}
// 5. Extract the Transitions.
if (SDK_INT >= ICE_CREAM_SANDWICH) {
if (node.getTransitionKey() != null) {
layoutState
.getOrCreateTransitionContext()
.addTransitionKey(node.getTransitionKey());
}
if (component != null) {
Transition transition = component.getLifecycle().onLayoutTransition(
layoutState.mContext,
component);
if (transition != null) {
layoutState.getOrCreateTransitionContext().add(transition);
}
}
}
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
// We must process the nodes in order so that the layout state output order is correct.
for (int i = 0, size = node.getChildCount(); i < size; i++) {
collectResults(
node.getChildAt(i),
layoutState,
diffNode);
}
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
// 6. Add foreground if defined.
final Reference<? extends Drawable> foreground = node.getForeground();
if (foreground != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) {
layoutOutput.getViewNodeInfo().setForeground(foreground);
} else {
final LayoutOutput convertForeground = (currentDiffNode != null)
? currentDiffNode.getForeground()
: null;
final LayoutOutput foregroundOutput = addDrawableComponent(
node,
layoutState,
convertForeground,
foreground,
LayoutOutput.TYPE_FOREGROUND);
if (diffNode != null) {
diffNode.setForeground(foregroundOutput);
}
}
}
// 7. Add VisibilityOutputs if any visibility-related event handlers are present.
if (node.hasVisibilityHandlers()) {
final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState);
final long previousId =
shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId(
visibilityOutput,
layoutState.mCurrentLevel,
previousId);
layoutState.mVisibilityOutputs.add(visibilityOutput);
if (diffNode != null) {
diffNode.setVisibilityOutput(visibilityOutput);
}
}
// 8. If we're in a testing environment, maintain an additional data structure with
// information about nodes that we can query later.
if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) {
final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput);
layoutState.mTestOutputs.add(testOutput);
}
// All children for the given host have been added, restore the previous
// host, level, and duplicate parent state value in the recursive queue.
if (layoutState.mCurrentHostMarker != currentHostMarker) {
layoutState.mCurrentHostMarker = currentHostMarker;
layoutState.mCurrentHostOutputPosition = currentHostOutputPosition;
layoutState.mCurrentLevel
}
layoutState.mShouldDuplicateParentState = shouldDuplicateParentState;
Collections.sort(layoutState.mMountableOutputTops, sTopsComparator);
Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator);
}
private static void calculateAndSetHostOutputIdAndUpdateState(
InternalNode node,
LayoutOutput hostOutput,
LayoutState layoutState,
boolean isCachedOutputUpdated) {
if (layoutState.isLayoutRoot(node)) {
// The root host (ComponentView) always has ID 0 and is unconditionally
// set as dirty i.e. no need to use shouldComponentUpdate().
hostOutput.setId(ROOT_HOST_ID);
// Special case where the host marker of the root host is pointing to itself.
hostOutput.setHostMarker(ROOT_HOST_ID);
hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY);
} else {
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
hostOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_HOST,
-1,
isCachedOutputUpdated);
}
}
private static LayoutOutput addDrawableComponent(
InternalNode node,
LayoutState layoutState,
LayoutOutput recycle,
Reference<? extends Drawable> reference,
@LayoutOutput.LayoutOutputType int type) {
final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference);
drawableComponent.setScopedContext(
ComponentContext.withComponentScope(node.getContext(), drawableComponent));
final boolean isOutputUpdated;
if (recycle != null) {
isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate(
recycle.getComponent(),
drawableComponent);
} else {
isOutputUpdated = false;
}
final long previousId = recycle != null ? recycle.getId() : -1;
final LayoutOutput output = addDrawableLayoutOutput(
drawableComponent,
layoutState,
node,
type,
previousId,
isOutputUpdated);
return output;
}
private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) {
if (!node.shouldDrawBorders()) {
throw new RuntimeException("This node does not support drawing border color");
}
return BorderColorDrawableReference.create(node.getContext())
.color(node.getBorderColor())
.borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT)))
.borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP)))
.borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT)))
.borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM)))
.build();
}
private static void addLayoutOutputIdToPositionsMap(
LongSparseArray outputsIdToPositionMap,
LayoutOutput layoutOutput,
int position) {
if (outputsIdToPositionMap != null) {
outputsIdToPositionMap.put(layoutOutput.getId(), position);
}
}
private static LayoutOutput addDrawableLayoutOutput(
Component<DrawableComponent> drawableComponent,
LayoutState layoutState,
InternalNode node,
@LayoutOutput.LayoutOutputType int layoutOutputType,
long previousId,
boolean isCachedOutputUpdated) {
drawableComponent.getLifecycle().onBoundsDefined(
layoutState.mContext,
node,
drawableComponent);
final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput(
drawableComponent,
layoutState,
node);
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
drawableLayoutOutput,
layoutState.mCurrentLevel,
layoutOutputType,
previousId,
isCachedOutputUpdated);
addMountableOutput(layoutState, drawableLayoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
drawableLayoutOutput,
layoutState.mMountableOutputs.size() - 1);
return drawableLayoutOutput;
}
static void releaseNodeTree(InternalNode node, boolean isNestedTree) {
if (node == NULL_LAYOUT) {
throw new IllegalArgumentException("Cannot release a null node tree");
}
for (int i = node.getChildCount() - 1; i >= 0; i
final InternalNode child = node.getChildAt(i);
if (isNestedTree && node.hasNewLayout()) {
node.markLayoutSeen();
}
// A node must be detached from its parent *before* being released (otherwise the parent would
// retain a reference to a node that may get re-used by another thread)
node.removeChildAt(i);
releaseNodeTree(child, isNestedTree);
}
if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) {
releaseNodeTree(node.getNestedTree(), true);
}
ComponentsPools.release(node);
}
/**
* If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an
* HostComponent in the Outputs such as it will be used as a HostView at Mount time. View
* MountSpec are not allowed.
*
* @return The position the HostLayoutOutput was inserted.
*/
private static int addHostLayoutOutput(
InternalNode node,
LayoutState layoutState,
DiffNode diffNode) {
final Component<?> component = node.getComponent();
// Only the root host is allowed to wrap view mount specs as a layout output
// is unconditionally added for it.
if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) {
throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View");
}
final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node);
// The component of the hostLayoutOutput will be set later after all the
// children got processed.
addMountableOutput(layoutState, hostLayoutOutput);
final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1;
if (diffNode != null) {
diffNode.setHost(hostLayoutOutput);
}
calculateAndSetHostOutputIdAndUpdateState(
node,
hostLayoutOutput,
layoutState,
false);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
hostLayoutOutput,
hostOutputPosition);
return hostOutputPosition;
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec,
boolean shouldGenerateDiffTree,
DiffNode previousDiffTreeRoot) {
// Detect errors internal to components
component.markLayoutStarted();
LayoutState layoutState = ComponentsPools.acquireLayoutState(c);
layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree;
layoutState.mComponentTreeId = componentTreeId;
layoutState.mAccessibilityManager =
(AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE);
layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager);
layoutState.mComponent = component;
layoutState.mWidthSpec = widthSpec;
layoutState.mHeightSpec = heightSpec;
component.applyStateUpdates(c);
final InternalNode root = createAndMeasureTreeForComponent(
component.getScopedContext(),
component,
null, // nestedTreeHolder is null because this is measuring the root component tree.
widthSpec,
heightSpec,
previousDiffTreeRoot);
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.EXACTLY:
layoutState.mWidth = SizeSpec.getSize(widthSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mWidth = root.getWidth();
break;
}
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.EXACTLY:
layoutState.mHeight = SizeSpec.getSize(heightSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mHeight = root.getHeight();
break;
}
layoutState.mLayoutStateOutputIdCalculator.clear();
// Reset markers before collecting layout outputs.
layoutState.mCurrentHostMarker = -1;
final ComponentsLogger logger = c.getLogger();
if (root == NULL_LAYOUT) {
return layoutState;
}
layoutState.mLayoutRoot = root;
ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName());
if (logger != null) {
logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag());
}
collectResults(root, layoutState, null);
if (logger != null) {
logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection();
if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) {
releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */);
layoutState.mLayoutRoot = null;
}
if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) {
collectDisplayLists(layoutState);
}
return layoutState;
}
void preAllocateMountContent() {
if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
final Component component = mMountableOutputs.get(i).getComponent();
if (Component.isMountViewSpec(component)) {
final ComponentLifecycle lifecycle = component.getLifecycle();
if (!lifecycle.hasBeenPreallocated()) {
final int poolSize = lifecycle.poolSize();
int insertedCount = 0;
while (insertedCount < poolSize &&
ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) {
ComponentsPools.release(
mContext,
lifecycle,
lifecycle.createMountContent(mContext));
insertedCount++;
}
lifecycle.setWasPreallocated();
}
}
}
}
}
private static void collectDisplayLists(LayoutState layoutState) {
final Rect rect = new Rect();
final ComponentContext context = layoutState.mContext;
final Activity activity = findActivityInContext(context);
if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) {
return;
}
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
final Component component = output.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
if (lifecycle.shouldUseDisplayList()) {
output.getMountBounds(rect);
if (output.getDisplayList() != null && output.getDisplayList().isValid()) {
// This output already has a valid DisplayList from diffing. No need to re-create it.
// Just update its bounds.
try {
output.getDisplayList().setBounds(rect.left, rect.top, rect.right, rect.bottom);
continue;
} catch (DisplayListException e) {
// Nothing to do here.
}
}
final DisplayList displayList = DisplayList.createDisplayList(
lifecycle.getClass().getSimpleName());
if (displayList != null) {
Drawable drawable =
(Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getId());
if (drawable == null) {
drawable = (Drawable) lifecycle.createMountContent(context);
}
final LayoutOutput clickableOutput = findInteractiveRoot(layoutState, output);
boolean isStateEnabled = false;
if (clickableOutput != null && clickableOutput.getNodeInfo() != null) {
final NodeInfo nodeInfo = clickableOutput.getNodeInfo();
if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) {
isStateEnabled = true;
}
}
if (isStateEnabled) {
drawable.setState(DRAWABLE_STATE_ENABLED);
} else {
drawable.setState(DRAWABLE_STATE_NOT_ENABLED);
}
lifecycle.mount(
context,
drawable,
component);
lifecycle.bind(context, drawable, component);
output.getMountBounds(rect);
drawable.setBounds(0, 0, rect.width(), rect.height());
try {
final Canvas canvas = displayList.start(rect.width(), rect.height());
drawable.draw(canvas);
displayList.end(canvas);
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
output.setDisplayList(displayList);
} catch (DisplayListException e) {
// Display list creation failed. Make sure the DisplayList for this output is set
// to null.
output.setDisplayList(null);
}
lifecycle.unbind(context, drawable, component);
lifecycle.unmount(context, drawable, component);
ComponentsPools.release(context, lifecycle, drawable);
}
}
}
}
private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) {
if (output.getId() == ROOT_HOST_ID) {
return output;
}
if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) {
final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker());
if (parentPosition >= 0) {
final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition);
if (parent == null) {
return null;
}
return findInteractiveRoot(layoutState, parent);
}
return null;
}
return output;
}
private static boolean isActivityDestroyed(Activity activity) {
if (SDK_INT >= JELLY_BEAN_MR1) {
return activity.isDestroyed();
}
return false;
}
private static Activity findActivityInContext(Context context) {
if (context instanceof Activity) {
return (Activity) context;
} else if (context instanceof ContextWrapper) {
return findActivityInContext(((ContextWrapper) context).getBaseContext());
}
return null;
}
@VisibleForTesting
static <T extends ComponentLifecycle> InternalNode createTree(
Component<T> component,
ComponentContext context) {
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CREATE_LAYOUT, context, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddTag(EVENT_CREATE_LAYOUT, context, component.getSimpleName());
}
final InternalNode root = (InternalNode) component.getLifecycle().createLayout(
context,
component,
true /* resolveNestedTree */);
if (logger != null) {
logger.eventEnd(EVENT_CREATE_LAYOUT, context, ACTION_SUCCESS);
}
return root;
}
@VisibleForTesting
static void measureTree(
InternalNode root,
int widthSpec,
int heightSpec,
DiffNode previousDiffTreeRoot) {
final ComponentContext context = root.getContext();
final Component component = root.getComponent();
ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName());
if (YogaConstants.isUndefined(root.getStyleWidth())) {
root.setStyleWidthFromSpec(widthSpec);
}
if (YogaConstants.isUndefined(root.getStyleHeight())) {
root.setStyleHeightFromSpec(heightSpec);
}
if (previousDiffTreeRoot != null) {
ComponentsSystrace.beginSection("applyDiffNode");
applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot);
ComponentsSystrace.endSection(/* applyDiffNode */);
}
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CSS_LAYOUT, component, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddParam(
EVENT_CSS_LAYOUT,
component,
PARAM_TREE_DIFF_ENABLED,
String.valueOf(previousDiffTreeRoot != null));
}
root.calculateLayout(
SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(widthSpec),
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(heightSpec));
if (logger != null) {
logger.eventEnd(EVENT_CSS_LAYOUT, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection(/* measureTree */);
}
/**
* Create and measure the nested tree or return the cached one for the same size specs.
*/
static InternalNode resolveNestedTree(
InternalNode nestedTreeHolder,
int widthSpec,
int heightSpec) {
final ComponentContext context = nestedTreeHolder.getContext();
final Component<?> component = nestedTreeHolder.getComponent();
InternalNode nestedTree = nestedTreeHolder.getNestedTree();
if (nestedTree == null
|| !hasCompatibleSizeSpec(
nestedTree.getLastWidthSpec(),
nestedTree.getLastHeightSpec(),
widthSpec,
heightSpec,
nestedTree.getLastMeasuredWidth(),
nestedTree.getLastMeasuredHeight())) {
if (nestedTree != null) {
if (nestedTree != NULL_LAYOUT) {
releaseNodeTree(nestedTree, true /* isNestedTree */);
}
nestedTree = null;
}
if (component.hasCachedLayout()) {
final InternalNode cachedLayout = component.getCachedLayout();
final boolean hasCompatibleLayoutDirection =
InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout);
// Transfer the cached layout to the node without releasing it if it's compatible.
if (hasCompatibleLayoutDirection &&
hasCompatibleSizeSpec(
cachedLayout.getLastWidthSpec(),
cachedLayout.getLastHeightSpec(),
widthSpec,
heightSpec,
cachedLayout.getLastMeasuredWidth(),
cachedLayout.getLastMeasuredHeight())) {
nestedTree = cachedLayout;
component.clearCachedLayout();
} else {
component.releaseCachedLayout();
}
}
if (nestedTree == null) {
nestedTree = createAndMeasureTreeForComponent(
context,
component,
nestedTreeHolder,
widthSpec,
heightSpec,
nestedTreeHolder.getDiffNode()); // Previously set while traversing the holder's tree.
nestedTree.setLastWidthSpec(widthSpec);
nestedTree.setLastHeightSpec(heightSpec);
nestedTree.setLastMeasuredHeight(nestedTree.getHeight());
nestedTree.setLastMeasuredWidth(nestedTree.getWidth());
}
nestedTreeHolder.setNestedTree(nestedTree);
}
// This is checking only nested tree roots however it will be moved to check all the tree roots.
InternalNode.assertContextSpecificStyleNotSet(nestedTree);
return nestedTree;
}
/**
* Create and measure a component with the given size specs.
*/
static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
int widthSpec,
int heightSpec) {
return createAndMeasureTreeForComponent(c, component, null, widthSpec, heightSpec, null);
}
private static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
InternalNode nestedTreeHolder, // This will be set only if we are resolving a nested tree.
int widthSpec,
int heightSpec,
DiffNode diffTreeRoot) {
// Account for the size specs in ComponentContext in case the tree is a NestedTree.
final int previousWidthSpec = c.getWidthSpec();
final int previousHeightSpec = c.getHeightSpec();
final boolean hasNestedTreeHolder = nestedTreeHolder != null;
c.setWidthSpec(widthSpec);
c.setHeightSpec(heightSpec);
if (hasNestedTreeHolder) {
c.setTreeProps(nestedTreeHolder.getPendingTreeProps());
}
final InternalNode root = createTree(
component,
c);
if (hasNestedTreeHolder) {
c.setTreeProps(null);
}
c.setWidthSpec(previousWidthSpec);
c.setHeightSpec(previousHeightSpec);
if (root == NULL_LAYOUT) {
return root;
}
// If measuring a ComponentTree with a LayoutSpecWithSizeSpec at the root, the nested tree
// holder argument will be null.
if (hasNestedTreeHolder && isLayoutSpecWithSizeSpec(component)) {
// Transfer information from the holder node to the nested tree root before measurement.
nestedTreeHolder.copyInto(root);
diffTreeRoot = nestedTreeHolder.getDiffNode();
} else if (root.getStyleDirection() == com.facebook.yoga.YogaDirection.INHERIT |
package com.facebook.litho;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.litho.displaylist.DisplayListException;
import com.facebook.litho.reference.BorderColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec;
import static com.facebook.litho.Component.isMountSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentLifecycle.MountType.NONE;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS;
import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT;
import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE;
import static com.facebook.litho.MountState.ROOT_HOST_ID;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.litho.SizeSpec.EXACTLY;
/**
* The main role of {@link LayoutState} is to hold the output of layout calculation. This includes
* mountable outputs and visibility outputs. A centerpiece of the class is {@link
* #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs
* based on the provided {@link InternalNode} for later use in {@link MountState}.
*/
class LayoutState {
static final Comparator<LayoutOutput> sTopsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsTop = lhs.getBounds().top;
final int rhsTop = rhs.getBounds().top;
return lhsTop < rhsTop
? -1
: lhsTop > rhsTop
? 1
// Hosts should be higher for tops so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? -1 : 1;
}
};
static final Comparator<LayoutOutput> sBottomsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsBottom = lhs.getBounds().bottom;
final int rhsBottom = rhs.getBounds().bottom;
return lhsBottom < rhsBottom
? -1
: lhsBottom > rhsBottom
? 1
// Hosts should be lower for bottoms so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? 1 : -1;
}
};
private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled};
private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{};
private ComponentContext mContext;
private TransitionContext mTransitionContext;
private Component<?> mComponent;
private int mWidthSpec;
private int mHeightSpec;
private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8);
private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8);
private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8);
private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator;
private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>();
private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>();
private final List<TestOutput> mTestOutputs;
private InternalNode mLayoutRoot;
private DiffNode mDiffTreeRoot;
// Reference count will be initialized to 1 in init().
private final AtomicInteger mReferenceCount = new AtomicInteger(-1);
private int mWidth;
private int mHeight;
private int mCurrentX;
private int mCurrentY;
private int mCurrentLevel = 0;
// Holds the current host marker in the layout tree.
private long mCurrentHostMarker = -1;
private int mCurrentHostOutputPosition = -1;
private boolean mShouldDuplicateParentState = true;
private boolean mShouldGenerateDiffTree = false;
private int mComponentTreeId = -1;
private AccessibilityManager mAccessibilityManager;
private boolean mAccessibilityEnabled = false;
private StateHandler mStateHandler;
LayoutState() {
mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator();
mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null;
}
/**
* Acquires a new layout output for the internal node and its associated component. It returns
* null if there's no component associated with the node as the mount pass only cares about nodes
* that will potentially mount content into the component host.
*/
@Nullable
private static LayoutOutput createGenericLayoutOutput(
InternalNode node,
LayoutState layoutState) {
final Component<?> component = node.getComponent();
// Skip empty nodes and layout specs because they don't mount anything.
if (component == null || component.getLifecycle().getMountType() == NONE) {
return null;
}
return createLayoutOutput(
component,
layoutState,
node,
true /* useNodePadding */,
node.getImportantForAccessibility(),
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) {
final LayoutOutput hostOutput = createLayoutOutput(
HostComponent.create(),
layoutState,
node,
false /* useNodePadding */,
node.getImportantForAccessibility(),
node.isDuplicateParentStateEnabled());
hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey());
return hostOutput;
}
private static LayoutOutput createDrawableLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node) {
return createLayoutOutput(
component,
layoutState,
node,
false /* useNodePadding */,
IMPORTANT_FOR_ACCESSIBILITY_NO,
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node,
boolean useNodePadding,
int importantForAccessibility,
boolean duplicateParentState) {
final boolean isMountViewSpec = isMountViewSpec(component);
final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput();
layoutOutput.setComponent(component);
layoutOutput.setImportantForAccessibility(importantForAccessibility);
// The mount operation will need both the marker for the target host and its matching
// parent host to ensure the correct hierarchy when nesting the host views.
layoutOutput.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutState.mCurrentHostOutputPosition >= 0) {
final LayoutOutput hostOutput =
layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition);
final Rect hostBounds = hostOutput.getBounds();
layoutOutput.setHostTranslationX(hostBounds.left);
layoutOutput.setHostTranslationY(hostBounds.top);
}
int l = layoutState.mCurrentX + node.getX();
int t = layoutState.mCurrentY + node.getY();
int r = l + node.getWidth();
int b = t + node.getHeight();
final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0;
final int paddingTop = useNodePadding ? node.getPaddingTop() : 0;
final int paddingRight = useNodePadding ? node.getPaddingRight() : 0;
final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0;
// View mount specs are able to set their own attributes when they're mounted.
// Non-view specs (drawable and layout) always transfer their view attributes
// to their respective hosts.
// Moreover, if the component mounts a view, then we apply padding to the view itself later on.
// Otherwise, apply the padding to the bounds of the layout output.
if (isMountViewSpec) {
layoutOutput.setNodeInfo(node.getNodeInfo());
// Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput.
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection());
viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b);
layoutOutput.setViewNodeInfo(viewNodeInfo);
viewNodeInfo.release();
} else {
l += paddingLeft;
t += paddingTop;
r -= paddingRight;
b -= paddingBottom;
}
layoutOutput.setBounds(l, t, r, b);
int flags = 0;
if (duplicateParentState) {
flags |= FLAG_DUPLICATE_PARENT_STATE;
}
layoutOutput.setFlags(flags);
return layoutOutput;
}
/**
* Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information
* stored in the {@link InternalNode}.
*/
private static VisibilityOutput createVisibilityOutput(
InternalNode node,
LayoutState layoutState) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final EventHandler visibleHandler = node.getVisibleHandler();
final EventHandler focusedHandler = node.getFocusedHandler();
final EventHandler fullImpressionHandler = node.getFullImpressionHandler();
final EventHandler invisibleHandler = node.getInvisibleHandler();
final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput();
final Component<?> handlerComponent;
// Get the component from the handler that is not null. If more than one is not null, then
// getting the component from any of them works.
if (visibleHandler != null) {
handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher;
} else if (focusedHandler != null) {
handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher;
} else if (fullImpressionHandler != null) {
handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher;
} else {
handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher;
}
visibilityOutput.setComponent(handlerComponent);
visibilityOutput.setBounds(l, t, r, b);
visibilityOutput.setVisibleEventHandler(visibleHandler);
visibilityOutput.setFocusedEventHandler(focusedHandler);
visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler);
visibilityOutput.setInvisibleEventHandler(invisibleHandler);
return visibilityOutput;
}
private static TestOutput createTestOutput(
InternalNode node,
LayoutState layoutState,
LayoutOutput layoutOutput) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final TestOutput output = ComponentsPools.acquireTestOutput();
output.setTestKey(node.getTestKey());
output.setBounds(l, t, r, b);
output.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutOutput != null) {
output.setLayoutOutputId(layoutOutput.getId());
}
return output;
}
private static boolean isLayoutDirectionRTL(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if ((SDK_INT >= JELLY_BEAN_MR1)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) {
int layoutDirection = getLayoutDirection(context);
return layoutDirection == View.LAYOUT_DIRECTION_RTL;
}
return false;
}
@TargetApi(JELLY_BEAN_MR1)
private static int getLayoutDirection(Context context) {
return context.getResources().getConfiguration().getLayoutDirection();
}
/**
* Determine if a given {@link InternalNode} within the context of a given {@link LayoutState}
* requires to be wrapped inside a view.
*
* @see #needsHostView(InternalNode, LayoutState)
*/
private static boolean hasViewContent(InternalNode node, LayoutState layoutState) {
final Component<?> component = node.getComponent();
final NodeInfo nodeInfo = node.getNodeInfo();
final boolean implementsAccessibility =
(nodeInfo != null && nodeInfo.hasAccessibilityHandlers())
|| (component != null && component.getLifecycle().implementsAccessibility());
final int importantForAccessibility = node.getImportantForAccessibility();
// A component has accessibility content if:
// 1. Accessibility is currently enabled.
// 2. Accessibility hasn't been explicitly disabled on it
// i.e. IMPORTANT_FOR_ACCESSIBILITY_NO.
// 3. Any of these conditions are true:
// - It implements accessibility support.
// - It has a content description.
// - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES
// or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.
// IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host
// so that such flag is applied in the resulting view hierarchy after the component
// tree is mounted. Click handling is also considered accessibility content but
// this is already covered separately i.e. click handler is not null.
final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled
&& importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO
&& (implementsAccessibility
|| (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription()))
|| importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO);
final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers());
final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null);
final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null);
final boolean isFocusableSetTrue =
(nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE);
return hasTouchEventHandlers
|| hasViewTag
|| hasViewTags
|| hasAccessibilityContent
|| isFocusableSetTrue;
}
/**
* Collects layout outputs and release the layout tree. The layout outputs hold necessary
* information to be used by {@link MountState} to mount components into a {@link ComponentHost}.
* <p/>
* Whenever a component has view content (view tags, click handler, etc), a new host 'marker'
* is added for it. The mount pass will use the markers to decide which host should be used
* for each layout output. The root node unconditionally generates a layout output corresponding
* to the root host.
* <p/>
* The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts
* will be created at the right order when mounting. The host markers will be define which host
* each mounted artifacts will be attached to.
* <p/>
* At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled
* will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the
* host and the contents (including background/foreground). In all other cases instead we'll only
* try to re-use the hosts. In some cases the host's structure might change between two updates
* even if the component is of the same type. This can happen for example when a click listener is
* added. To avoid trying to re-use the wrong host type we explicitly check that after all the
* children for a subtree have been added (this is when the actual host type is resolved). If the
* host type changed compared to the one in the DiffNode we need to refresh the ids for the whole
* subtree in order to ensure that the MountState will unmount the subtree and mount it again on
* the correct host.
* <p/>
*
* @param node InternalNode to process.
* @param layoutState the LayoutState currently operating.
* @param parentDiffNode whether this method also populates the diff tree and assigns the root
* to mDiffTreeRoot.
*/
private static void collectResults(
InternalNode node,
LayoutState layoutState,
DiffNode parentDiffNode) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
final Component<?> component = node.getComponent();
// Early return if collecting results of a node holding a nested tree.
if (node.isNestedTreeHolder()) {
// If the nested tree is defined, it has been resolved during a measure call during
// layout calculation.
InternalNode nestedTree = resolveNestedTree(
node,
SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY),
SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY));
if (nestedTree == NULL_LAYOUT) {
return;
}
// Account for position of the holder node.
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
collectResults(nestedTree, layoutState, parentDiffNode);
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
return;
}
final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree;
final DiffNode currentDiffNode = node.getDiffNode();
final boolean shouldUseCachedOutputs =
isMountSpec(component) && currentDiffNode != null;
final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid();
final DiffNode diffNode;
if (shouldGenerateDiffTree) {
diffNode = createDiffNode(node, parentDiffNode);
if (parentDiffNode == null) {
layoutState.mDiffTreeRoot = diffNode;
}
} else {
diffNode = null;
}
final boolean needsHostView = needsHostView(node, layoutState);
final long currentHostMarker = layoutState.mCurrentHostMarker;
final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition;
int hostLayoutPosition = -1;
// 1. Insert a host LayoutOutput if we have some interactive content to be attached to.
if (needsHostView) {
hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode);
layoutState.mCurrentLevel++;
layoutState.mCurrentHostMarker =
layoutState.mMountableOutputs.get(hostLayoutPosition).getId();
layoutState.mCurrentHostOutputPosition = hostLayoutPosition;
}
// We need to take into account flattening when setting duplicate parent state. The parent after
// flattening may no longer exist. Therefore the value of duplicate parent state should only be
// true if the path between us (inclusive) and our inner/root host (exclusive) all are
// duplicate parent state.
final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState;
layoutState.mShouldDuplicateParentState =
needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled());
// Generate the layoutOutput for the given node.
final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState);
if (layoutOutput != null) {
final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
layoutOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_CONTENT,
previousId,
isCachedOutputUpdated);
}
// If we don't need to update this output we can safely re-use the display list from the
// previous output.
if (isCachedOutputUpdated) {
layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList());
}
// 2. Add background if defined.
final Reference<? extends Drawable> background = node.getBackground();
if (background != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) {
layoutOutput.getViewNodeInfo().setBackground(background);
} else {
final LayoutOutput convertBackground = (currentDiffNode != null)
? currentDiffNode.getBackground()
: null;
final LayoutOutput backgroundOutput = addDrawableComponent(
node,
layoutState,
convertBackground,
background,
LayoutOutput.TYPE_BACKGROUND);
if (diffNode != null) {
diffNode.setBackground(backgroundOutput);
}
}
}
// 3. Now add the MountSpec (either View or Drawable) to the Outputs.
if (isMountSpec(component)) {
// Notify component about its final size.
component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component);
addMountableOutput(layoutState, layoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
layoutOutput,
layoutState.mMountableOutputs.size() - 1);
if (diffNode != null) {
diffNode.setContent(layoutOutput);
}
}
// 4. Add border color if defined.
if (node.shouldDrawBorders()) {
final LayoutOutput convertBorder = (currentDiffNode != null)
? currentDiffNode.getBorder()
: null;
final LayoutOutput borderOutput = addDrawableComponent(
node,
layoutState,
convertBorder,
getBorderColorDrawable(node),
LayoutOutput.TYPE_BORDER);
if (diffNode != null) {
diffNode.setBorder(borderOutput);
}
}
// 5. Extract the Transitions.
if (SDK_INT >= ICE_CREAM_SANDWICH) {
if (node.getTransitionKey() != null) {
layoutState
.getOrCreateTransitionContext()
.addTransitionKey(node.getTransitionKey());
}
if (component != null) {
Transition transition = component.getLifecycle().onLayoutTransition(
layoutState.mContext,
component);
if (transition != null) {
layoutState.getOrCreateTransitionContext().add(transition);
}
}
}
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
// We must process the nodes in order so that the layout state output order is correct.
for (int i = 0, size = node.getChildCount(); i < size; i++) {
collectResults(
node.getChildAt(i),
layoutState,
diffNode);
}
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
// 6. Add foreground if defined.
final Reference<? extends Drawable> foreground = node.getForeground();
if (foreground != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) {
layoutOutput.getViewNodeInfo().setForeground(foreground);
} else {
final LayoutOutput convertForeground = (currentDiffNode != null)
? currentDiffNode.getForeground()
: null;
final LayoutOutput foregroundOutput = addDrawableComponent(
node,
layoutState,
convertForeground,
foreground,
LayoutOutput.TYPE_FOREGROUND);
if (diffNode != null) {
diffNode.setForeground(foregroundOutput);
}
}
}
// 7. Add VisibilityOutputs if any visibility-related event handlers are present.
if (node.hasVisibilityHandlers()) {
final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState);
final long previousId =
shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId(
visibilityOutput,
layoutState.mCurrentLevel,
previousId);
layoutState.mVisibilityOutputs.add(visibilityOutput);
if (diffNode != null) {
diffNode.setVisibilityOutput(visibilityOutput);
}
}
// 8. If we're in a testing environment, maintain an additional data structure with
// information about nodes that we can query later.
if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) {
final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput);
layoutState.mTestOutputs.add(testOutput);
}
// All children for the given host have been added, restore the previous
// host, level, and duplicate parent state value in the recursive queue.
if (layoutState.mCurrentHostMarker != currentHostMarker) {
layoutState.mCurrentHostMarker = currentHostMarker;
layoutState.mCurrentHostOutputPosition = currentHostOutputPosition;
layoutState.mCurrentLevel
}
layoutState.mShouldDuplicateParentState = shouldDuplicateParentState;
Collections.sort(layoutState.mMountableOutputTops, sTopsComparator);
Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator);
}
private static void calculateAndSetHostOutputIdAndUpdateState(
InternalNode node,
LayoutOutput hostOutput,
LayoutState layoutState,
boolean isCachedOutputUpdated) {
if (layoutState.isLayoutRoot(node)) {
// The root host (ComponentView) always has ID 0 and is unconditionally
// set as dirty i.e. no need to use shouldComponentUpdate().
hostOutput.setId(ROOT_HOST_ID);
// Special case where the host marker of the root host is pointing to itself.
hostOutput.setHostMarker(ROOT_HOST_ID);
hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY);
} else {
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
hostOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_HOST,
-1,
isCachedOutputUpdated);
}
}
private static LayoutOutput addDrawableComponent(
InternalNode node,
LayoutState layoutState,
LayoutOutput recycle,
Reference<? extends Drawable> reference,
@LayoutOutput.LayoutOutputType int type) {
final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference);
drawableComponent.setScopedContext(
ComponentContext.withComponentScope(node.getContext(), drawableComponent));
final boolean isOutputUpdated;
if (recycle != null) {
isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate(
recycle.getComponent(),
drawableComponent);
} else {
isOutputUpdated = false;
}
final long previousId = recycle != null ? recycle.getId() : -1;
final LayoutOutput output = addDrawableLayoutOutput(
drawableComponent,
layoutState,
node,
type,
previousId,
isOutputUpdated);
return output;
}
private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) {
if (!node.shouldDrawBorders()) {
throw new RuntimeException("This node does not support drawing border color");
}
return BorderColorDrawableReference.create(node.getContext())
.color(node.getBorderColor())
.borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT)))
.borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP)))
.borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT)))
.borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM)))
.build();
}
private static void addLayoutOutputIdToPositionsMap(
LongSparseArray outputsIdToPositionMap,
LayoutOutput layoutOutput,
int position) {
if (outputsIdToPositionMap != null) {
outputsIdToPositionMap.put(layoutOutput.getId(), position);
}
}
private static LayoutOutput addDrawableLayoutOutput(
Component<DrawableComponent> drawableComponent,
LayoutState layoutState,
InternalNode node,
@LayoutOutput.LayoutOutputType int layoutOutputType,
long previousId,
boolean isCachedOutputUpdated) {
drawableComponent.getLifecycle().onBoundsDefined(
layoutState.mContext,
node,
drawableComponent);
final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput(
drawableComponent,
layoutState,
node);
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
drawableLayoutOutput,
layoutState.mCurrentLevel,
layoutOutputType,
previousId,
isCachedOutputUpdated);
addMountableOutput(layoutState, drawableLayoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
drawableLayoutOutput,
layoutState.mMountableOutputs.size() - 1);
return drawableLayoutOutput;
}
static void releaseNodeTree(InternalNode node, boolean isNestedTree) {
if (node == NULL_LAYOUT) {
throw new IllegalArgumentException("Cannot release a null node tree");
}
for (int i = node.getChildCount() - 1; i >= 0; i
final InternalNode child = node.getChildAt(i);
if (isNestedTree && node.hasNewLayout()) {
node.markLayoutSeen();
}
// A node must be detached from its parent *before* being released (otherwise the parent would
// retain a reference to a node that may get re-used by another thread)
node.removeChildAt(i);
releaseNodeTree(child, isNestedTree);
}
if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) {
releaseNodeTree(node.getNestedTree(), true);
}
ComponentsPools.release(node);
}
/**
* If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an
* HostComponent in the Outputs such as it will be used as a HostView at Mount time. View
* MountSpec are not allowed.
*
* @return The position the HostLayoutOutput was inserted.
*/
private static int addHostLayoutOutput(
InternalNode node,
LayoutState layoutState,
DiffNode diffNode) {
final Component<?> component = node.getComponent();
// Only the root host is allowed to wrap view mount specs as a layout output
// is unconditionally added for it.
if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) {
throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View");
}
final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node);
// The component of the hostLayoutOutput will be set later after all the
// children got processed.
addMountableOutput(layoutState, hostLayoutOutput);
final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1;
if (diffNode != null) {
diffNode.setHost(hostLayoutOutput);
}
calculateAndSetHostOutputIdAndUpdateState(
node,
hostLayoutOutput,
layoutState,
false);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
hostLayoutOutput,
hostOutputPosition);
return hostOutputPosition;
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec,
boolean shouldGenerateDiffTree,
DiffNode previousDiffTreeRoot) {
// Detect errors internal to components
component.markLayoutStarted();
LayoutState layoutState = ComponentsPools.acquireLayoutState(c);
layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree;
layoutState.mComponentTreeId = componentTreeId;
layoutState.mAccessibilityManager =
(AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE);
layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager);
layoutState.mComponent = component;
layoutState.mWidthSpec = widthSpec;
layoutState.mHeightSpec = heightSpec;
component.applyStateUpdates(c);
final InternalNode root = createAndMeasureTreeForComponent(
component.getScopedContext(),
component,
null, // nestedTreeHolder is null because this is measuring the root component tree.
widthSpec,
heightSpec,
previousDiffTreeRoot);
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.EXACTLY:
layoutState.mWidth = SizeSpec.getSize(widthSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mWidth = root.getWidth();
break;
}
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.EXACTLY:
layoutState.mHeight = SizeSpec.getSize(heightSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mHeight = root.getHeight();
break;
}
layoutState.mLayoutStateOutputIdCalculator.clear();
// Reset markers before collecting layout outputs.
layoutState.mCurrentHostMarker = -1;
final ComponentsLogger logger = c.getLogger();
if (root == NULL_LAYOUT) {
return layoutState;
}
layoutState.mLayoutRoot = root;
ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName());
if (logger != null) {
logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag());
}
collectResults(root, layoutState, null);
if (logger != null) {
logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection();
if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) {
releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */);
layoutState.mLayoutRoot = null;
}
if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) {
collectDisplayLists(layoutState);
}
return layoutState;
}
void preAllocateMountContent() {
if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
final Component component = mMountableOutputs.get(i).getComponent();
if (Component.isMountViewSpec(component)) {
final ComponentLifecycle lifecycle = component.getLifecycle();
if (!lifecycle.hasBeenPreallocated()) {
final int poolSize = lifecycle.poolSize();
int insertedCount = 0;
while (insertedCount < poolSize &&
ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) {
ComponentsPools.release(
mContext,
lifecycle,
lifecycle.createMountContent(mContext));
insertedCount++;
}
lifecycle.setWasPreallocated();
}
}
}
}
}
private static void collectDisplayLists(LayoutState layoutState) {
final Rect rect = new Rect();
final ComponentContext context = layoutState.mContext;
final Activity activity = findActivityInContext(context);
if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) {
return;
}
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
final Component component = output.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
if (lifecycle.shouldUseDisplayList()) {
output.getMountBounds(rect);
if (output.getDisplayList() != null && output.getDisplayList().isValid()) {
// This output already has a valid DisplayList from diffing. No need to re-create it.
// Just update its bounds.
try {
output.getDisplayList().setBounds(rect.left, rect.top, rect.right, rect.bottom);
continue;
} catch (DisplayListException e) {
// Nothing to do here.
}
}
final DisplayList displayList = DisplayList.createDisplayList(
lifecycle.getClass().getSimpleName());
if (displayList != null) {
Drawable drawable =
(Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getId());
if (drawable == null) {
drawable = (Drawable) lifecycle.createMountContent(context);
}
final LayoutOutput clickableOutput = findInteractiveRoot(layoutState, output);
boolean isStateEnabled = false;
if (clickableOutput != null && clickableOutput.getNodeInfo() != null) {
final NodeInfo nodeInfo = clickableOutput.getNodeInfo();
if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) {
isStateEnabled = true;
}
}
if (isStateEnabled) {
drawable.setState(DRAWABLE_STATE_ENABLED);
} else {
drawable.setState(DRAWABLE_STATE_NOT_ENABLED);
}
lifecycle.mount(
context,
drawable,
component);
lifecycle.bind(context, drawable, component);
output.getMountBounds(rect);
drawable.setBounds(0, 0, rect.width(), rect.height());
try {
final Canvas canvas = displayList.start(rect.width(), rect.height());
drawable.draw(canvas);
displayList.end(canvas);
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
output.setDisplayList(displayList);
} catch (DisplayListException e) {
// Display list creation failed. Make sure the DisplayList for this output is set
// to null.
output.setDisplayList(null);
}
lifecycle.unbind(context, drawable, component);
lifecycle.unmount(context, drawable, component);
ComponentsPools.release(context, lifecycle, drawable);
}
}
}
}
private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) {
if (output.getId() == ROOT_HOST_ID) {
return output;
}
if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) {
final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker());
if (parentPosition >= 0) {
final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition);
if (parent == null) {
return null;
}
return findInteractiveRoot(layoutState, parent);
}
return null;
}
return output;
}
private static boolean isActivityDestroyed(Activity activity) {
if (SDK_INT >= JELLY_BEAN_MR1) {
return activity.isDestroyed();
}
return false;
}
private static Activity findActivityInContext(Context context) {
if (context instanceof Activity) {
return (Activity) context;
} else if (context instanceof ContextWrapper) {
return findActivityInContext(((ContextWrapper) context).getBaseContext());
}
return null;
}
@VisibleForTesting
static <T extends ComponentLifecycle> InternalNode createTree(
Component<T> component,
ComponentContext context) {
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CREATE_LAYOUT, context, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddTag(EVENT_CREATE_LAYOUT, context, component.getSimpleName());
}
final InternalNode root = (InternalNode) component.getLifecycle().createLayout(
context,
component,
true /* resolveNestedTree */);
if (logger != null) {
logger.eventEnd(EVENT_CREATE_LAYOUT, context, ACTION_SUCCESS);
}
return root;
}
@VisibleForTesting
static void measureTree(
InternalNode root,
int widthSpec,
int heightSpec,
DiffNode previousDiffTreeRoot) {
final ComponentContext context = root.getContext();
final Component component = root.getComponent();
ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName());
if (YogaConstants.isUndefined(root.getStyleWidth())) {
root.setStyleWidthFromSpec(widthSpec);
}
if (YogaConstants.isUndefined(root.getStyleHeight())) {
root.setStyleHeightFromSpec(heightSpec);
}
if (previousDiffTreeRoot != null) {
ComponentsSystrace.beginSection("applyDiffNode");
applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot);
ComponentsSystrace.endSection(/* applyDiffNode */);
}
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CSS_LAYOUT, component, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddParam(
EVENT_CSS_LAYOUT,
component,
PARAM_TREE_DIFF_ENABLED,
String.valueOf(previousDiffTreeRoot != null));
}
root.calculateLayout(
SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(widthSpec),
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(heightSpec));
if (logger != null) {
logger.eventEnd(EVENT_CSS_LAYOUT, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection(/* measureTree */);
}
/**
* Create and measure the nested tree or return the cached one for the same size specs.
*/
static InternalNode resolveNestedTree(
InternalNode nestedTreeHolder,
int widthSpec,
int heightSpec) {
final ComponentContext context = nestedTreeHolder.getContext();
final Component<?> component = nestedTreeHolder.getComponent();
InternalNode nestedTree = nestedTreeHolder.getNestedTree();
if (nestedTree == null
|| !hasCompatibleSizeSpec(
nestedTree.getLastWidthSpec(),
nestedTree.getLastHeightSpec(),
widthSpec,
heightSpec,
nestedTree.getLastMeasuredWidth(),
nestedTree.getLastMeasuredHeight())) {
if (nestedTree != null) {
if (nestedTree != NULL_LAYOUT) {
releaseNodeTree(nestedTree, true /* isNestedTree */);
}
nestedTree = null;
}
if (component.hasCachedLayout()) {
final InternalNode cachedLayout = component.getCachedLayout();
final boolean hasCompatibleLayoutDirection =
InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout);
// Transfer the cached layout to the node without releasing it if it's compatible.
if (hasCompatibleLayoutDirection &&
hasCompatibleSizeSpec(
cachedLayout.getLastWidthSpec(),
cachedLayout.getLastHeightSpec(),
widthSpec,
heightSpec,
cachedLayout.getLastMeasuredWidth(),
cachedLayout.getLastMeasuredHeight())) {
nestedTree = cachedLayout;
component.clearCachedLayout();
} else {
component.releaseCachedLayout();
}
}
if (nestedTree == null) {
nestedTree = createAndMeasureTreeForComponent(
context,
component,
nestedTreeHolder,
widthSpec,
heightSpec,
nestedTreeHolder.getDiffNode()); // Previously set while traversing the holder's tree.
nestedTree.setLastWidthSpec(widthSpec);
nestedTree.setLastHeightSpec(heightSpec);
nestedTree.setLastMeasuredHeight(nestedTree.getHeight());
nestedTree.setLastMeasuredWidth(nestedTree.getWidth());
}
nestedTreeHolder.setNestedTree(nestedTree);
}
// This is checking only nested tree roots however it will be moved to check all the tree roots.
InternalNode.assertContextSpecificStyleNotSet(nestedTree);
return nestedTree;
}
/**
* Create and measure a component with the given size specs.
*/
static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
int widthSpec,
int heightSpec) {
return createAndMeasureTreeForComponent(c, component, null, widthSpec, heightSpec, null);
}
private static InternalNode createAndMeasureTreeForComponent(
ComponentContext c,
Component component,
InternalNode nestedTreeHolder, // This will be set only if we are resolving a nested tree.
int widthSpec,
int heightSpec,
DiffNode diffTreeRoot) {
// Account for the size specs in ComponentContext in case the tree is a NestedTree.
final int previousWidthSpec = c.getWidthSpec();
final int previousHeightSpec = c.getHeightSpec();
final boolean hasNestedTreeHolder = nestedTreeHolder != null;
c.setWidthSpec(widthSpec);
c.setHeightSpec(heightSpec);
if (hasNestedTreeHolder) {
c.setTreeProps(nestedTreeHolder.getPendingTreeProps());
}
final InternalNode root = createTree(
component,
c);
if (hasNestedTreeHolder) {
c.setTreeProps(null);
}
c.setWidthSpec(previousWidthSpec);
c.setHeightSpec(previousHeightSpec);
if (root == NULL_LAYOUT) {
return root;
}
// If measuring a ComponentTree with a LayoutSpecWithSizeSpec at the root, the nested tree
// holder argument will be null.
if (hasNestedTreeHolder && isLayoutSpecWithSizeSpec(component)) {
// Transfer information from the holder node to the nested tree root before measurement.
nestedTreeHolder.copyInto(root);
diffTreeRoot = nestedTreeHolder.getDiffNode();
} else if (root.getStyleDirection() == com.facebook.yoga.YogaDirection.INHERIT
&& LayoutState.isLayoutDirectionRTL(c)) {
root.layoutDirection(YogaDirection.RTL);
}
measureTree(
root,
widthSpec,
heightSpec,
diffTreeRoot);
return root;
}
static DiffNode createDiffNode(InternalNode node, DiffNode parent) {
ComponentsSystrace.beginSection("diff_node_creation");
DiffNode diffNode = ComponentsPools.acquireDiffNode();
diffNode.setLastWidthSpec(node.getLastWidthSpec());
diffNode.setLastHeightSpec(node.getLastHeightSpec());
diffNode.setLastMeasuredWidth(node.getLastMeasuredWidth());
diffNode.setLastMeasuredHeight(node.getLastMeasuredHeight());
diffNode.setComponent(node.getComponent());
if (parent != null) {
parent.addChild(diffNode);
}
ComponentsSystrace.endSection();
return diffNode;
}
boolean isCompatibleSpec(int widthSpec, int heightSpec) {
final boolean widthIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mWidthSpec,
widthSpec,
mWidth);
final boolean heightIsCompatible =
MeasureComparisonUtils.isMeasureSpecCompatible(
mHeightSpec,
heightSpec,
mHeight);
return widthIsCompatible && heightIsCompatible;
}
boolean isCompatibleAccessibility() {
return isAccessibilityEnabled(mAccessibilityManager) == mAccessibilityEnabled;
}
private static boolean isAccessibilityEnabled(AccessibilityManager accessibilityManager) {
return accessibilityManager.isEnabled() &&
AccessibilityManagerCompat.isTouchExplorationEnabled(accessibilityManager);
}
/**
* Traverses the layoutTree and the diffTree recursively. If a layoutNode has a compatible host
* type {@link LayoutState#hostIsCompatible} it assigns the DiffNode to the layout node in order
* to try to re-use the LayoutOutputs that will be generated by {@link
* LayoutState#collectResults(InternalNode, LayoutState, DiffNode)}. If a layoutNode
* component returns false when shouldComponentUpdate is called with the DiffNode Component it
* also tries to re-use the old measurements and therefore marks as valid the cachedMeasures for
* the whole component subtree.
*
* @param layoutNode the root of the LayoutTree
* @param diffNode the root of the diffTree
*
* @return true if the layout node requires updating, false if it can re-use the measurements
* from the diff node.
*/
static boolean applyDiffNodeToUnchangedNodes(InternalNode layoutNode, DiffNode diffNode) {
// Root of the main tree or of a nested tree.
final boolean isTreeRoot = layoutNode.getParent() == null;
if (isLayoutSpecWithSizeSpec(layoutNode.getComponent()) && !isTreeRoot) {
layoutNode.setDiffNode(diffNode);
return true;
}
if (!hostIsCompatible(layoutNode, diffNode)) {
return true;
}
layoutNode.setDiffNode(diffNode);
final int layoutCount = layoutNode.getChildCount();
final int diffCount = diffNode.getChildCount();
// Layout node needs to be updated if:
// - it has a different number of children.
// - one of its children needs updating.
// - the node itself declares that it needs updating.
boolean shouldUpdate = layoutCount != diffCount;
for (int i = 0; i < layoutCount && i < diffCount; i++) {
// ensure that we always run for all children.
boolean shouldUpdateChild =
applyDiffNodeToUnchangedNodes(
layoutNode.getChildAt(i),
diffNode.getChildAt(i));
shouldUpdate |= shouldUpdateChild;
}
shouldUpdate |= shouldComponentUpdate(layoutNode, diffNode);
if (!shouldUpdate) {
applyDiffNodeToLayoutNode(layoutNode, diffNode);
}
return shouldUpdate;
}
/**
* Copies the inter stage state (if any) from the DiffNode's component to the layout node's
* component, and declares that the cached measures on the diff node are valid for the layout
* node.
*/
private static void applyDiffNodeToLayoutNode(InternalNode layoutNode, DiffNode diffNode) {
final Component component = layoutNode.getComponent();
if (component != null) {
component.copyInterStageImpl(diffNode.getComponent());
}
layoutNode.setCachedMeasuresValid(true);
}
/**
* Returns true either if the two nodes have the same Component type or if both don't have a
* Component.
*/
private static boolean hostIsCompatible(InternalNode node, DiffNode diffNode) {
if (diffNode == null) {
return false;
}
return isSameComponentType(node.getComponent(), diffNode.getComponent());
}
private static boolean isSameComponentType(Component a, Component b) {
if (a == b) {
return true;
} else if (a == null || b == null) {
return false;
}
return a.getLifecycle().getClass().equals(b.getLifecycle().getClass());
}
private static boolean shouldComponentUpdate(InternalNode layoutNode, DiffNode diffNode) {
if (diffNode == null) {
return true;
}
final Component component = layoutNode.getComponent();
if (component != null) {
return component.getLifecycle().shouldComponentUpdate(component, diffNode.getComponent());
}
return true;
}
boolean isCompatibleComponentAndSpec(
int componentId,
int widthSpec,
int heightSpec) {
return mComponent.getId() == componentId && isCompatibleSpec(widthSpec, heightSpec);
}
boolean isCompatibleSize(int width, int height) {
return mWidth == width && mHeight == height;
}
boolean isComponentId(int componentId) {
return mComponent.getId() == componentId;
}
int getMountableOutputCount() {
return mMountableOutputs.size(); |
package com.filestack.model;
import com.filestack.model.transform.base.ImageTransform;
import com.filestack.util.Upload;
import com.filestack.util.UploadOptions;
import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
import java.io.IOException;
import java.util.concurrent.Callable;
/**
* Wrapper for communicating with the Filestack REST API.
* Instantiate with an API Key from the Developer Portal.
*/
public class FilestackClient {
private String apiKey;
private Security security;
/**
* Constructs an instance without security.
*
* @param apiKey account key from the dev portal
*/
public FilestackClient(String apiKey) {
this.apiKey = apiKey;
}
public FilestackClient(String apiKey, Security security) {
this.apiKey = apiKey;
this.security = security;
}
/**
* Upload local file to Filestack using default storage options.
*
* @param filepath path to the file, can be local or absolute
* @return new {@link FileLink} referencing file
* @throws IOException for network failures or invalid security
*/
public FileLink upload(String filepath) throws IOException {
UploadOptions defaultOptions = new UploadOptions.Builder().build();
return upload(filepath, defaultOptions);
}
public FileLink upload(String filepath, UploadOptions options) throws IOException {
Upload upload = new Upload(filepath, this, options);
return upload.run();
}
// Async method wrappers
/**
* Async, observable version of {@link #upload(String)}.
* Throws same exceptions.
*/
public Single<FileLink> uploadAsync(String filepath) {
UploadOptions defaultOptions = new UploadOptions.Builder().build();
return uploadAsync(filepath, defaultOptions);
}
/**
* Async, observable version of {@link #upload(String, UploadOptions)}.
* Throws same exceptions.
*/
public Single<FileLink> uploadAsync(final String filepath, final UploadOptions options) {
return Single.fromCallable(new Callable<FileLink>() {
@Override
public FileLink call() throws IOException {
return upload(filepath, options);
}
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.single());
}
/**
* Creates an image transformation object for this file.
* A transformation call isn't made directly by this method.
*
* @return {@link ImageTransform ImageTransform} instance configured for this file
*/
public ImageTransform imageTransform(String url) {
return new ImageTransform(this, url);
}
public String getApiKey() {
return apiKey;
}
public Security getSecurity() {
return security;
}
} |
package com.github.intangir.Tweaks;
import java.io.File;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.inventory.ItemStack;
public class Vehicles extends Tweak
{
Vehicles(Tweaks plugin) {
super(plugin);
CONFIG_FILE = new File(plugin.getDataFolder(), "vehicles.yml");
TWEAK_NAME = "Tweak_Vehicles";
TWEAK_VERSION = "1.0";
fixExitMinecart = true;
fixExitBoat = true;
fixExitHorse = true;
breakSwordInHand = true;
}
private boolean fixExitMinecart;
private boolean fixExitBoat;
private boolean fixExitHorse;
private boolean breakSwordInHand;
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent e) {
final LivingEntity exiter = e.getExited();
final Vehicle vehicle = e.getVehicle();
if(exiter instanceof Player) {
if( (fixExitMinecart && vehicle instanceof Minecart) ||
(fixExitBoat && vehicle instanceof Boat) ||
(fixExitHorse && vehicle instanceof Horse)) {
final Location fixLoc = exiter.getLocation().add(0, 0.5, 0);
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
exiter.teleport(fixLoc);
ItemStack hand = ((Player)exiter).getItemInHand();
// auto destroy boat/minecart if they are a holding a sword
if(breakSwordInHand && hand != null && hand.getType().toString().contains("SWORD")) {
ItemStack item = null;
if(vehicle instanceof Minecart) {
item = new ItemStack(Material.MINECART);
} else if(vehicle instanceof Boat) {
item = new ItemStack(Material.BOAT);
}
if(item != null) {
exiter.getWorld().dropItem(fixLoc, item);
vehicle.remove();
}
}
}
}, 2);
}
}
}
} |
package com.gooddata.dataset;
import com.gooddata.AbstractService;
import com.gooddata.gdc.DataStoreService;
import com.gooddata.project.Project;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
public class DatasetService extends AbstractService {
private static final String MANIFEST_FILE_NAME = "upload_info.json";
private final DataStoreService dataStoreService;
private final static ObjectMapper mapper = new ObjectMapper();
public DatasetService(RestTemplate restTemplate, DataStoreService dataStoreService) {
super(restTemplate);
this.dataStoreService = dataStoreService;
}
public DatasetManifest getDatasetManifest(Project project, String datasetId) {
return restTemplate.getForObject(DatasetManifest.URI, DatasetManifest.class, project.getId(), datasetId);
}
public void loadDataset(Project project, InputStream dataset, DatasetManifest manifest) {
final String dirPath = getDirPath(project);
try {
dataStoreService.upload(dirPath + manifest.getFile(), dataset);
final String manifestJson = mapper.writeValueAsString(manifest);
dataStoreService.upload(dirPath + MANIFEST_FILE_NAME, IOUtils.toInputStream(manifestJson));
final PullTask pullTask = restTemplate.postForObject(Pull.URI, new Pull(dirPath), PullTask.class, project.getId());
final PullTaskStatus taskStatus = poll(URI.create(pullTask.getUri()), new ConditionCallback() {
@Override
public boolean finished(ClientHttpResponse response) throws IOException {
final PullTaskStatus status = extractData(response, PullTaskStatus.class);
return status.isFinished();
}
}, PullTaskStatus.class);
if (!taskStatus.isSuccess()) {
throw new DatasetException("ETL pull finished with status " + taskStatus.getStatus());
}
} catch (IOException e) {
throw new DatasetException("Unable to serialize manifest", e);
} finally {
dataStoreService.delete(dirPath);
}
}
private String getDirPath(Project project) {
return new StringBuilder("/")
.append(project.getId())
.append("_")
.append(RandomStringUtils.randomAlphabetic(3))
.append("/")
.toString();
}
public void loadDataset(Project project, String datasetId, InputStream dataset) {
loadDataset(project, dataset, getDatasetManifest(project, datasetId));
}
} |
package com.greatwebguy.application;
import java.io.InputStream;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.GlyphFont;
import org.controlsfx.glyphfont.GlyphFontRegistry;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.TextAlignment;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
public class MobTime extends Application {
private Stage miniTimer;
private Stage mainStage;
@Override
public void start(Stage stage) {
try {
mainStage = stage;
InputStream is = getClass().getResourceAsStream("fontawesome-webfont.ttf");
GlyphFont fa = new FontAwesome(is);
GlyphFontRegistry.register(fa);
Parent root = FXMLLoader.load(getClass().getResource("application.fxml"));
stage.setTitle("MobTime");
stage.getIcons().add(new Image(getClass().getResourceAsStream("icon.png")));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
openMiniTimer();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(final WindowEvent event) {
miniTimer.close();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
private void openMiniTimer() {
if (miniTimer == null) {
int height = 40;
int width = 50;
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
miniTimer = new Stage();
miniTimer.initStyle(StageStyle.TRANSPARENT);
miniTimer.setX(screenBounds.getMinX() + screenBounds.getWidth() - width);
miniTimer.setY(screenBounds.getMinY() + screenBounds.getHeight() + 2 - height);
Label turn = new Label();
turn.setPrefWidth(width);
turn.setPrefHeight(height - 25);
turn.setTextAlignment(TextAlignment.CENTER);
turn.setAlignment(Pos.CENTER);
turn.setStyle("-fx-background-color: #000000; -fx-text-fill: white; -fx-font-size: 10px;");
turn.textProperty().bind(Settings.instance().userName);
Label timer = new Label();
timer.setPrefWidth(width);
timer.setPrefHeight(height - 10);
timer.textProperty().bind(TimeController.timeMinutes);
timer.setTextAlignment(TextAlignment.CENTER);
timer.setAlignment(Pos.CENTER);
timer.setTextFill(Paint.valueOf("white"));
timer.styleProperty().bind(TimeController.paneColor);
Label nextTurn = new Label();
nextTurn.setPrefWidth(width);
nextTurn.setPrefHeight(5);
nextTurn.setTextAlignment(TextAlignment.CENTER);
nextTurn.setAlignment(Pos.CENTER);
nextTurn.setStyle("-fx-background-color: #000000; -fx-text-fill: white; -fx-font-size: 9px;");
nextTurn.textProperty().bind(Settings.instance().nextUserMessage);
VBox box = new VBox();
box.setAlignment(Pos.CENTER);
box.getChildren().add(turn);
box.getChildren().add(timer);
box.getChildren().add(nextTurn);
box.setCenterShape(true);
final Scene scene = new Scene(box, width, height);
scene.setFill(Color.TRANSPARENT);
miniTimer.setScene(scene);
miniTimer.setAlwaysOnTop(true);
miniTimer.show();
box.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
showMainWindow();
}
});
}
}
public void showMainWindow() {
Stage window = (Stage) mainStage.getScene().getWindow();
window.toFront();
window.requestFocus();
}
} |
package com.groupbyinc.api.model;
import com.groupbyinc.common.jackson.annotation.JsonIgnore;
import com.groupbyinc.common.jackson.annotation.JsonInclude;
import com.groupbyinc.common.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
/**
* <code>
* The Navigation object represents dynamic navigation sent back from the search engine.
* Each navigation item has the following properties:
*
* - `id`: an MD5 hash of the name.
* - `name`: the name of the metadata used to create this dynamic navigation option.
* - `displayName`: the human digestible version of this name.
* - `range`: true if the navigation option is a range.
* - `or`: true if the navigation option supports or-queries.
* - `refinements`: A list of the refinement values for this dynamic navigation
* - `sort`: If specified, an object detailing the sort field and sort order
*
* </code>
*
* @author will
*/
public class Navigation {
public enum Sort {
Count_Ascending,
Count_Descending,
Value_Ascending,
Value_Descending // NOSONAR
}
@JsonProperty("_id") private String id;
private String name;
private String displayName;
private boolean range = false;
private boolean or = false;
private Boolean ignored;
private Sort sort;
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT) private Boolean moreRefinements = Boolean.FALSE;
private List<Refinement> refinements = new ArrayList<Refinement>();
private List<Metadata> metadata = new ArrayList<Metadata>();
/**
* <code>
* Default constructor
* </code>
*/
public Navigation() {
// default constructor
}
/**
* @return The name of the dynamic navigation attribute. This is the name of
* the metadata that was uploaded as part of the feed
*/
public String getName() {
return name;
}
/**
* @param name The name of the navigation
* @return
*/
public Navigation setName(String name) {
this.name = name;
return this;
}
/**
* @return The human readable label for this navigation.
*/
public String getDisplayName() {
return displayName;
}
/**
* @param displayName Set the display name
* @return
*/
public Navigation setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* @return A list of refinement values that represent the ways in which you
* can filter data.
*/
public List<Refinement> getRefinements() {
return refinements;
}
/**
* @param refinements The refinement values
* @return
*/
public Navigation setRefinements(List<Refinement> refinements) {
this.refinements = refinements;
return this;
}
/**
* @return A MD5 of the name, which means that this navigation ID is unique.
*/
public String getId() {
return id;
}
/**
* @param id Set the ID
* @return
*/
public Navigation setId(String id) {
this.id = id;
return this;
}
/**
* @return True if this navigation is a of type range.
*/
@JsonProperty("range")
public boolean isRange() {
return range;
}
/**
* @param range Set range
* @return
*/
public Navigation setRange(boolean range) {
this.range = range;
return this;
}
/**
* <code>
* If you are using the this object within a JSP you will not be able to reference it directly as
* `navigation.or` is a reserved field in JSTL. Instead reference it within quotes:
*
* <div>
* ${navigation['or'] ? 'Or Query' : 'And Query'}
* </div>
*
* </code>
* @return Is this dynamic navigation going to be treated as an OR field by the search service.
*/
@JsonProperty("or")
public boolean isOr() {
return or;
}
/**
* @param or
* Set whether this is an OR field
*
* @return
*/
public Navigation setOr(boolean or) {
this.or = or;
return this;
}
/**
* <code>
* Will return one of the following sort types:
*
* Count_Ascending, Count_Descending
* Value_Ascending, Value_Descending
*
* </code>
*
* @return The sort option for this navigation.
*/
public Sort getSort() {
return sort;
}
/**
* <code>
* Helper method
* </code>
*
* @param sort Set the sort by string.
*/
public Navigation setSort(String sort) {
this.sort = Sort.valueOf(sort);
return this;
}
/**
* @param sort Set the sort type
*/
@JsonIgnore
public Navigation setSort(Sort sort) {
this.sort = sort;
return this;
}
/**
* <code>
* A list of metadata key-value pairs for a specified navigation item. Each value
* contains the following properties:
*
* - key: a string containing the attribute name
* - value: a string containing the attribute value
*
* </code>
*
* @return A list of metadata elements
*/
public List<Metadata> getMetadata() {
return metadata;
}
/**
* @param metadata Set the metadata
* @return
*/
public Navigation setMetadata(List<Metadata> metadata) {
this.metadata = metadata;
return this;
}
/**
* <code>
* True if this navigation has more refinement values than the ones returned.
* </code>
*
* @return True if this navigation has more refinement values than the ones returned, false otherwise.
*/
public Boolean isMoreRefinements() {
return moreRefinements;
}
/**
* @param moreRefinements True if this navigation has more refinement values than the ones returned.
* @return
*/
public Navigation setMoreRefinements(Boolean moreRefinements) {
this.moreRefinements = moreRefinements;
return this;
}
/**
* <code>
* True if this navigation has been ignored.
* </code>
*
* @return True if this navigation was ignored, false otherwise.
*/
public Boolean isIgnored() {
return ignored;
}
/**
* @param ignored True if this navigation has been ignored.
* @return
*/
public Navigation setIgnored(Boolean ignored) {
this.ignored = ignored;
return this;
}
} |
package com.ideaheap;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamsBasedCalculator {
public Map<String, String> getStringTransition(
final Set<String> stringSet,
final Map<String, Double> stringCosts) {
return stringCosts.keySet().parallelStream().collect(
Collectors.toConcurrentMap(
(state) -> state,
(state) -> stringTransitionCost(state, stringSet, stringCosts)
)
);
}
private String stringTransitionCost(
final String state,
final Set<String> stringSet,
final Map<String, Double> expectedUtilities) {
return stringSet.stream().max(
Comparator.comparing(
act -> calculateExpectedUtility(state, act, expectedUtilities)
)
).get();
}
private Double calculateExpectedUtility(
String state,
String act,
Map<String, Double> expectedUtilities) {
return expectedUtilities
.entrySet()
.stream()
.mapToDouble(
n -> getStateProbability(state, act, n.getKey()) * n.getValue()
).sum();
}
private Double getStateProbability(String state, String act, String key) {
return 5.0;
}
} |
package com.imcode.imcms.model;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@NoArgsConstructor
public abstract class CategoryType implements Serializable {
private static final long serialVersionUID = 6975350692159491957L;
protected CategoryType(CategoryType from) {
setId(from.getId());
setName(from.getName());
setMultiSelect(from.isMultiSelect());
setInherited(from.isInherited());
}
public abstract boolean isMultiSelect();
public abstract void setMultiSelect(boolean multiSelect);
public abstract boolean isInherited();
public abstract void setInherited(boolean isInherited);
public abstract boolean isImageArchive();
public abstract void setImageArchive(boolean imageArchive);
public abstract Integer getId();
public abstract void setId(Integer id);
public abstract String getName();
public abstract void setName(String name);
} |
package com.mattcorallo.relaynode;
import com.google.bitcoin.core.*;
import com.google.bitcoin.networkabstraction.NioClientManager;
import com.google.bitcoin.networkabstraction.NioServer;
import com.google.bitcoin.networkabstraction.StreamParser;
import com.google.bitcoin.networkabstraction.StreamParserFactory;
import com.google.bitcoin.params.MainNetParams;
import com.google.bitcoin.utils.Threading;
import com.google.common.base.Preconditions;
import com.google.common.collect.EvictingQueue;
import javax.annotation.Nullable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;
/**
* Keeps track of the set of known blocks and transactions for relay
*/
abstract class Pool<Type extends Message> {
abstract int relayedCacheSize();
Map<Sha256Hash, Type> objects = new HashMap<Sha256Hash, Type>();
Set<Sha256Hash> objectsRelayed = new LinkedHashSet<Sha256Hash>() {
@Override
public boolean add(Sha256Hash e) {
boolean res = super.add(e);
if (size() > relayedCacheSize())
super.remove(super.iterator().next()); //TODO: right order, or inverse?
return res;
}
};
public synchronized boolean shouldRequestInv(Sha256Hash hash) {
return !objectsRelayed.contains(hash) && !objects.containsKey(hash);
}
public synchronized void provideObject(Type m) {
if (!objectsRelayed.contains(m.getHash()))
objects.put(m.getHash(), m);
}
public synchronized void invGood(Set<Peer> clients, Sha256Hash hash) {
Type o = objects.get(hash);
Preconditions.checkState(o != null);
if (!objectsRelayed.contains(hash)) {
for (Peer p : clients) {
try {
p.sendMessage(o);
} catch (IOException e) { /* Oops, lost them */ }
}
objectsRelayed.add(hash);
}
objects.remove(hash);
}
}
class BlockPool extends Pool<Block> {
@Override
int relayedCacheSize() {
return 100;
}
}
class TransactionPool extends Pool<Transaction> {
@Override
int relayedCacheSize() {
return 10000;
}
}
/** Keeps track of trusted peer connections (two for each trusted peer) */
class TrustedPeerConnections {
/** We only receive messages here (listen for invs of validated data) */
public Peer inbound;
/** We only send messages here (send unvalidated data) */
public Peer outbound;
}/**
* A RelayNode which is designed to relay blocks/txn from a set of untrusted peers, through a trusted bitcoind, to the
* rest of the untrusted peers. It does no verification and trusts everything that comes from the trusted bitcoind is
* good to relay.
*/
public class RelayNode {
public static void main(String[] args) {
new RelayNode().run(8334, 8335);
}
final NetworkParameters params = MainNetParams.get();
final VersionMessage versionMessage = new VersionMessage(params, 0);
final TransactionPool txPool = new TransactionPool();
final BlockPool blockPool = new BlockPool();
final Set<Peer> txnClients = Collections.synchronizedSet(new HashSet<Peer>());
final Set<Peer> blocksClients = Collections.synchronizedSet(new HashSet<Peer>());
PeerEventListener clientPeerListener = new AbstractPeerEventListener() {
@Override
public Message onPreMessageReceived(Peer p, Message m) {
if (m instanceof InventoryMessage) {
GetDataMessage getDataMessage = new GetDataMessage(params);
for (InventoryItem item : ((InventoryMessage)m).getItems()) {
if (item.type == InventoryItem.Type.Block)
if (blockPool.shouldRequestInv(item.hash))
getDataMessage.addBlock(item.hash);
else if (item.type == InventoryItem.Type.Transaction)
if (txPool.shouldRequestInv(item.hash))
getDataMessage.addTransaction(item.hash);
}
if (!getDataMessage.getItems().isEmpty())
try {
p.sendMessage(getDataMessage);
} catch (IOException e) { /* Oops, lost them */ }
return null;
} else if (m instanceof Transaction) {
txPool.provideObject((Transaction) m);
return null;
} else if (m instanceof Block) {
blockPool.provideObject((Block) m);
return null;
}
return m;
}
};
Map<InetSocketAddress, TrustedPeerConnections> trustedPeerConnectionsMap = Collections.synchronizedMap(new HashMap<InetSocketAddress, TrustedPeerConnections>());
NioClientManager trustedPeerManager = new NioClientManager();
PeerEventListener trustedPeerInboundListener = new AbstractPeerEventListener() {
@Override
public Message onPreMessageReceived(Peer p, Message m) {
if (m instanceof InventoryMessage) {
GetDataMessage getDataMessage = new GetDataMessage(params);
for (InventoryItem item : ((InventoryMessage)m).getItems()) {
if (item.type == InventoryItem.Type.Block) {
if (blockPool.shouldRequestInv(item.hash))
getDataMessage.addBlock(item.hash);
else
blockPool.invGood(blocksClients, item.hash);
} else if (item.type == InventoryItem.Type.Transaction) {
if (txPool.shouldRequestInv(item.hash))
getDataMessage.addTransaction(item.hash);
else
txPool.invGood(txnClients, item.hash);
}
}
if (!getDataMessage.getItems().isEmpty())
try {
p.sendMessage(getDataMessage);
} catch (IOException e) { /* Oops, lost them, we'll pick them back up in onPeerDisconnected */ }
return null;
} else if (m instanceof Transaction) {
txPool.provideObject((Transaction) m);
txPool.invGood(txnClients, m.getHash());
return null;
} else if (m instanceof Block) {
blockPool.provideObject((Block) m);
blockPool.invGood(blocksClients, m.getHash());
return null;
}
return m;
}
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
//TODO
}
};
public RelayNode() {
versionMessage.appendToSubVer("RelayNode", "bicurious bison", null);
trustedPeerManager.startAndWait();
}
public void run(int onlyBlocksListenPort, int bothListenPort) {
// Listen for incoming client connections
try {
NioServer onlyBlocksServer = new NioServer(new StreamParserFactory() {
@Nullable
@Override
public StreamParser getNewParser(InetAddress inetAddress, int port) {
Peer p = new Peer(params, versionMessage, null, new InetSocketAddress(inetAddress, port));
p.addEventListener(clientPeerListener, Threading.SAME_THREAD);
blocksClients.add(p);
return p;
}
}, new InetSocketAddress(onlyBlocksListenPort));
NioServer bothServer = new NioServer(new StreamParserFactory() {
@Nullable
@Override
public StreamParser getNewParser(InetAddress inetAddress, int port) {
Peer p = new Peer(params, versionMessage, null, new InetSocketAddress(inetAddress, port));
p.addEventListener(clientPeerListener, Threading.SAME_THREAD);
blocksClients.add(p);
txnClients.add(p);
return p;
}
}, new InetSocketAddress(bothListenPort));
onlyBlocksServer.startAndWait();
bothServer.startAndWait();
} catch (IOException e) {
System.err.println("Failed to bind to port");
System.exit(1);
}
// Print stats
new Thread(new Runnable() {
@Override
public void run() {
printStats();
}
}).start();
// Get user input
Scanner scanner = new Scanner(System.in);
String line;
while ((line = scanner.nextLine()) != null) {
if (line.equals("q")) {
synchronized (printLock) {
System.out.println("Quitting...");
// Wait...cleanup? naaaaa
System.exit(0);
}
} else if (line.startsWith("t ")) {
String[] hostPort = line.substring(2).split(":");
if (hostPort.length != 2) {
LogLine("Invalid argument");
continue;
}
try {
int port = Integer.parseInt(hostPort[1]);
InetSocketAddress addr = new InetSocketAddress(hostPort[0], port);
if (addr.isUnresolved())
LogLine("Unable to resolve host");
else
AddTrustedPeer(addr);
} catch (NumberFormatException e) {
LogLine("Invalid argument");
}
}
}
}
public void AddTrustedPeer(InetSocketAddress address) {
TrustedPeerConnections connections = new TrustedPeerConnections();
connections.inbound = new Peer(params, versionMessage, null, address);
connections.inbound.addEventListener(trustedPeerInboundListener, Threading.SAME_THREAD);
trustedPeerManager.openConnection(address, connections.inbound);
connections.outbound = new Peer(params, versionMessage, null, address);
trustedPeerManager.openConnection(address, connections.outbound);
trustedPeerConnectionsMap.put(address, connections);
}
public static final int LOG_LINES = 10;
final Queue<String> logLines = EvictingQueue.create(LOG_LINES);
public void LogLine(String line) {
synchronized (logLines) {
logLines.add(line);
}
}
// Wouldn't want to print from multiple threads, would we?
final Object printLock = new Object();
public void printStats() {
while (true) {
synchronized (printLock) {
System.out.print("\033[2J"); // Clear screen, move to top-left
if (trustedPeerConnectionsMap.isEmpty()) {
System.out.println("Relaying will not start until you add some trusted nodes");
} else {
System.out.println("Trusted nodes: ");
for (Map.Entry<InetSocketAddress, TrustedPeerConnections> entry : trustedPeerConnectionsMap.entrySet()) {
boolean connected = true;
try {
entry.getValue().inbound.sendMessage(new Ping(0xDEADBEEF));
} catch (Exception e) {
connected = false;
}
System.out.println(" " + entry.getKey() + (connected ? " connected" : " not connected"));
}
}
System.out.println();
System.out.println("Connected block+transaction clients: " + txnClients.size());
System.out.println("Connected block-only clients: " + (blocksClients.size() - txnClients.size()));
System.out.println();
System.out.println("Commands:");
System.out.println("q \t\tquit");
System.out.println("t IP:port\t\tadd node IP:port as a trusted peer");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.err.println("Stats printing thread interrupted");
System.exit(1);
}
}
}
} |
package com.mongodb.hadoop.demo;
import com.mongodb.hadoop.BSONFileInputFormat;
import com.mongodb.hadoop.MongoOutputFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.mllib.recommendation.MatrixFactorizationModel;
import org.apache.spark.mllib.recommendation.Rating;
import org.apache.spark.mllib.recommendation.ALS;
import org.apache.spark.storage.StorageLevel;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import scala.Tuple2;
import java.util.Date;
public class Recommender {
private static String MONGODB = "127.0.0.1:27017";
private static String HDFS = "127.0.0.1:9000";
public static void main(String[] args) {
JavaSparkContext sc = new JavaSparkContext("local", "Recommender");
Configuration bsonDataConfig = new Configuration();
bsonDataConfig.set("mongo.job.input.format", "com.mongodb.hadoop.BSONFileInputFormat");
Configuration predictionsConfig = new Configuration();
predictionsConfig.set("mongo.output.uri", "mongodb://" + MONGODB + "/movielens.predictions");
JavaPairRDD<Object,BSONObject> bsonRatingsData = sc.newAPIHadoopFile(
"hdfs://" + HDFS + "/work/ratings.bson", BSONFileInputFormat.class, Object.class,
BSONObject.class, bsonDataConfig);
JavaRDD<Rating> ratingsData = bsonRatingsData.map(
new Function<Tuple2<Object,BSONObject>,Rating>() {
public Rating call(Tuple2<Object,BSONObject> doc) throws Exception {
Integer userid = (Integer) doc._2.get("userid");
Integer movieid = (Integer) doc._2.get("movieid");
Double rating = (Double) doc._2.get("rating");
return new Rating(userid, movieid, rating);
}
}
);
// keep this RDD in memory as much as possible, and spill to disk if needed
ratingsData.persist(StorageLevel.MEMORY_AND_DISK());
// create the model from existing ratings data
MatrixFactorizationModel model = ALS.train(ratingsData.rdd(), 1, 20, 0.01);
JavaRDD<Object> userData = sc.newAPIHadoopFile("hdfs://" + HDFS + "/work/users.bson",
BSONFileInputFormat.class, Object.class, BSONObject.class, bsonDataConfig).map(
new Function<Tuple2<Object, BSONObject>, Object>() {
@Override
public Object call(Tuple2<Object, BSONObject> doc) throws Exception {
return doc._2.get("userid");
}
}
);
JavaRDD<Object> movieData = sc.newAPIHadoopFile("hdfs://" + HDFS + "/work/movies.bson",
BSONFileInputFormat.class, Object.class, BSONObject.class, bsonDataConfig).map(
new Function<Tuple2<Object, BSONObject>, Object>() {
@Override
public Object call(Tuple2<Object, BSONObject> doc) throws Exception {
return doc._2.get("movieid");
}
}
);
// generate complete pairing for all possible (user,movie) combinations
JavaPairRDD<Object,Object> usersMovies = userData.cartesian(movieData);
// predict ratings
JavaPairRDD<Object,BSONObject> predictions = model.predict(usersMovies.rdd()).toJavaRDD().mapToPair(
new PairFunction<Rating, Object, BSONObject>() {
@Override
public Tuple2<Object, BSONObject> call(Rating rating) throws Exception {
BSONObject doc = new BasicBSONObject();
doc.put("userid", rating.user());
doc.put("movieid", rating.product());
doc.put("rating", rating.rating());
doc.put("timestamp", new Date());
// null key means an ObjectId will be generated on insert
return new Tuple2<Object, BSONObject>(null, doc);
}
}
);
predictions.saveAsNewAPIHadoopFile("file:///notapplicable",
Object.class, Object.class, MongoOutputFormat.class, predictionsConfig);
}
} |
package com.my.blog.website.utils;
import com.my.blog.website.exception.TipException;
import com.my.blog.website.constant.WebConst;
import com.my.blog.website.controller.admin.AttachController;
import com.my.blog.website.modal.Vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.awt.*;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TaleUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(TaleUtils.class);
private static DataSource newDataSource;
private static final int one_month = 30 * 24 * 60 * 60;
private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
private static final Pattern SLUG_REGEX = Pattern.compile("^[A-Za-z0-9_-]{5,100}$", Pattern.CASE_INSENSITIVE);
/**
* markdown
*/
private static Parser parser = Parser.builder().build();
private static String location = TaleUtils.class.getClassLoader().getResource("").getPath();
/**
*
*
* @param emailStr
* @return
*/
public static boolean isEmail(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
/**
* @param fileName jar
* @return
*/
private static Properties getPropFromFile(String fileName) {
Properties properties = new Properties();
try {
// classPath
InputStream resourceAsStream = new FileInputStream(fileName);
properties.load(resourceAsStream);
} catch (TipException | IOException e) {
LOGGER.error("get properties file fail={}", e.getMessage());
}
return properties;
}
/**
* md5
*
* @param source
* @return
*/
public static String MD5encode(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ignored) {
}
byte[] encode = messageDigest.digest(source.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte anEncode : encode) {
String hex = Integer.toHexString(0xff & anEncode);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
/**
*
*
* @return
*/
public static DataSource getNewDataSource() {
if (newDataSource == null) synchronized (TaleUtils.class) {
if (newDataSource == null) {
Properties properties = TaleUtils.getPropFromFile("application-jdbc.properties");
if (properties.size() == 0) {
return newDataSource;
}
DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
managerDataSource.setUrl(str);
managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
newDataSource = managerDataSource;
}
}
return newDataSource;
}
/**
*
*
* @return
*/
public static UserVo getLoginUser(HttpServletRequest request) {
HttpSession session = request.getSession();
if (null == session) {
return null;
}
return (UserVo) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
}
/**
* cookieid
*
* @param request
* @return
*/
public static Integer getCookieUid(HttpServletRequest request) {
if (null != request) {
Cookie cookie = cookieRaw(WebConst.USER_IN_COOKIE, request);
if (cookie != null && cookie.getValue() != null) {
try {
String uid = Tools.deAes(cookie.getValue(), WebConst.AES_SALT);
return StringUtils.isNotBlank(uid) && Tools.isNumber(uid) ? Integer.valueOf(uid) : null;
} catch (Exception e) {
}
}
}
return null;
}
/**
* cookiescookie
*
* @param name
* @param request
* @return cookie
*/
private static Cookie cookieRaw(String name, HttpServletRequest request) {
javax.servlet.http.Cookie[] servletCookies = request.getCookies();
if (servletCookies == null) {
return null;
}
for (javax.servlet.http.Cookie c : servletCookies) {
if (c.getName().equals(name)) {
return c;
}
}
return null;
}
/**
* cookie
*
* @param response
* @param uid
*/
public static void setCookie(HttpServletResponse response, Integer uid) {
try {
String val = Tools.enAes(uid.toString(), WebConst.AES_SALT);
boolean isSSL = false;
Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, val);
cookie.setPath("/");
cookie.setMaxAge(60*30);
cookie.setSecure(isSSL);
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* html
*
* @param html
* @return
*/
public static String htmlToText(String html) {
if (StringUtils.isNotBlank(html)) {
return html.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
}
return "";
}
/**
* markdownhtml
*
* @param markdown
* @return
*/
public static String mdToHtml(String markdown) {
if (StringUtils.isBlank(markdown)) {
return "";
}
Node document = parser.parse(markdown);
HtmlRenderer renderer = HtmlRenderer.builder().build();
String content = renderer.render(document);
content = Commons.emoji(content);
return content;
}
/**
*
*
* @param session
* @param response
*/
public static void logout(HttpSession session, HttpServletResponse response) {
session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
cookie.setMaxAge(0);
response.addCookie(cookie);
try {
response.sendRedirect(Commons.site_url());
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* HTML
*
* @param value
* @return
*/
public static String cleanXSS(String value) {
//You'll need to remove the spaces from the html entities below
value = value.replaceAll("<", "<").replaceAll(">", ">");
value = value.replaceAll("\\(", "(").replaceAll("\\)", ")");
value = value.replaceAll("'", "&
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
/**
* XSS
*
* @param value
* @return
*/
public static String filterXSS(String value) {
String cleanValue = null;
if (value != null) {
cleanValue = Normalizer.normalize(value, Normalizer.Form.NFD);
// Avoid null characters
cleanValue = cleanValue.replaceAll("\0", "");
// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Avoid anything in a src='...' type of expression
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Avoid expression(...) expressions
scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
// Avoid onload= expressions
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
}
return cleanValue;
}
/**
*
*
* @param slug
* @return
*/
public static boolean isPath(String slug) {
if (StringUtils.isNotBlank(slug)) {
if (slug.contains("/") || slug.contains(" ") || slug.contains(".")) {
return false;
}
Matcher matcher = SLUG_REGEX.matcher(slug);
return matcher.find();
}
return false;
}
public static String getFileKey(String name) {
String prefix = "/upload/" + DateKit.dateFormat(new Date(), "yyyy/MM");
if (!new File(AttachController.CLASSPATH + prefix).exists()) {
new File(AttachController.CLASSPATH + prefix).mkdirs();
}
name = StringUtils.trimToNull(name);
if (name == null) {
return prefix + "/" + UUID.UU32() + "." + null;
} else {
name = name.replace('\\', '/');
name = name.substring(name.lastIndexOf("/") + 1);
int index = name.lastIndexOf(".");
String ext = null;
if (index >= 0) {
ext = StringUtils.trimToNull(name.substring(index + 1));
}
return prefix + "/" + UUID.UU32() + "." + (ext == null ? null : (ext));
}
}
/**
*
*
* @param imageFile
* @return
*/
public static boolean isImage(InputStream imageFile) {
try {
Image img = ImageIO.read(imageFile);
if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
/**
*
*
* @param size
* @return
*/
public static String getRandomNumber(int size) {
String num = "";
for (int i = 0; i < size; ++i) {
double a = Math.random() * 9.0D;
a = Math.ceil(a);
int randomNum = (new Double(a)).intValue();
num = num + randomNum;
}
return num;
}
/**
* ,jar
*
* @return
*/
public static String getUplodFilePath() {
String path = TaleUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(1, path.length());
try {
path = java.net.URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int lastIndex = path.lastIndexOf("/") + 1;
path = path.substring(0, lastIndex);
File file = new File("");
return file.getAbsolutePath() + "/";
}
} |
package com.recallq.parseweblog;
import com.recallq.parseweblog.fieldparser.LocalTimeFieldParser;
import com.recallq.parseweblog.fieldparser.RequestFieldParser;
import com.recallq.parseweblog.outputters.JsonOutputter;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
/**
* Main class that parses log files and outputs data.
*
* @author Jeroen De Swaef
*/
public class ParseWebLog {
private static final Logger logger = Logger.getLogger(ParseWebLog.class.getName());
static {
final InputStream inputStream = ParseWebLog.class.getResourceAsStream("/logging.properties");
try {
LogManager.getLogManager().readConfiguration(inputStream);
} catch (final IOException e) {
Logger.getAnonymousLogger().severe("Could not load default logging.properties file");
Logger.getAnonymousLogger().severe(e.getMessage());
}
}
private static final String LOGFILE_PARAMETER = "logfile";
private static final String CONFIG_PROPERTIES_PARAMETER = "config";
private static final String LOG_FORMAT_PROP = "log-format";
private static final String GZIP_EXTENSION = "gz";
private static final Set<Character> charactersToEscape = new HashSet<Character>() {
{
add('[');
add(']');
}
};
private static final Map<String, FieldParser> fieldParsers = new HashMap<String, FieldParser>() {
{
put("time_local", new LocalTimeFieldParser());
put("request", new RequestFieldParser());
}
};
private static final List<String> logFieldNames = new ArrayList<String>();
// Returns a pattern where all punctuation characters are escaped.
private static final Pattern escaper = Pattern.compile("([\\[\\]])");
private static final Pattern extractVariablePattern = Pattern.compile("\\$[a-zA-Z0-9_]*");
private static String escapeRE(String str) {
return escaper.matcher(str).replaceAll("\\\\$1");
}
private final String metaPattern;
private final InputStream logStream;
// each item in the map represents a log line
// each map entry has as key the name of the nginx log variable
// the object in the map can be:
// - a String: for single values
// - a Map of <String, String>: for values that are being split by FieldParsers
private List<Map<String, Object>> logData;
private Pattern getLogFilePattern(String metaPattern) {
Matcher matcher = extractVariablePattern.matcher(metaPattern);
int parsedPosition = 0;
StringBuilder parsePatternBuilder = new StringBuilder();
while (matcher.find()) {
if (parsedPosition < matcher.start()) {
String residualPattern = metaPattern.substring(parsedPosition, matcher.start());
parsePatternBuilder.append(escapeRE(residualPattern));
}
String logFieldName = metaPattern.substring(matcher.start() + 1, matcher.end());
logFieldNames.add(logFieldName);
parsedPosition = matcher.end();
char splitCharacter = metaPattern.charAt(matcher.end());
parsePatternBuilder.append("([^");
if (charactersToEscape.contains(splitCharacter)) {
parsePatternBuilder.append("\\");
}
parsePatternBuilder.append(splitCharacter);
parsePatternBuilder.append("]*)");
}
parsePatternBuilder.append(metaPattern.substring(parsedPosition, metaPattern.length()));
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, parsePatternBuilder.toString());
}
Pattern logFilePattern = Pattern.compile(parsePatternBuilder.toString());
return logFilePattern;
}
private static InputStream getStreamForFilename(String filename) throws FileNotFoundException, IOException {
if (filename.endsWith(GZIP_EXTENSION)) {
return new GZIPInputStream(new FileInputStream(filename));
} else {
return new FileInputStream(filename);
}
}
public List<Map<String, Object>> getLogData() {
return logData;
}
public ParseWebLog(InputStream logStream, String metaPattern) {
this.logStream = logStream;
this.metaPattern = metaPattern;
}
public void parseLog() {
logData = new ArrayList<Map<String, Object>>();
Pattern logFilePattern = getLogFilePattern(metaPattern);
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(logStream));
String line;
while ((line = br.readLine()) != null) {
Map<String, Object> logLine = new HashMap<String, Object>();
Matcher logFileMatcher = logFilePattern.matcher(line);
if (logFileMatcher.matches()) {
for (int i = 1; i < logFileMatcher.groupCount(); i++) {
String logFieldName = logFieldNames.get(i - 1);
FieldParser fieldParser = fieldParsers.get(logFieldName);
Object fieldValue;
if (fieldParser != null) {
if (fieldParser instanceof SingleResultFieldParser) {
fieldValue = ((SingleResultFieldParser) fieldParser)
.parse(logFileMatcher.group(i));
} else {
fieldValue = ((MultipleResultFieldParser) fieldParser)
.parse(logFileMatcher.group(i));
}
} else {
fieldValue = logFileMatcher.group(i);
}
logLine.put(logFieldName, fieldValue);
}
logData.add(logLine);
}
}
br.close();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error parsing log", ex);
}
if (logger.isLoggable(Level.INFO)) {
logger.log(Level.INFO, "Parsed {0} log lines", new Object[]{logData.size()});
}
}
public void outputParsedData() {
JsonOutputter outputter = new JsonOutputter();
try {
outputter.outputData(logData, System.out);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error outputting in JSON", ex);
}
}
public static void main(String... arguments) {
String logFilename = null;
OptionSet options = null;
OptionParser parser = new OptionParser() {
{
accepts(LOGFILE_PARAMETER).withRequiredArg().required()
.describedAs("Apache/Nginx log file");
accepts(CONFIG_PROPERTIES_PARAMETER).withRequiredArg()
.describedAs("Configuration file");
}
};
try {
options = parser.parse(arguments);
logFilename = (String) options.valueOf(LOGFILE_PARAMETER);
} catch (Exception e) {
try {
parser.printHelpOn(System.out);
} catch (IOException ex) {
Logger.getLogger(ParseWebLog.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(1);
}
Properties prop = new Properties();
InputStream configStream = null;
if (options.has(CONFIG_PROPERTIES_PARAMETER)) {
String configFilename = (String) options.valueOf(CONFIG_PROPERTIES_PARAMETER);
try {
configStream = new FileInputStream(configFilename);
} catch (FileNotFoundException ex) {
logger.log(Level.SEVERE, "Couldn''t open config file {0}", configFilename);
System.exit(1);
}
}
if (configStream == null) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
configStream = loader.getResourceAsStream("config.properties");
}
try {
prop.load(configStream);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to load config.properties", ex);
}
String metaPattern = prop.getProperty(LOG_FORMAT_PROP);
try {
InputStream fstream = getStreamForFilename(logFilename);
ParseWebLog webLogParser = new ParseWebLog(fstream, metaPattern);
webLogParser.parseLog();
webLogParser.outputParsedData();
} catch (FileNotFoundException ex) {
logger.log(Level.SEVERE, "Unable to find file {0}", new Object[]{logFilename});
} catch (IOException ex1) {
logger.log(Level.SEVERE, "Error while reading file " + logFilename, ex1);
}
}
} |
package com.stripe.model;
import java.util.Map;
import java.util.List;
import com.stripe.Stripe;
import com.stripe.exception.APIConnectionException;
import com.stripe.exception.APIException;
import com.stripe.exception.AuthenticationException;
import com.stripe.exception.CardException;
import com.stripe.exception.InvalidRequestException;
import com.stripe.net.APIResource;
public class BalanceTransaction extends APIResource {
String id;
String source;
Integer amount;
String currency;
Integer net;
String type;
Long created;
Long availableOn;
String status;
Integer fee;
List<Fee> feeDetails;
String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getNet() {
return net;
}
public void setNet(Integer net) {
this.net = net;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getCreated() {
return created;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getAvailableOn() {
return availableOn;
}
public void setAvailableOn(Long availableOn) {
this.availableOn = availableOn;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getFee() {
return fee;
}
public void setFee(Integer fee) {
this.fee = fee;
}
public List<Fee> getFeeDetails() {
return feeDetails;
}
public void setFeeDetails(List<Fee> feeDetails) {
this.feeDetails = feeDetails;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public static BalanceTransaction retrieve(String id) throws AuthenticationException,
InvalidRequestException, APIConnectionException, CardException,
APIException {
return retrieve(id, null);
}
public static BalanceTransactionCollection all(Map<String, Object> params)
throws AuthenticationException, InvalidRequestException,
APIConnectionException, CardException, APIException {
return all(params, null);
}
public static BalanceTransaction retrieve(String id, String apiKey)
throws AuthenticationException, InvalidRequestException,
APIConnectionException, CardException, APIException {
String url = String.format("%s/%s/%s", Stripe.getApiBase(), "v1/balance/history", id);
return request(RequestMethod.GET, url, null,
BalanceTransaction.class, apiKey);
}
public static BalanceTransactionCollection all(Map<String, Object> params, String apiKey)
throws AuthenticationException, InvalidRequestException,
APIConnectionException, CardException, APIException {
String url = String.format("%s/%s", Stripe.getApiBase(), "v1/balance/history");
return request(RequestMethod.GET, url, params,
BalanceTransactionCollection.class, apiKey);
}
} |
package com.wuest.prefab.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
public class BlockShaped extends Block {
private final BlockShape shape;
public BlockShaped(BlockShape shape, Properties properties) {
super(properties);
this.shape = shape;
}
@Override
public VoxelShape getShape(BlockState p_220053_1_, IBlockReader p_220053_2_, BlockPos p_220053_3_, ISelectionContext p_220053_4_) {
return this.shape.getShape();
}
public enum BlockShape {
PileOfBricks(Block.box(3.0D, 0.0D, 3.0D, 13.0D, 5.0D, 12.0D)),
PalletOfBricks(Block.box(1.0D, 0.0D, 0.0D, 15.0D, 15.0D, 16.0D)),
BundleOfTimber(Block.box(0.0D, 0.0D, 0.0D, 15.0D, 4.0D, 15.0D)),
HeapOfTimber(Block.box(3.0D, 0.0D, 2.0D, 13.0D, 6.0D, 14.0D)),
TonOfTimber(Block.box(1.0D, 0.0D, 2.0D, 14.0D, 9.0D, 14.0D));
private final VoxelShape shape;
BlockShape(VoxelShape shape) {
this.shape = shape;
}
public VoxelShape getShape() {
return this.shape;
}
}
} |
package com.yq.manager.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.sr178.common.jdbc.bean.IPage;
import com.sr178.common.jdbc.bean.SqlParamBean;
import com.sr178.game.framework.log.LogSystem;
import com.yq.common.exception.ServiceException;
import com.yq.common.utils.DateStyle;
import com.yq.common.utils.DateUtils;
import com.yq.common.utils.FileCreatUtil;
import com.yq.common.utils.MD5Security;
import com.yq.cservice.bean.SqDayAddBean;
import com.yq.manager.bean.Performance;
import com.yq.manager.bean.UserPerformanceSearch;
import com.yq.manager.bean.YbCjbBean;
import com.yq.manager.bo.BackCountBean;
import com.yq.manager.bo.DateBean;
import com.yq.manager.bo.GcfhBean;
import com.yq.manager.bo.NewsDateBean;
import com.yq.manager.bo.PmmltBean;
import com.yq.manager.bo.PointsChangeLog;
import com.yq.manager.bo.UserVipLog;
import com.yq.manager.bo.W10Bean;
import com.yq.manager.dao.AddShengDao;
import com.yq.manager.dao.FhdateDao;
import com.yq.manager.dao.MqfhDao;
import com.yq.manager.dao.MtfhtjDao;
import com.yq.manager.dao.PointsChangeLogDao;
import com.yq.manager.dao.SgtjDao;
import com.yq.manager.dao.UserVipLogDao;
import com.yq.user.bean.TopReward;
import com.yq.user.bo.Addsheng;
import com.yq.user.bo.Bdbdate;
import com.yq.user.bo.Cpuser;
import com.yq.user.bo.Datecj;
import com.yq.user.bo.Dateip;
import com.yq.user.bo.Datepay;
import com.yq.user.bo.Dgag;
import com.yq.user.bo.Fcxt;
import com.yq.user.bo.Fhdate;
import com.yq.user.bo.Gcfh;
import com.yq.user.bo.Gcuser;
import com.yq.user.bo.GcuserForExcel;
import com.yq.user.bo.Gpjy;
import com.yq.user.bo.Mtfhtj;
import com.yq.user.bo.Sgtj;
import com.yq.user.bo.Sgxt;
import com.yq.user.bo.Tduser;
import com.yq.user.bo.Txpay;
import com.yq.user.bo.UserExtinfo;
import com.yq.user.bo.UserPerformance;
import com.yq.user.bo.Vipcjgl;
import com.yq.user.bo.Vipxtgc;
import com.yq.user.bo.YouMingxi;
import com.yq.user.bo.ZuoMingxi;
import com.yq.user.dao.BdbDateDao;
import com.yq.user.dao.CpuserDao;
import com.yq.user.dao.DatePayDao;
import com.yq.user.dao.DatecjDao;
import com.yq.user.dao.DateipDao;
import com.yq.user.dao.DgagDao;
import com.yq.user.dao.FcxtDao;
import com.yq.user.dao.GcfhDao;
import com.yq.user.dao.GcuserDao;
import com.yq.user.dao.GpjyDao;
import com.yq.user.dao.JfcpDao;
import com.yq.user.dao.SgxtDao;
import com.yq.user.dao.TduserDao;
import com.yq.user.dao.TxPayDao;
import com.yq.user.dao.TxifokDao;
import com.yq.user.dao.UserExtinfoDao;
import com.yq.user.dao.UserPerformanceDao;
import com.yq.user.dao.VipcjglDao;
import com.yq.user.dao.VipxtgcDao;
import com.yq.user.dao.YouMingXiDao;
import com.yq.user.dao.ZuoMingxiDao;
import com.yq.user.service.LogService;
import com.yq.user.service.UserService;
import com.yq.user.utils.Ref;
import com.yq.user.utils._99douInterface;
public class AdminService {
@Autowired
private FcxtDao fcxtDao;
@Autowired
private SgtjDao sgtjDao;
@Autowired
private BdbDateDao bdbDateDao;
@Autowired
private GpjyDao gpjyDao;
@Autowired
private GcfhDao gcfhDao;
@Autowired
private TxPayDao txPayDao;
@Autowired
private FhdateDao fhDateDao;
@Autowired
private MqfhDao mqfhDao;
@Autowired
private AddShengDao addShengDao;
@Autowired
private GcuserDao gcuserDao;
@Autowired
private LogService logService;
@Autowired
private DatecjDao datecjDao;
@Autowired
private SgxtDao sgxtDao;
@Autowired
private ZuoMingxiDao zuoMingxiDao;
@Autowired
private YouMingXiDao youMingXiDao;
@Autowired
private TxifokDao txifokDao;
@Autowired
private MtfhtjDao mtfhtjDao;
@Autowired
private DateipDao dateipDao;
@Autowired
private CpuserDao cpuserDao;
@Autowired
private JfcpDao jfcpDao;
@Autowired
private DgagDao dgagDao;
@Autowired
private DatePayDao datePayDao;
@Autowired
private UserService userService;
@Autowired
private VipcjglDao vipcjglDao;
@Autowired
private TduserDao tduserDao;
@Autowired
private TxPayDao txpayDao;
@Autowired
private VipxtgcDao vipxtgcDao;
@Autowired
private UserPerformanceDao userPerformanceDao;
@Autowired
private UserExtinfoDao userExtinfoDao;
@Autowired
private PointsChangeLogDao pointsChangeLogDao;
@Autowired
private UserVipLogDao userVipLogDao;
private Cache<String,String> adminUserMap = CacheBuilder.newBuilder().expireAfterAccess(24, TimeUnit.HOURS).maximumSize(2000).build();
public static boolean isClose = false;
public String getLoginAdminUserName(String sessionId){
return adminUserMap.getIfPresent(sessionId);
}
/**
*
* @param userName
* @param password
* @param sessionId
*/
public boolean adminLogin(String userName,String password,String sessionId){
String md5pass = MD5Security.md5_16(password);
Fcxt fcxt = fcxtDao.getByUserNameAndPassword(userName, md5pass);
if(fcxt!=null){
adminUserMap.put(sessionId, userName);
return true;
}else{
return false;
}
}
public IPage<Gcfh> getAllGcfhPage(int pageIndex,int pageSize){
return gcfhDao.getAllPageList(pageSize, pageIndex);
}
public GcfhBean getGcfhBean(){
GcfhBean result = new GcfhBean();
result.setTotalIn(gcfhDao.getSumSyfhIn());
result.setTotalOut(gcfhDao.getSumSyfhOut());
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
String todayEnd = todayStr+" 23:59:59";
String yesterdayStr = DateUtils.getDate(DateUtils.addDay(new Date(), -1));
String yesterdayStart = yesterdayStr+" 00:00:00";
String yesterdayEnd = yesterdayStr+" 23:59:59";
result.setTodayIn(gcfhDao.getDateSumSyfhIn(todayStart, todayEnd));
result.setTodayOut(gcfhDao.getDateSumSyfhOut(todayStart, todayEnd));
result.setYesterdayIn(gcfhDao.getDateSumSyfhIn(yesterdayStart, yesterdayEnd));
result.setYeaterdayOut(gcfhDao.getDateSumSyfhOut(yesterdayStart, yesterdayEnd));
return result;
}
public Double getSumpayNumOfTxpay(){
return txPayDao.getSumPayNum();
}
public IPage<Txpay> getTxpayPageList(int pageIndex,int pageSize){
return txPayDao.getPageListOrder(pageIndex, pageSize);
}
public void logout(String sessionId){
adminUserMap.invalidate(sessionId);
}
public IPage<Sgtj> getSgtjPageList(int pageIndex,int pageSize){
return sgtjDao.getPageList(pageIndex, pageSize);
}
public IPage<Bdbdate> getBdbdatePageListByUserNameAndDate(String zuser,String startDate,String endDate,int pageIndex,int pageSize){
return bdbDateDao.getPageListByUserNameAndDate(zuser, startDate, endDate, pageSize, pageIndex);
}
public List<Bdbdate> getBdbdateListByUserNameAndDate(String zuser,String startDate,String endDate){
return bdbDateDao.getListByUserNameAndDate(zuser, startDate, endDate);
}
public IPage<Bdbdate> getBdbdatePageList(int pageIndex,int pageSize){
return bdbDateDao.getALLPageList(pageSize, pageIndex);
}
public IPage<Gpjy> getGpjyPageList(int pageIndex,int pageSize){
return gpjyDao.getPageList(pageIndex, pageSize);
}
public IPage<Gpjy> getAdminMcPageList(int pageIndex,int pageSize){
return gpjyDao.getAdminMcPage(pageIndex, pageSize);
}
public IPage<Gpjy> getAdminMyPageList(int pageIndex,int pageSize){
return gpjyDao.getAdminMrPage(pageIndex, pageSize);
}
public IPage<Fhdate> getFhdatePageList(int pageIndex,int pageSize){
return fhDateDao.getPageList(pageIndex, pageSize);
}
public IPage<Gpjy> searchGpjyPageList(String field,String value,int pageIndex,int pageSize){
return gpjyDao.getSearchResultPageDetailsList(field, value, pageIndex, pageSize);
}
public Double getTodaySumpdlj(){
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
String todayEnd = todayStr+" 23:59:59";
return mqfhDao.getSumpdlb(todayStart, todayEnd);
}
public Fhdate getFirstFhdate(){
return fhDateDao.get();
}
public void countYesterday(){
mqfhDao.update();
String yesterdayStr = DateUtils.getDate(DateUtils.addDay(new Date(), -1));
String yesterdayStart = yesterdayStr+" 00:00:00";
String yesterdayEnd = yesterdayStr+" 23:59:59";
Double yesterdaySumPdlj = mqfhDao.getSumpdlb(yesterdayStart, yesterdayEnd);
Double beforeYesterdaySumPdlj = mqfhDao.getSumpdlb("1970-1-1 00:00:00", yesterdayStart);
Double mqPaySum = mqfhDao.getSumMqpay();
Fhdate fhdate = new Fhdate();
fhdate.setAbdate(DateUtils.addDay(new Date(), -1));
fhdate.setZly(yesterdaySumPdlj);
int cjt = (int)(yesterdaySumPdlj+beforeYesterdaySumPdlj);
fhdate.setFhk(cjt);
fhdate.setTjmq(mqPaySum);
fhdate.setVipfhpay(0.005);
fhdate.setFhpay(0.001);
fhDateDao.add(fhdate);
Addsheng addsheng = new Addsheng();
addsheng.setDate(DateUtils.addDay(new Date(), -1));
addsheng.setCg(yesterdaySumPdlj.intValue());
addsheng.setBj(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setTj(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setHb(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setSx(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setNmg(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setLn(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setJl(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setHlj(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setSh(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setJs(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setZz(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setNf(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setFz(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setZx(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setHn(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setHbs(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setHns(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setGd(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setGx(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setNn(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setCq(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setXc(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setGz(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setUn(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setXz(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setSxs(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setJs(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setQh(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setNs(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setSj(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setTw(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setSg(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addsheng.setOm(mqfhDao.getSumpdlbByArea("", yesterdayStart, yesterdayEnd).intValue());
addShengDao.add(addsheng);
}
/**
*
* @param pdid
*/
public void sendDoubleArea(int pdid){
Fhdate fhdate = fhDateDao.getById(pdid);
if(fhDateDao.updateBz(pdid, 1)){
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
mqfhDao.updateDoubleAreaFh(fhdate.getVipfhpay(), todayStart);
}
}
/**
*
* @param pdid
*/
public void sendCommonUser(int pdid){
Fhdate fhdate = fhDateDao.getById(pdid);
if(fhDateDao.updateBz(pdid, 2)){
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
mqfhDao.updateCommonUserFh(fhdate.getFhpay(), todayStart);
}
}
/**
*
* @param param
* @param pageIndex
* @param pageSize
* @return
*/
public IPage<Gcuser> searchUser(String param,int pageIndex,int pageSize){
return gcuserDao.searchPage(param, pageIndex, pageSize);
}
/**
*
* @param userName
* @param password3
* @param card
* @param bank
* @param name
* @param call
* @param email
* @param qq
* @param userid
* @param payok
* @param jcname
* @param jcuserid
* @param password
* @return
*/
@Transactional
public boolean updateUser(String userName,String password3,String card, String bank, String name, String call,String email,String qq,String userid,int payok,String jcname,String jcuserid,String password,String pwdate,int cxt,String ip,String updateDownPayOk){
Gcuser gcuser = gcuserDao.getUser(userName);
Date date = null;
if(!Strings.isNullOrEmpty(pwdate)){
try {
date = DateUtils.StringToDate(pwdate, DateStyle.YYYY_MM_DD_HH_MM_SS);
} catch (Exception e) {
throw new ServiceException(1, " :'2015-10-12 21:10:00' ");
}
}
String md5Password = null;
if(!Strings.isNullOrEmpty(password)){
md5Password = MD5Security.md5_16(password);
}
String beforUserId = gcuser.getUserid()==null?"":gcuser.getUserid();
String nowUserId = userid==null?"":userid;
String beforName = gcuser.getName()==null?"":gcuser.getName();
String nowName = name==null?"":name;
if(gcuserDao.updateUserByAdmin(userName,password3, card, bank, nowName, call, email, qq, nowUserId, payok, jcname, jcuserid, md5Password,date,cxt)){
dateipDao.addDateIpLog(userName, "sy-"+userName, ip);
}
if(!beforUserId.equals(nowUserId)||!beforName.equals(nowName)){
Tduser tduser = new Tduser();
tduser.setGainame(gcuser.getName());
tduser.setTdname(name);
tduser.setGaiuserid(gcuser.getUserid());
tduser.setTduserid(userid);
tduser.setTduser(userName);
tduser.setTdqq(qq);
tduser.setTdcall(call);
tduser.setGai(1);
tduserDao.add(tduser);
}
if(md5Password!=null){
dateipDao.addDateIpLog("admin", "sy-"+userName, ip);
}
if("ok".equals(updateDownPayOk)){
gcuserDao.updatePayOk(nowName, nowUserId, payok);
LogSystem.log(""+userName+",payok,name="+nowName+",nowUserId="+nowUserId+",payok="+payok);
}
return true;
}
/**
*
* @param chargeUser
* @param amount
* @param bank
* @param operator
*/
@Transactional
public void chargeToUser(String chargeUser,int amount,String bank,String operator,String ip){
Gcuser gcuser = gcuserDao.getUser(chargeUser);
if(gcuser==null){
throw new ServiceException(1, "");
}
Fcxt fcxt = fcxtDao.getFcxt(operator);
if(fcxt==null){
throw new ServiceException(2, "");
}
if(!gcuserDao.updateCjtj(chargeUser, amount)){
throw new ServiceException(3000, "");
}
boolean result = false;
if(amount==5000&&gcuser.getSyep()>4999){
result = updateSybdbByManager(chargeUser, 5000, 10000, 10000, "5000EP5000");
}else if(amount==10000&&gcuser.getSyep()==5000){
result = updateSybdbByManager(chargeUser, 5000, 15000, 15000, "10000EP5000");
}else if(amount==10000&&gcuser.getSyep()>9999){
result = updateSybdbByManager(chargeUser, 10000, 20000, 20000, "10000EP10000");
}else if(amount==15000&&gcuser.getSyep()==5000){
result = updateSybdbByManager(chargeUser, 5000, 20000, 20000, "15000EP5000");
}else if(amount==15000&&gcuser.getSyep()==10000){
result = updateSybdbByManager(chargeUser, 10000, 25000, 25000, "15000EP10000");
}else if(amount==15000&&gcuser.getSyep()>14999){
result = updateSybdbByManager(chargeUser, 15000, 30000, 30000, "15000EP15000");
}else if(amount==20000&&gcuser.getSyep()==5000){
result = updateSybdbByManager(chargeUser, 5000, 25000, 25000, "20000EP5000");
}else if(amount==20000&&gcuser.getSyep()==10000){
result = updateSybdbByManager(chargeUser, 10000, 30000, 30000, "20000EP10000");
}else if(amount==20000&&gcuser.getSyep()>19999){
result = updateSybdbByManager(chargeUser, 20000, 40000, 40000, "20000EP20000");
}else if(amount>4999){
result = updateSybdbByManager(chargeUser, 0, amount, amount, "");
}else{
result = gcuserDao.addOnlyYb(chargeUser, amount);
gcuser = gcuserDao.getUser(chargeUser);
Datepay datepay = new Datepay();
datepay.setUsername(chargeUser);
datepay.setRegid("");
datepay.setSyjz(amount);
datepay.setPay(gcuser.getPay());
datepay.setJydb(gcuser.getJydb());
logService.addDatePay(datepay);
}
if(!result){
throw new ServiceException(3000, "");
}
gcuser = gcuserDao.getUser(chargeUser);
Datecj datecj = new Datecj();
datecj.setCjuser(chargeUser);
datecj.setDqcj(amount);
datecj.setLjcj(gcuser.getCjtj());
datecj.setCjfs(bank);
datecj.setCz(operator);
datecj.setIp(ip);
datecjDao.add(datecj);
}
public void pmToUser(String chargeUser,int amount,String operator){
Gcuser gcuser = gcuserDao.getUser(chargeUser);
if(gcuser==null||gcuser.getSjb()>0){
throw new ServiceException(1, "");
}
Fcxt fcxt = fcxtDao.getFcxt(operator);
if(fcxt==null){
throw new ServiceException(2, "");
}
int sjb = amount/500;
gcuserDao.updateSjb(chargeUser, sjb);
}
public PmmltBean pmmlt(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
int sjb = gcuser.getSjb();
int fd=0;
int cfd=0;
if (sjb==1){
fd=2000;cfd=20;
}else if(sjb==2){
fd=4000;cfd=40;
}else if(sjb==4){
fd=8000;cfd=60;
}else if(sjb==10){
fd=20000;cfd=80;
}else if(sjb==20){
fd=40000;cfd=100;
}else if(sjb==40){
fd=80000;cfd=150;
}else if(sjb==100){
fd=200000;cfd=200;
}
Sgxt last = sgxtDao.getLast();
Gcuser rs10 = gcuserDao.getUser(gcuser.getUp());
Gcuser rs11 = gcuserDao.getUser(rs10.getUp());
Gcuser rs12 = gcuserDao.getUser(rs11.getUp());
Gcuser rs13 = gcuserDao.getUser(rs12.getUp());
Gcuser rs14 = gcuserDao.getUser(rs13.getUp());
String myup = "";
if(rs10.getSjb()>0){
myup = rs10.getUsername();
}else if(rs11.getSjb()>0){
myup = rs11.getUsername();
}else if(rs12.getSjb()>0){
myup = rs12.getUsername();
}else if(rs13.getSjb()>0){
myup = rs13.getUsername();
}else if(rs14.getSjb()>0){
myup = rs14.getUsername();
}else{
myup = last.getUsername();
}
PmmltBean result = generatorPmmltBean(userName,myup);
Sgxt sgxt = new Sgxt();
sgxt.setUsername(userName);
sgxt.setSjb(sjb);
sgxt.setFdpay(fd);
sgxt.setCfd(cfd);
sgxt.setXxnew(3);
sgxt.setFhbl(0.005);
sgxt.setZfh(sjb*250);
sgxt.setBddate(new Date());
sgxtDao.add(sgxt);
return result;
}
/**
*
* @param userName
* @return
*/
public PmmltBean bsReg(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
Sgxt rs2 = sgxtDao.get(userName);
if(rs2==null){
throw new ServiceException(4, "");
}
Sgxt rs1 = sgxtDao.getByAOrBuid(userName);
if(rs1!=null){
throw new ServiceException(2, "");
}
Sgxt last = sgxtDao.getLast();
Gcuser rs10 = gcuserDao.getUser(gcuser.getUp());
Gcuser rs11 = gcuserDao.getUser(rs10.getUp());
Gcuser rs12 = gcuserDao.getUser(rs11.getUp());
Gcuser rs13 = gcuserDao.getUser(rs12.getUp());
Gcuser rs14 = gcuserDao.getUser(rs13.getUp());
String myup = "";
if(rs10.getSjb()>0){
myup = rs10.getUsername();
}else if(rs11.getSjb()>0){
myup = rs11.getUsername();
}else if(rs12.getSjb()>0){
myup = rs12.getUsername();
}else if(rs13.getSjb()>0){
myup = rs13.getUsername();
}else if(rs14.getSjb()>0){
myup = rs14.getUsername();
}else{
myup = last.getUsername();
}
PmmltBean result = generatorPmmltBean(userName,myup);
return result;
}
public PmmltBean mlt(String userName,String myup){
Sgxt rs0 = sgxtDao.get(userName);
if(rs0==null){
throw new ServiceException(1, "");
}
Sgxt rs1 = sgxtDao.getByAOrBuid(userName);
if(rs1!=null){
throw new ServiceException(2, "");
}
Sgxt rs = sgxtDao.get(myup);
if(rs==null){
throw new ServiceException(3, "");
}
return generatorPmmltBean(userName, myup);
}
/**
*
* @param userName
* @param myup
* @return
*/
private PmmltBean generatorPmmltBean(String userName,String myup){
Sgxt rs = sgxtDao.get(myup);
String rsauid = null;
String rsbuid = null;
String rs21auid = null;
String rs21buid = null;
String rs22auid = null;
String rs22buid = null;
String rs31auid = null;
String rs31buid = null;
String rs32auid = null;
String rs32buid = null;
String rs33auid = null;
String rs33buid = null;
String rs34auid = null;
String rs34buid = null;
if(rs!=null){
if(!Strings.isNullOrEmpty(rs.getAuid())){
rsauid = rs.getAuid();
Sgxt rs21 = sgxtDao.get(rsauid);
if(rs21!=null){
if(!Strings.isNullOrEmpty(rs21.getAuid())){
rs21auid = rs21.getAuid();
}
if(!Strings.isNullOrEmpty(rs21.getBuid())){
rs21buid = rs21.getBuid();
}
}
}
if(!Strings.isNullOrEmpty(rs.getBuid())){
rsbuid = rs.getBuid();
Sgxt rs22 = sgxtDao.get(rsbuid);
if(rs22!=null){
if(!Strings.isNullOrEmpty(rs22.getAuid())){
rs22auid = rs22.getAuid();
}
if(!Strings.isNullOrEmpty(rs22.getBuid())){
rs22buid = rs22.getBuid();
}
}
}
if(rs21auid!=null){
Sgxt rs31 = sgxtDao.get(rs21auid);
if(rs31!=null){
if(!Strings.isNullOrEmpty(rs31.getAuid())){
rs31auid = rs31.getAuid();
}
if(!Strings.isNullOrEmpty(rs31.getBuid())){
rs31buid = rs31.getBuid();
}
}
}
if(rs21buid!=null){
Sgxt rs32 = sgxtDao.get(rs21buid);
if(rs32!=null){
if(!Strings.isNullOrEmpty(rs32.getAuid())){
rs32auid = rs32.getAuid();
}
if(!Strings.isNullOrEmpty(rs32.getBuid())){
rs32buid = rs32.getBuid();
}
}
}
if(rs22auid!=null){
Sgxt rs33 = sgxtDao.get(rs22auid);
if(rs33!=null){
if(!Strings.isNullOrEmpty(rs33.getAuid())){
rs33auid = rs33.getAuid();
}
if(!Strings.isNullOrEmpty(rs33.getBuid())){
rs33buid = rs33.getBuid();
}
}
}
if(rs22buid!=null){
Sgxt rs34 = sgxtDao.get(rs22buid);
if(rs34!=null){
if(!Strings.isNullOrEmpty(rs34.getAuid())){
rs34auid = rs34.getAuid();
}
if(!Strings.isNullOrEmpty(rs34.getBuid())){
rs34buid = rs34.getBuid();
}
}
}
}
return new PmmltBean(userName, myup, rsauid, rsbuid, rs21auid, rs21buid, rs22auid, rs22buid, rs31auid, rs31buid, rs32auid, rs32buid, rs33auid, rs33buid, rs34auid, rs34buid);
}
/**
*
* @param userName
* @param changeNum
* @param desc
* @return
*/
private boolean updateSybdbByManager(String userName,int syep,int ljbdb,int sybdb,String desc){
if(syep>=0){
boolean result = gcuserDao.updateSyepLjbdbSybdb(userName, syep,ljbdb,sybdb);
if(result){
Gcuser gcuser = gcuserDao.getUser(userName);
Bdbdate bdbdate = new Bdbdate();
bdbdate.setZuser(userName);
bdbdate.setBz(desc);
bdbdate.setSy(sybdb);
bdbdate.setSybdb(gcuser.getSybdb());
bdbdate.setLjbdb(gcuser.getLjbdb());
bdbDateDao.add(bdbdate);
}
return result;
}else{
// changeNum = Math.abs(changeNum);
// boolean result = gcuserDao.reduceSybdb(userName, changeNum);
// if(result){
// Gcuser gcuser = gcuserDao.getUser(userName);
// Bdbdate bdbdate = new Bdbdate();
// bdbdate.setZuser(userName);
// bdbdate.setBz(desc);
// bdbdate.setSy(changeNum);
// bdbdate.setSybdb(gcuser.getSybdb());
// bdbdate.setLjbdb(gcuser.getLjbdb());
// bdbDateDao.add(bdbdate);
throw new ServiceException(3000,"");
}
}
/**
*
* @param userName
* @param addGfAmount
* @param addJfAmount
*/
public void editGfAndJf(String userName,int addGfAmount,int addJfAmount){
gpjyDao.update(userName, addJfAmount, "");
gcfhDao.update(userName, "", addGfAmount);
}
public Gcfh getGcfh(String userName,String bz){
return gcfhDao.get(userName, bz);
}
public Gpjy getGpjy(String userName,String dfuser){
return gpjyDao.get(userName, dfuser);
}
/**
*
* @param userName
* @param addAmount
*/
public void addJf(String userName,int addAmount){
if (!gcuserDao.updateJyg(userName, - addAmount)) {
throw new ServiceException(3000, "");
}
Gcuser gcuser = gcuserDao.getUser(userName);
Gpjy gpjy = new Gpjy();
gpjy.setUsername(userName);
gpjy.setMysl(new Double(addAmount));
gpjy.setSysl(Double.valueOf(gcuser.getJyg()));
gpjy.setBz("");
gpjy.setCgdate(new Date());
gpjy.setJy(1);
gpjy.setDfuser("");
gpjyDao.add(gpjy);
}
/**
*
* @param userName
* @param addAmount
*/
public void addJb(String userName,int addAmount){
gcuserDao.addOnlyJB(userName, addAmount);
Gcuser gcuser = gcuserDao.getUser(userName);
Datepay datePay1 = new Datepay();
datePay1.setUsername(userName);
datePay1.setPay(gcuser.getPay());
datePay1.setJydb(gcuser.getJydb());
datePay1.setJyjz(addAmount);
datePay1.setRegid("");
datePay1.setAbdate(new Date());
logService.addDatePay(datePay1);
}
/**
*
* @param userName
* @param sjid
*/
public void changeArea(String userName,int sjid){
gcuserDao.updateGwuid(userName, sjid);
}
@Transactional
public void Sgreg(String my,String up){
if(sgxtDao.getByAOrBuid(my)!=null){
throw new ServiceException(1, "");
}
Gcuser rs_my = gcuserDao.getUser(my);
if(rs_my==null){
throw new ServiceException(3000, "");
}
int zjjb = 0 ;
int cjpay = 0;
if(rs_my.getSjb()==1){
zjjb=200;cjpay=500;
}else if(rs_my.getSjb()==2){
zjjb=450;cjpay=1000;
}else if(rs_my.getSjb()==4){
zjjb=960;cjpay=2000;
}else if(rs_my.getSjb()==10){
zjjb=2500;cjpay=5000;
}else if(rs_my.getSjb()==20){
zjjb=5000;cjpay=10000;
}else if(rs_my.getSjb()==40){
zjjb=11000;cjpay=20000;
}else if(rs_my.getSjb()==100){
zjjb=30000;cjpay=50000;
}
gcuserDao.addOnlyJB(my, zjjb);
gcuserDao.updateGmdate(my, new Date());
rs_my = gcuserDao.getUser(my);
Datepay datepay = new Datepay();
datepay.setUsername(my);
datepay.setRegid(""+cjpay+""+zjjb+"-"+rs_my.getUp());
datepay.setJyjz(zjjb);
datepay.setPay(rs_my.getPay());
datepay.setJydb(rs_my.getJydb());
logService.addDatePay(datepay);
Sgxt sgxtUp = sgxtDao.get(up);
if(sgxtUp==null){
throw new ServiceException(2, "");
}
if(Strings.isNullOrEmpty(sgxtUp.getAuid())){
sgxtDao.updateAuid(up, my);
}else if(Strings.isNullOrEmpty(sgxtUp.getBuid())){
sgxtDao.updateBuid(up, my);
}else{
throw new ServiceException(3, "");
}
Sgxt sgxtMy = sgxtDao.get(my);
int sjb = sgxtMy.getSjb();
cupUser(my,my,1,sjb);
List<ZuoMingxi> zList = zuoMingxiDao.getDownList(my);
if(zList!=null&&!zList.isEmpty()){
for(ZuoMingxi zuoMingxi:zList){
int sjtjzb = zuoMingxiDao.getSumSjb(zuoMingxi.getTjuser(), zuoMingxi.getCount());
sgxtDao.updateZ(zuoMingxi.getTjuser(), sjtjzb-sjb, zuoMingxi.getCount());
}
}
List<YouMingxi> yList = youMingXiDao.getDownList(my);
if(yList!=null&&!yList.isEmpty()){
for(YouMingxi youMingxi:yList){
int sjtjzb = youMingXiDao.getSumSjb(youMingxi.getTjuser(), youMingxi.getCount());
sgxtDao.updateY(youMingxi.getTjuser(), sjtjzb-sjb, youMingxi.getCount());
}
}
CalculateQ(my, sjb);
}
private void CalculateQ(String userName,int sjb){
Sgxt sgxtBd = sgxtDao.getByAOrBuid(userName);
if(sgxtBd!=null){
if(userName.equals(sgxtBd.getAuid())){
sgxtDao.updateZaq(sgxtBd.getUsername(), sjb);
CalculateQ(sgxtBd.getUsername(),sjb);
}else{
sgxtDao.updateZbq(sgxtBd.getUsername(), sjb);
CalculateQ(sgxtBd.getUsername(),sjb);
}
}
}
private void cupUser(String my,String constUp,int count,int constSjb){
Sgxt sgxtBd = sgxtDao.getByAOrBuid(my);
if(sgxtBd!=null){
if(my.equals(sgxtBd.getAuid())){
zuoMingxiDao.delete(sgxtBd.getUsername(), constUp, count);
ZuoMingxi zuoMingxi = new ZuoMingxi();
zuoMingxi.setTjuser(sgxtBd.getUsername());
zuoMingxi.setSjb(constSjb);
zuoMingxi.setDown(constUp);
zuoMingxi.setCount(count);
zuoMingxiDao.add(zuoMingxi);
}else{
youMingXiDao.delete(sgxtBd.getUsername(), constUp, count);
YouMingxi youMingxi = new YouMingxi();
youMingxi.setCount(count);
youMingxi.setDown(constUp);
youMingxi.setTjuser(sgxtBd.getUsername());
youMingxi.setSjb(constSjb);
youMingXiDao.add(youMingxi);
}
count = count+1;
cupUser(sgxtBd.getUsername(),constUp,count,constSjb);
}
}
public void delUser(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
if(gcuser!=null&&(gcuser.getJb()>0||gcuser.getSjb()>0||gcuser.getPay()>0||gcuser.getJyg()>0)){
throw new ServiceException(1, "");
}
gcuserDao.delete(userName);
txifokDao.delete(userName);
}
public IPage<Txpay> getTranserRecordList(int pageIndex,int pageSize){
return txPayDao.getAdminPageList(pageIndex, pageSize);
}
public IPage<Mtfhtj> getMtfhtjPageList(int pageIndex,int pageSize){
return mtfhtjDao.getPageList(pageIndex, pageSize, "order by tjid desc");
}
public boolean isCanBackCount(){
Mtfhtj mtfhtj = mtfhtjDao.getFirstOne("order by tjid desc");
if(mtfhtj!=null){
if(DateUtils.getIntervalDays(new Date(), mtfhtj.getFhdate())!=1){
return true;
}else{
return false;
}
}
return true;
}
public BackCountBean getBackCountBean(){
BackCountBean backCountBean = new BackCountBean();
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
String todayEnd = todayStr+" 23:59:59";
backCountBean.setRs_nd(sgxtDao.getSumSjbByTime(todayStart, todayEnd));
// backCountBean.setRs_cb(sgxtDao.getSumZfh());
// backCountBean.setRs_mq(sgxtDao.getSumMqfh());
backCountBean.setRs_zd(sgxtDao.getSumSjb());
String monthStr = DateUtils.DateToString(new Date(),DateStyle.YYYY_MM);
String startMonthStr = monthStr+"-01 00:00:00";
String endMonthStr = monthStr+"-31 23:59:59";
backCountBean.setRs_month(sgxtDao.getSumSjbByTime(startMonthStr, endMonthStr));
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, c.get(Calendar.MONTH)-1);
String upMonthStr = DateUtils.DateToString(c.getTime(),DateStyle.YYYY_MM);
String startUpMonthStr = upMonthStr+"-01 00:00:00";
String endUpMonthStr = upMonthStr+"-31 23:59:59";
backCountBean.setRs_up_month(sgxtDao.getSumSjbByTime(startUpMonthStr, endUpMonthStr));
return backCountBean;
}
@Transactional
public synchronized void doubelAreaCount(){
Fcxt fcxt = fcxtDao.get(2);
int mqbz = fcxt.getPayadd();
// int sqbz = fcxt.getPayadd()-1;
String lastname = fcxt.getLname();
if(System.currentTimeMillis()<fcxt.getJsdate().getTime()){
throw new ServiceException(1, "22");
}
IPage<Sgxt> page = null;
Collection<Sgxt> tempData = null;
int pageIndex = 0;
int pageSize = 100;
while(true){
page = sgxtDao.getDoubleAreaCountPageList(pageIndex, pageSize);
tempData = page.getData();
if(tempData!=null&&tempData.size()>0){
for(Sgxt sgxt:tempData){
dealDoubleAreaCount(sgxt,fcxt);
}
}else{
break;
}
// pageIndex++;
}
Double rs_sgaq = sgxtDao.getSumField("aq");
Double rs_sgbq = sgxtDao.getSumField("bq");
Double rs_mq = datePayDao.getSumSyjz(mqbz);
// Sgtj sgtj = sgtjDao.get(sqbz);
// Date jsdate = sgtj.getJsdate();
Double rs_zd = sgxtDao.getSumField("sjb");
Sgxt sgxt = sgxtDao.get(lastname);
int lastid =sgxt.getId();
Double rs_nd = sgxtDao.getSumSjbById(lastid);
Double rs_cb = gcuserDao.getSumByField("cbpay");
Double rs_pa = gcuserDao.getSumByField("pay");
Double rs_tx = gcuserDao.getSumByField("txpay");
Double rs_db = gcuserDao.getSumByField("jydb");
Double rs_xt = gcuserDao.getSumByField("jyg");
Double rs_fhg = gcuserDao.getSumByField("gdgc");
Double rs_zfh = gcuserDao.getSumByField("ljfh");
Double rs_ztx = txPayDao.getSumpayNumNoCondition();
Sgtj sgtj2 = new Sgtj();
sgtj2.setZd(rs_zd.intValue());
sgtj2.setNd(rs_nd.intValue());
sgtj2.setAq(rs_sgaq.intValue());
sgtj2.setBq(rs_sgbq.intValue());
sgtj2.setZpay(rs_mq.intValue());
sgtj2.setAbp(rs_mq.intValue()/50);
sgtj2.setLdpay((int)(rs_mq*0.1));
sgtj2.setJsdate(new Date());
sgtj2.setLjcb(rs_cb);
sgtj2.setLjpa(rs_pa);
sgtj2.setLjtx(rs_tx.intValue());
sgtj2.setLjztx(rs_ztx.intValue());
sgtj2.setLjdb(rs_db);
sgtj2.setLjyg(rs_xt);
sgtj2.setLjfhg(rs_fhg);
sgtj2.setLjzfh(rs_zfh);
sgtjDao.add(sgtj2);
Sgxt rs_last = sgxtDao.getLast();
Date jsDate = DateUtils.addDay(fcxt.getJsdate(), 7);
fcxtDao.updateDoubleAreaCount(jsDate, rs_last.getUsername(), 2);
}
private void dealDoubleAreaCount(Sgxt sgxt,Fcxt fcxt){
int jsq = 0 ;
if(sgxt.getAq()==sgxt.getBq()){
jsq = sgxt.getBq();
}else if(sgxt.getAq()<sgxt.getBq()){
jsq = sgxt.getAq();
}else if(sgxt.getAq()>sgxt.getBq()){
jsq = sgxt.getBq();
}
int sgxtPay = 0;
if(jsq*50>sgxt.getFdpay()){
sgxtDao.updateDoubleCount(sgxt.getId(), sgxt.getFdpay(), sgxt.getFdpay()+sgxt.getCbpay(), 0, 0);
sgxtPay = sgxt.getFdpay();
}else{
sgxtDao.updateDoubleCount(sgxt.getId(),jsq*50, jsq*50+sgxt.getCbpay(), sgxt.getAq()-jsq, sgxt.getBq()-jsq);
sgxtPay = jsq*50;
}
Gcuser gcuser = gcuserDao.getUser(sgxt.getUsername());
if(gcuser!=null){
gcuserDao.addYbForDoubleAreaCount(gcuser.getUsername(), sgxtPay);
Datepay datepay = new Datepay();
datepay.setUsername(sgxt.getUsername());
datepay.setRegid(""+jsq+"");
datepay.setPay(gcuser.getPay()+sgxtPay);
datepay.setSyjz(sgxtPay);
datepay.setJydb(gcuser.getJydb());
datepay.setBz(fcxt.getPayadd());
datepay.setNewbz(1);
logService.addDatePay(datepay);
if(gcuser.getCxt()<3&&(gcuser.getCxdate()!=null&&gcuser.getCxdate().getTime()>System.currentTimeMillis())){
gcuserDao.reduceYbForDoubleAreaCount(gcuser.getUsername(), sgxtPay);
Datepay datepay2 = new Datepay();
datepay2.setUsername(sgxt.getUsername());
datepay2.setRegid("");
datepay2.setPay(gcuser.getPay());
datepay2.setJc(sgxtPay);
datepay2.setJydb(gcuser.getJydb());
datepay2.setBz(fcxt.getPayadd());
datepay2.setNewbz(1);
logService.addDatePay(datepay2);
}
Gcuser upUser = gcuserDao.getUser(gcuser.getUp());
if(upUser!=null&&upUser.getSjb()>0){
int addNum = (int)(sgxtPay*0.1);
gcuserDao.addYbForDoubleAreaCountJypay(upUser.getUsername(),addNum);
Datepay datepay3 = new Datepay();
datepay3.setUsername(upUser.getUsername());
datepay3.setRegid(gcuser.getUsername()+""+jsq+"");
datepay3.setPay(upUser.getPay()+addNum);
datepay3.setSyjz(addNum);
datepay3.setJydb(upUser.getJydb());
datepay3.setNewbz(8);
logService.addDatePay(datepay3);
if(upUser.getCxt()<2&&(gcuser.getCxdate()!=null&&upUser.getCxdate().getTime()>System.currentTimeMillis())){
gcuserDao.reduceYbForDoubleAreaCountJypay(upUser.getUsername(),addNum);
Datepay datepay4 = new Datepay();
datepay4.setUsername(upUser.getUsername());
datepay4.setRegid("");
datepay4.setPay(upUser.getPay());
datepay4.setJc(addNum);
datepay4.setJydb(upUser.getJydb());
datepay4.setBz(fcxt.getPayadd());
datepay4.setNewbz(8);
logService.addDatePay(datepay4);
}
}
}
}
public void backCount(Date date){
if(!isCanBackCount()){
throw new ServiceException(1, "");
}
// String todayStr = DateUtils.getDate(date);
// String todayStart = todayStr+" 00:00:00";
// IPage<Sgxt> page = null;
// Collection<Sgxt> tempData = null;
// int pageIndex = 0;
// while(true){
// page = sgxtDao.backCountPage(todayStart, pageIndex, 100);
// tempData = page.getData();
// if(tempData!=null&&tempData.size()>0){
// for(Sgxt sgxt:tempData){
// int addAmount = (int)(sgxt.getFhbl()*sgxt.getSjb()*500);
// if(gcuserDao.addYbByBackCount(sgxt.getUsername(),addAmount )){
// Gcuser gcuser = gcuserDao.getUser(sgxt.getUsername());
// Datepay datepay = new Datepay();
// datepay.setUsername(sgxt.getUsername());
// datepay.setRegid("");
// datepay.setSyjz(addAmount);
// datepay.setPay(gcuser.getPay());
// datepay.setJydb(gcuser.getJydb());
// logService.addDatePay(datepay);
// }else{
// break;
// pageIndex++;
// sgxtDao.backCount(todayStart);
String yesterdayStr = DateUtils.getDate(DateUtils.addDay(date, -1));
String yesterdayStart = yesterdayStr+" 00:00:00";
String yesterdayEnd = yesterdayStr+" 23:59:59";
Double rs_nd = sgxtDao.getSumSjbByTime(yesterdayStart, yesterdayEnd);
Double rs_cb = sgxtDao.getSumZfhBigMqfh();
Double rs_mq = sgxtDao.getSumMqfh();
Mtfhtj mtfhtj = new Mtfhtj();
mtfhtj.setFhdate(DateUtils.addDay(date, -1));
mtfhtj.setNewd((int)(rs_nd*500));
mtfhtj.setZfh(rs_cb);
mtfhtj.setMqfh(rs_mq);
mtfhtjDao.add(mtfhtj);
}
public DateBean getDateBean(){
DateBean result = new DateBean();
result.setRs(fcxtDao.get(2));
result.setRs_cb(gcuserDao.getSumCbpay());
result.setRs_pa(gcuserDao.getSumPay());
result.setRs_pal(gcuserDao.getSumPayIdRange());
result.setRs_tx(gcuserDao.getSumTxpay());
result.setRs_db(gcuserDao.getSumJydb());
result.setRs_xt(gcuserDao.getSumJyg());
result.setRs_xtl(gcuserDao.getSumJygIdRange());
result.setRs_fhg(gcuserDao.getSumGdgc());
result.setRs_fhgl(gcuserDao.getSumGdgcIdRange());
result.setRs_zfh(gcuserDao.getSumLjfh());
result.setRs_ztx(txPayDao.getSumpayNumNoCondition());
result.setRslj1(gpjyDao.getSumMcsl());
result.setRslj2(gpjyDao.getSumMysl());
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
String todayEnd = todayStr+" 23:59:59";
result.setRsjt1(gpjyDao.getSumMcslByDate(todayStart, todayEnd));
result.setRsjt2(gpjyDao.getSumMyslByDate(todayStart, todayEnd));
String yesterdayStr = DateUtils.getDate(DateUtils.addDay(new Date(), -1));
String yesterdayStart = yesterdayStr+" 00:00:00";
String yesterdayEnd = yesterdayStr+" 23:59:59";
result.setRszt1(gpjyDao.getSumMcslByDate(yesterdayStart, yesterdayEnd));
result.setRszt2(gpjyDao.getSumMyslByDate(yesterdayStart, yesterdayEnd));
String ctStr = DateUtils.getDate(DateUtils.addDay(new Date(), -2));
String ctStart = ctStr+" 00:00:00";
String ctEnd = ctStr+" 23:59:59";
result.setRsct1(gpjyDao.getSumMcslByDate(ctStart, ctEnd));
result.setRsct2(gpjyDao.getSumMyslByDate(ctStart, ctEnd));
return result;
}
public NewsDateBean getNewsDateBean(){
NewsDateBean result = new NewsDateBean();
result.setRslj(dateipDao.getCountId());
String todayStr = DateUtils.getDate(new Date());
String todayStart = todayStr+" 00:00:00";
String todayEnd = todayStr+" 23:59:59";
result.setRsjt(dateipDao.getCountByTime(todayStart, todayEnd));
String yesterdayStr = DateUtils.getDate(DateUtils.addDay(new Date(), -1));
String yesterdayStart = yesterdayStr+" 00:00:00";
String yesterdayEnd = yesterdayStr+" 23:59:59";
result.setRszt(dateipDao.getCountByTime(yesterdayStart, yesterdayEnd));
String qtStr = DateUtils.getDate(DateUtils.addDay(new Date(), -2));
String qtStart = qtStr+" 00:00:00";
String qtEnd = qtStr+" 23:59:59";
result.setRsqt(dateipDao.getCountByTime(qtStart, qtEnd));
String dqtStr = DateUtils.getDate(DateUtils.addDay(new Date(), -3));
String dqtStart = dqtStr+" 00:00:00";
String dqtEnd = dqtStr+" 23:59:59";
result.setRsdqt(dateipDao.getCountByTime(dqtStart, dqtEnd));
return result;
}
/**
*
* @param pageIndex
* @param pageSize
* @return
*/
public IPage<Dateip> getAllDateIp(int pageIndex,int pageSize){
return dateipDao.getAllPageList(pageIndex, pageSize);
}
public IPage<Cpuser> getCpuserPageList(int pageIndex,int pageSize){
return cpuserDao.getPageList(pageIndex, pageSize);
}
/**
*
* @param cpId
*/
public void recoverGoods(int cpId){
if(!jfcpDao.recoverDqjf(cpId)){
throw new ServiceException(1, "");
}
}
/**
*
* @param cgId
*/
public void fwDate(int cgId){
cpuserDao.updateFwdate(cgId);
}
public IPage<Dgag> getNoticePageList(int pageIndex,int pageSize){
return dgagDao.getAllPage(pageIndex, pageSize);
}
/**
*
* @param csUser
* @param toUserName
* @param amount
* @param ip
* @param cjfs
*/
@Transactional
public void chargeBdbByAdmin(String csUser,String toUserName,int amount,String ip,String cjfs){
Gcuser toUser = gcuserDao.getUser(toUserName);
if(toUser==null){
throw new ServiceException(1, "");
}
if(toUser.getGmdate()!=null&&toUser.getGmdate().getTime()+2*60*1000>System.currentTimeMillis()){
throw new ServiceException(2, "");
}
if((amount==5000&&toUser.getPay()<45000)||amount>5000){
if(toUser.getSyep()<amount){
throw new ServiceException(4, ""+amount+""+amount+"");
}
gcuserDao.updateCjtj(toUserName, amount);
if(!this.updateSybdbByManager(toUserName, amount, amount*2, amount*2, ""+amount+""+amount+"")){
throw new ServiceException(4, ""+amount+""+amount+"");
}
}else{
if(toUser.getPay()<9*amount){
throw new ServiceException(3, ""+amount+""+9*amount+"");
}
gcuserDao.updateCjtj(toUserName, amount);
if(!userService.changeYb(toUserName, -9*amount, "", 0, null,0)){
throw new ServiceException(3, ""+amount+""+9*amount+"");
}
userService.updateSybdb(toUserName, amount*10, ""+amount+""+9*amount+"");
}
Datecj datecj = new Datecj();
datecj.setCjuser(toUserName);
datecj.setDqcj(amount);
datecj.setLjcj(toUser.getCjtj()+amount);
datecj.setCjfs(cjfs);
datecj.setCz(csUser);
datecj.setIp(ip);
datecj.setQldate(new Date());
datecjDao.add(datecj);
}
/**
*
* @param csUser
* @param toUserName
* @param amount
* @param ip
* @param cjfs
*/
public void chargeGw(String csUser,String toUserName,int amount,String ip,String cjfs){
Gcuser toUser = gcuserDao.getUser(toUserName);
if(toUser==null){
throw new ServiceException(1, "");
}
gcuserDao.updateCjtjForGw(toUserName, amount);
Gcfh gcfh = new Gcfh();
gcfh.setUserid(toUserName);
gcfh.setSyfh(amount);
gcfh.setLjfhtj(toUser.getJjsy()+amount);
gcfh.setBz("");
gcfh.setSf(1);
gcfh.setAbdate(new Date());
gcfhDao.add(gcfh);
Datecj datecj = new Datecj();
datecj.setCjuser(toUserName);
datecj.setDqcj(amount);
datecj.setLjcj(toUser.getCjtj()+amount);
datecj.setCjfs(cjfs);
datecj.setCz(csUser);
datecj.setIp(ip);
datecj.setQldate(new Date());
datecjDao.add(datecj);
}
/**
*
* @param userName
* @return
*/
public Fcxt getAdminUser(String userName){
return fcxtDao.getAdminUser(userName);
}
/**
*
* @param userName
* @param addAmount
*/
public void addSyep(String userName,int addAmount){
if (gcuserDao.addSyep(userName, addAmount)) {
Gcuser gcuser = gcuserDao.getUser(userName);
Bdbdate bdbdate = new Bdbdate();
bdbdate.setZuser(userName);
bdbdate.setSy(addAmount);
bdbdate.setSybdb(gcuser.getSybdb());
bdbdate.setLjbdb(gcuser.getLjbdb());
bdbDateDao.add(bdbdate);
}else{
throw new ServiceException(1, "");
}
}
/**
* vip
* @param userName
* @param addAmount
*/
public void addVipcjb(String userName,int addAmount){
if(addAmount<1000||addAmount%1000!=0){
throw new ServiceException(1, "10002000300040005000600070008000");
}
Gcuser gcuser = gcuserDao.getUser(userName);
if(gcuser==null||!isCanUseVipCjb(gcuser)){
throw new ServiceException(2, "VIP");
}
if(gcuserDao.addVipcjcjb(userName, addAmount)){
Vipcjgl vipcjgl = new Vipcjgl();
vipcjgl.setCjuser("");
vipcjgl.setCjjo(addAmount);
vipcjgl.setSycjb(gcuser.getVipcjcjb()+addAmount);
vipcjgl.setVipuser(userName);
vipcjgl.setBz("");
vipcjgl.setCjdate(new Date());
vipcjglDao.add(vipcjgl);
}
}
private boolean isCanUseVipCjb(Gcuser gcuser){
//vipvip
if(gcuser.getVip()==2){
return true;
}else{
return false;
}
}
/**
*
* @param userName
* @param addAmount
*/
public void addBtPay(String userName,int addAmount){
if(gcuserDao.addWhenOtherPersionBuyJbCard(userName, addAmount)){
Gcuser gcuser = gcuserDao.getUser(userName);
Datepay datePay = new Datepay();
datePay.setUsername(gcuser.getUsername());
datePay.setSyjz(addAmount);
datePay.setPay(gcuser.getPay());
datePay.setJydb(gcuser.getJydb());
datePay.setRegid("");
datePay.setNewbz(0);
datePay.setAbdate(new Date());
logService.addDatePay(datePay);
}
}
/**
*
* @param userName
* @param jb
* @param dqDate
*/
public void changeDldate(String userName,int jb,String dlDate,String dqDate){
Gcuser gcuser = gcuserDao.getUser(userName);
if(gcuser.getDldate()!=null||gcuser.getDqdate()!=null){
Date dldate = DateUtils.StringToDate(dlDate, DateStyle.YYYY_MM_DD_HH_MM_SS);
Date dqdate = DateUtils.StringToDate(dqDate, DateStyle.YYYY_MM_DD_HH_MM_SS);
gcuserDao.updateAdminLevel(userName, jb,dldate,dqdate);
}else{
throw new ServiceException(1, "");
}
}
/**
*
* @param userName
*/
public void changeSheng(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
String sheng = gcuser.getAddsheng();
if(gcuserDao.getByAddress("addsheng", sheng, 2)!=null){
throw new ServiceException(2, "");
}
Date now = new Date();
gcuserDao.updateAdminLevel(userName, 2,now , DateUtils.addDay(now, 180));
}
/**
*
* @param userName
*/
public void changeShi(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
String addshi = gcuser.getAddshi();
if(gcuserDao.getByAddress("addshi", addshi, 3)!=null){
throw new ServiceException(3, "");
}
Date now = new Date();
gcuserDao.updateAdminLevel(userName, 3,now , DateUtils.addDay(now, 90));
}
/**
*
* @param userName
*/
public void changeArea(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
String addqu = gcuser.getAddqu();
if(gcuserDao.getByAddress("addqu", addqu, 4)!=null){
throw new ServiceException(4, "");
}
Date now = new Date();
gcuserDao.updateAdminLevel(userName, 4,now , DateUtils.addDay(now, 60));
}
/**
*
* @param userName
*/
public void changeBigArea(String userName){
Gcuser gcuser = gcuserDao.getUser(userName);
Integer dqu = gcuser.getDqu();
if(gcuserDao.getByAddress("dqu", dqu, 1)!=null){
throw new ServiceException(5, "");
}
Date now = new Date();
gcuserDao.updateAdminLevel(userName, 1,now , DateUtils.addDay(now, 180));
}
/**
*
* @param bdUser
* @param sjb
*/
@Transactional
public void adminBdUser(String bduser,int sjb){
Gcuser bdGUser = gcuserDao.getUser(bduser);
if(bdGUser==null||bdGUser.getSjb()==0){
throw new ServiceException(1,"");
}
Sgxt sgxt = sgxtDao.get(bduser);
if(sgxt==null){
throw new ServiceException(2,"");
}
List<ZuoMingxi> zList = zuoMingxiDao.getDownList(bduser);
if(zList!=null&&!zList.isEmpty()){
for(ZuoMingxi zuoMingxi:zList){
int sjtjzb = zuoMingxiDao.getSumSjb(zuoMingxi.getTjuser(), zuoMingxi.getCount());
if(sjtjzb>0){
if(zuoMingxi.getCount()>0&&zuoMingxi.getCount()<=16){
sgxtDao.updateZfiled(zuoMingxi.getTjuser(), "z"+zuoMingxi.getCount(), sjtjzb,sjtjzb-sjb,zuoMingxi.getCount());
}
}
}
}
List<YouMingxi> yList = youMingXiDao.getDownList(bduser);
if(yList!=null&&!yList.isEmpty()){
for(YouMingxi youMingxi:yList){
int sjtjzb = youMingXiDao.getSumSjb(youMingxi.getTjuser(), youMingxi.getCount());
if(sjtjzb>0){
if(youMingxi.getCount()>0&&youMingxi.getCount()<=16){
sgxtDao.updateYfiled(youMingxi.getTjuser(), "y"+youMingxi.getCount(), sjtjzb,sjtjzb-sjb,youMingxi.getCount());
}
}
}
}
List<Bdbdate> logList = Lists.newArrayList();
userService.CalculateQ(bduser, sjb, bduser,logList);
bdbDateDao.batchInsert(logList);
}
/**
*
* @param userName
* @param pageIndex
* @param pageSize
* @return
*/
public IPage<Tduser> getTduserPage(String userName,int pageIndex,int pageSize){
return tduserDao.getPage(userName, pageIndex, pageSize);
}
/**
*
* @param userName
* @param pageIndex
* @param pageSize
* @param day
* @return
*/
public IPage<Gcuser> getSqDayAddUsers(int pageIndex,int pageSize,Integer day){
String[] strArray = new String[2];
if(day!=null){
strArray = getTime(day);
}
return gcuserDao.getSqDayAddUserPages(pageIndex, pageSize, strArray[0], strArray[1],null);
}
public IPage<Gcuser> getSqDayAddUsersByTime(int pageIndex,int pageSize,String startTime,String endTime,String sheng){
if(!Strings.isNullOrEmpty(startTime)&&!Strings.isNullOrEmpty(endTime)){
startTime = startTime +" 00:00:00";
endTime = endTime+" 23:59:59";
}else{
return null;
}
return gcuserDao.getSqDayAddUserPages(pageIndex, pageSize, startTime, endTime,sheng);
}
public List<GcuserForExcel> getSqdayAddUsersForExcel(Integer day){
String[] strArray = new String[2];
if(day!=null){
strArray = getTime(day);
}
return gcuserDao.getSqDayAddUserList(strArray[0], strArray[1],null);
}
public List<GcuserForExcel> getSqdayAddUsersForExcelByTime(String startTime,String endTime,String sheng){
if(!Strings.isNullOrEmpty(startTime)&&!Strings.isNullOrEmpty(endTime)){
startTime = startTime +" 00:00:00";
endTime = endTime+" 23:59:59";
}else{
return new ArrayList<GcuserForExcel>(0);
}
return gcuserDao.getSqDayAddUserList(startTime, endTime,sheng);
}
private String[] getTime(int day){
String startTime = null;
String endTime = null;
String baseStr = null;
if(day==0){
baseStr = DateUtils.getDate(new Date());
}else{
baseStr = DateUtils.getDate(DateUtils.addDay(new Date(), day));
}
startTime = baseStr +" 00:00:00";
endTime = baseStr +" 23:59:59";
return new String[]{startTime,endTime};
}
public SqDayAddBean getSqDayAddBean(){
SqDayAddBean result = new SqDayAddBean();
String[] jt = getTime(0);
String[] zt = getTime(-1);
String[] qt = getTime(-2);
String[] dqt = getTime(-3);
result.setJt(gcuserDao.getSumSjbByTime(jt[0], jt[1]));
result.setZt(gcuserDao.getSumSjbByTime(zt[0], zt[1]));
result.setQt(gcuserDao.getSumSjbByTime(qt[0], qt[1]));
result.setDqt(gcuserDao.getSumSjbByTime(dqt[0], dqt[1]));
return result;
}
public IPage<W10Bean> getTxpayPage(int pageIndex,int pageSize,String uid,String uname,String riqi){
// String baseStr = DateUtils.DateToString(DateUtils.addDay(new Date(), 9),DateStyle.YYYY_MM_DD_HH_MM_SS);
String startTime = null;
String endTime = null;
if(!Strings.isNullOrEmpty(riqi)){
// Date date = DateUtils.StringToDate(riqi, DateStyle.YYYY_MM_DD_EN);
// String baseStr = DateUtils.DateToString(date,DateStyle.YYYY_MM_DD);
startTime = riqi+" 00:00:00";
endTime = riqi+" 23:59:59";
}
return txpayDao.getPageListW10(pageIndex, pageSize,uid,uname,startTime,endTime);
}
public void syusers(int payId,int op){
txpayDao.updateTxvip(payId, op);
txpayDao.updateIndexTxvip(payId, op);
}
/**
* tduser
* @param tdId
* @return
*/
public Tduser getTduser(Integer tdId){
if(null!=tdId){
return tduserDao.get(new SqlParamBean("id", tdId));
}
return null;
}
/**
*
* @param pageIndex
* @param pageSize
* @param param
* @return
*/
public IPage<Tduser> getTduserPageList(int pageIndex,int pageSize,String param){
return tduserDao.getTduserPageList(param, pageIndex, pageSize);
}
/**
* tduser
* @param tdname
* @param tduserid
* @param tduser
* @param tdcall
* @param tdqq
*/
public void addTduser(String tdname,String tduserid,String tduser,String tdcall,String tdqq){
if(tduserDao.get(new SqlParamBean("tduserid", tduserid))!=null){
throw new ServiceException(1, "["+tduserid+"]");
}
Tduser t = new Tduser();
t.setTdname(tdname);
t.setTduserid(tduserid);
t.setTduser(tduser);
t.setTdqq(tdqq);
t.setTdcall(tdcall);
tduserDao.add(t);
}
/**
* tduser
* @param id
* @param tdname
* @param tduserid
* @param tduser
* @param tdcall
* @param tdqq
*/
public void updateTduser(Integer id,String tdname,String tduserid,String tduser,String tdcall,String tdqq){
if(!tduserDao.update(id, tdname, tduserid, tduser, tdcall, tdqq)){
throw new ServiceException(2, ""+id);
}
}
/**
*
* @param fromUser
* @param toUser
*/
public void transferUserInfo(String fromUser,String toUser){
Gcuser from = gcuserDao.getUser(fromUser);
Gcuser to = gcuserDao.getUser(toUser);
if(from==null){
throw new ServiceException(3, ""+fromUser);
}
if(to==null){
throw new ServiceException(4, ""+toUser);
}
String tduserid = from.getUserid();
String tdname = from.getName();
if(tduserDao.getTdUserRecord(tduserid)!=null){
throw new ServiceException(5, "["+tduserid+"]");
}
if(from.getUserid().equals(to.getUserid())||from.getName().equals(to.getName())){
throw new ServiceException(6, ""+toUser);
}
gcuserDao.updateUserInfoToOtherUser(tduserid, tdname, toUser);
Tduser t = new Tduser();
t.setTdname(tdname);
t.setTduserid(tduserid);
t.setTduser(fromUser);
t.setTdqq(from.getQq());
t.setTdcall(from.getCall());
tduserDao.add(t);
}
/**
* xxxx
*/
public void man123(){
Fcxt fcxt = fcxtDao.get(2);
int ration = 30000000;
try {
ration = Integer.valueOf(fcxt.getCz04());
} catch (Exception e) {
LogSystem.warn("cz04~~~");
}
if (fcxtDao.updateJy5w(ration)) {
try {
PointsChangeLog changeLog = new PointsChangeLog();
changeLog.setCreatedTime(new Date());
String oldPrice = fcxt.getJygj() + "";
oldPrice = StringUtils.substring(oldPrice, 0, 5);
changeLog.setOldPrice(oldPrice);
String newPrice = (fcxt.getJygj() + 0.01) + "";
newPrice = StringUtils.substring(newPrice, 0, 5);
changeLog.setNewPrice(newPrice);
changeLog.setCurrentNum(fcxt.getJy5w() + "");
changeLog.setUpRation(ration + "");
pointsChangeLogDao.add(changeLog);
} catch (Exception e) {
LogSystem.error(e, "");
}
}
gcuserDao.updateAbdateAndDbtl(">30", 0, new Date(), 1);
gcuserDao.updateAbdateAndDbtl("<=30", 1, null, 0);
double jyj = fcxt.getJygj()+0.2;
int pageIndex = 0;
int pageSize = 100;
Collection<Gcuser> tempList = null;
IPage<Gcuser> page = null;
String endTime = DateUtils.DateToString(DateUtils.addDay(new Date(), -7),DateStyle.YYYY_MM_DD_HH_MM_SS);
while(true){
page= gcuserDao.getBatchUser(pageIndex, pageSize, endTime);
if(page!=null){
tempList = page.getData();
if(tempList!=null&&tempList.size()>0){
for(Gcuser gcuser:tempList){
String clname = gcuser.getUsername();
int dbjc = gcuser.getJydb()-30;
double jc30 = dbjc*0.3;
int hs30 = (int)jc30;
if(hs30>0){
gcuserDao.reduceOnlyJB(clname, hs30);
adddatepay(clname, hs30, gcuser.getJydb()-hs30, gcuser.getPay(), ""+dbjc+"30%");
}
}
}else{
break;
}
}else{
break;
}
pageIndex++;
}
pageIndex = 0;
while(true){
page= gcuserDao.getBatchUser(pageIndex, pageSize, endTime);
if(page!=null){
tempList = page.getData();
if(tempList!=null&&tempList.size()>0){
for(Gcuser gcuser:tempList){
String clname=gcuser.getUsername();
int jydball=gcuser.getJydb();
int jydbnumber=gcuser.getJydb()-30;
int ForCount=(int)(jydbnumber/30);
int lasenumber=jydbnumber%30;
if(ForCount>0){
for(int j=1;j<=ForCount;j++){
int insertid = adddatepay(clname,30,jydball-j*30,gcuser.getPay(),"()");
addGpjy(clname,30,(jydball-ForCount*30)*1d,insertid,jyj);
}
}
if(lasenumber>1){
int insertid=adddatepay(clname,lasenumber,jydball-ForCount*30-lasenumber,gcuser.getPay(),"()");
addGpjy(clname,lasenumber,(jydball-ForCount*30-lasenumber)*1d,insertid,jyj);
}
gcuserDao.updateMan1234(clname, 30, null, 0);
}
}else{
break;
}
}else{
break;
}
pageIndex++;
}
}
private int adddatepay(String clname,int jo,int jydb,int pay,String regId){
Datepay datepay = new Datepay();
datepay.setUsername(clname);
datepay.setDbjc(jo);
datepay.setPay(pay);
datepay.setJydb(jydb);
datepay.setRegid(regId);
return datePayDao.addDatePay(datepay);
}
private void addGpjy(String clname,int mysl,double jyg,int jyid,double jyj){
Gpjy gpjy = new Gpjy();
gpjy.setUsername(clname);
gpjy.setMysl((int)(mysl/jyj+0.1)/1d);
gpjy.setSysl(jyg);
gpjy.setPay(jyj);
gpjy.setBz("()");
gpjy.setJypay((int)(mysl+0.1)/1d);
gpjy.setJyid(jyid);
gpjyDao.add(gpjy);
}
public void managequeren(){
gcuserDao.updateJygdateAndJygt1(">50000", 0, new Date(), 1);
gcuserDao.updateJygdateAndJygt1("<=50000", 1, null, 0);
int pageIndex = 0;
int pageSize = 100;
Collection<Gcuser> tempList = null;
IPage<Gcuser> page = null;
String endTime = DateUtils.DateToString(DateUtils.addDay(new Date(), -7),DateStyle.YYYY_MM_DD_HH_MM_SS);
LogSystem.info("30%~");
int dmSize = 0;
int loseSize = 0;
while(true){
page= gcuserDao.getManageQueren(pageIndex, pageSize, endTime);
if(page!=null){
tempList = page.getData();
if(tempList!=null&&tempList.size()>0){
for(Gcuser gcuser:tempList){
try {
String clname = gcuser.getUsername();
double mcsl = gcuser.getJyg() - 50000;
double mc30 = mcsl * 0.3;
int hs30 = (int) (mc30 / 1);
if (hs30 > 0) {
dmSize++;
if (gcuserDao.updateJyg(clname, hs30)) {
Gpjy gpjy = new Gpjy();
gpjy.setUsername(clname);
gpjy.setMcsl(hs30 * 1d);
gpjy.setSysl((gcuser.getJyg() - hs30) * 1d);
gpjy.setBz("" + mcsl + "30%");
gpjy.setDfuser("");
gpjy.setCgdate(new Date());
gpjy.setJy(1);
gpjyDao.add(gpjy);
}
}
} catch (Exception e) {
loseSize++;
LogSystem.error(e, "userName="+gcuser.getUsername()+",30%");
}
}
}else{
break;
}
}else{
break;
}
pageIndex++;
}
LogSystem.info("30%="+dmSize+","+loseSize);
pageIndex = 0;
Fcxt fcxt = fcxtDao.get(2);
LogSystem.info("~");
dmSize= 0;
loseSize = 0;
while(true){
page= gcuserDao.getManageQueren(pageIndex, pageSize, endTime);
if(page!=null){
tempList = page.getData();
if(tempList!=null&&tempList.size()>0){
for (Gcuser gcuser : tempList) {
try {
dmSize++;
String clname = gcuser.getUsername();
int jygall = gcuser.getJyg();
int jygnumber = gcuser.getJyg() - 50000;
int ForCount = (int) (jygnumber / 200);
int lasenumber = jygnumber % 200;
if (ForCount > 0) {
for (int j = 1; j <= ForCount; j++) {
addGpjyForManageQueren(clname, 200, jygall - j * 200, fcxt.getZdj());
}
}
if (lasenumber > 0) {
addGpjyForManageQueren(clname, lasenumber, jygall - ForCount * 200 - lasenumber,
fcxt.getZdj());
}
gcuserDao.updateManageQueren(clname, 50000, null, 0);
} catch (Exception e) {
loseSize++;
LogSystem.error(e, "userName="+gcuser.getUsername()+",");
}
}
}else{
break;
}
}else{
break;
}
}
LogSystem.info("="+dmSize+","+loseSize);
}
private void addGpjyForManageQueren(String clname,double mcsl,double jyg,double jg){
Gpjy gpjy = new Gpjy();
gpjy.setUsername(clname);
gpjy.setMcsl(mcsl);
gpjy.setSysl(jyg);
gpjy.setPay(jg);
gpjy.setJy(0);
gpjy.setBz("()");
gpjy.setJypay((int)(mcsl*jg*1+0.1)*1d);
gpjy.setNewjy(3);
gpjyDao.add(gpjy);
}
private List<YouMingxi> yList = Lists.newArrayList();
private List<ZuoMingxi> zList = Lists.newArrayList();
private final String Y_FILE_NAME = "D://temp//youmingxi.sql";
private final String Z_FILE_NAME = "D://temp//zuomingxi.sql";
public void resetUserDownInfo(){
long allStartTime = System.currentTimeMillis();
LogSystem.info("z y
int pageIndex = 0;
final int pageSize = 500;
IPage<Sgxt> page = null;
Collection<Sgxt> tempList = null;
yList = Lists.newArrayList();
zList = Lists.newArrayList();
FileCreatUtil.creatNewFile(Y_FILE_NAME);
FileCreatUtil.creatNewFile(Z_FILE_NAME);
// youMingXiDao.deleteAll();
// zuoMingxiDao.deleteAll();
while(true){
long startTime = System.currentTimeMillis();
long programeEndTime = System.currentTimeMillis();
page = sgxtDao.getPageList(pageIndex, pageSize);
if(page!=null){
tempList = page.getData();
if(tempList!=null&&tempList.size()>0){
for(Sgxt sgxt:tempList){
cupUserForReset(sgxt.getUsername(),sgxt.getUsername(),1,sgxt.getSjb());
}
programeEndTime = System.currentTimeMillis();
}else{
break;
}
}else{
break;
}
executeInsertSql();
long endTime = System.currentTimeMillis();
LogSystem.info("("+(pageIndex+1)+")("+page.getTotalPage()+"),"+(endTime-startTime)+"===="+(endTime-startTime)/1000+""+(programeEndTime-startTime)/1000+"="+(endTime-programeEndTime)/1000+"");
pageIndex++;
}
LogSystem.info("
}
private void cupUserForReset(String my,String constUp,int count,int sjb){
Sgxt sgxtBd = sgxtDao.getByAOrBuid(my);
if(sgxtBd!=null){
if(my.equals(sgxtBd.getAuid())){
ZuoMingxi zuoMingxi = new ZuoMingxi();
zuoMingxi.setTjuser(sgxtBd.getUsername());
zuoMingxi.setSjb(sjb);
zuoMingxi.setDown(constUp);
zuoMingxi.setCount(count);
zList.add(zuoMingxi);
}else{
YouMingxi youMingxi = new YouMingxi();
youMingxi.setCount(count);
youMingxi.setDown(constUp);
youMingxi.setTjuser(sgxtBd.getUsername());
youMingxi.setSjb(sjb);
yList.add(youMingxi);
}
count = count+1;
cupUserForReset(sgxtBd.getUsername(),constUp,count,sjb);
}
}
private final String preYouMingXI = "INSERT INTO `you_mingxi` VALUES ";
private final String preZuoMingXI = "INSERT INTO `zuo_mingxi` VALUES ";
private void executeInsertSql(){
if(yList.size()>0){
StringBuffer yBuffer = new StringBuffer();
yBuffer.append(preYouMingXI);
int y=0;
for(YouMingxi youMingxi:yList){
if(y==0){
yBuffer.append(youMingxi.insertStr());
}else{
yBuffer.append(","+youMingxi.insertStr());
}
y++;
}
yBuffer.append(";\r\n");
//youMingXiDao.batchInsert(yList);
FileCreatUtil.appendFile(Y_FILE_NAME, yBuffer.toString());
LogSystem.info("youMingxi("+yList.size()+")");
}else{
LogSystem.info("zList");
}
if(zList.size()>0){
StringBuffer zBuffer = new StringBuffer();
zBuffer.append(preZuoMingXI);
int z=0;
for(ZuoMingxi zuoMingxi:zList){
if(z==0){
zBuffer.append(zuoMingxi.insertStr());
}else{
zBuffer.append(","+zuoMingxi.insertStr());
}
z++;
}
zBuffer.append(";\r\n");
//youMingXiDao.batchInsert(yList);
FileCreatUtil.appendFile(Z_FILE_NAME, zBuffer.toString());
//zuoMingxiDao.batchInsert(zList);
LogSystem.info("zuoMingxi("+zList.size()+")");
}else{
LogSystem.info("yList");
}
yList = Lists.newArrayList();
zList = Lists.newArrayList();
}
public void executeSynNameSql(){
int pageIndex = 0;
final int pageSize = 1000;
IPage<Gcuser> page = null;
Collection<Gcuser> tempList = null;
final String FILEName = "E://temp//name_update.sql";
FileCreatUtil.creatNewFile(FILEName);
while(true){
page = gcuserDao.getPageList(pageIndex, pageSize);
tempList = page.getData();
StringBuffer buffer = new StringBuffer();
if(tempList!=null&&tempList.size()>0){
for(Gcuser gcuser:tempList){
buffer.append("update gcuser set name='"+gcuser.getName()+"' where id="+gcuser.getId()+" and username='"+gcuser.getUsername()+"';\r\n");
}
FileCreatUtil.appendFile(FILEName, buffer.toString());
}else{
break;
}
pageIndex++;
}
}
public void resetZaqAndZbq(){
long allStartTime = System.currentTimeMillis();
LogSystem.info("zaq zbq---"+new Date());
int pageIndex = 0;
final int pageSize = 500;
IPage<Sgxt> page = null;
Collection<Sgxt> tempList = null;
sgxtDao.resetZaqAndZbq();
while(true){
long startTime = System.currentTimeMillis();
long programeEndTime = System.currentTimeMillis();
page = sgxtDao.getPageList(pageIndex, pageSize);
if(page!=null){
tempList = page.getData();
if(tempList!=null&&tempList.size()>0){
for(Sgxt sgxt:tempList){
CalculateQ(sgxt.getUsername(), sgxt.getSjb());
}
programeEndTime = System.currentTimeMillis();
}else{
break;
}
}else{
break;
}
long endTime = System.currentTimeMillis();
LogSystem.info("("+(pageIndex+1)+")("+page.getTotalPage()+"),"+(endTime-startTime)+"===="+(endTime-startTime)/1000+""+(programeEndTime-startTime)/1000+"="+(endTime-programeEndTime)/1000+"");
pageIndex++;
}
LogSystem.info("
}
public void resetUserZaqAndZbq(String userName){
long allStartTime = System.currentTimeMillis();
LogSystem.info("zaq zbq---["+userName+"]"+new Date());
if(sgxtDao.resetZaqAndZbq(userName)){
Sgxt sgxt = sgxtDao.get(userName);
if (sgxt != null) {
if (!Strings.isNullOrEmpty(sgxt.getAuid())) {
CalculateUserLeftZaq(userName, sgxt.getAuid());
}
if (!Strings.isNullOrEmpty(sgxt.getBuid())) {
CalculateUserRightZbq(userName, sgxt.getBuid());
}
}
}
LogSystem.info("
}
private void CalculateUserLeftZaq(String constantUserName,String auid){
Sgxt sgxt = sgxtDao.get(auid);
if(sgxt!=null){
sgxtDao.updateZaq(constantUserName, sgxt.getSjb());
if(!Strings.isNullOrEmpty(sgxt.getAuid())){
CalculateUserLeftZaq(constantUserName, sgxt.getAuid());
}
if(!Strings.isNullOrEmpty(sgxt.getBuid())){
CalculateUserLeftZaq(constantUserName, sgxt.getBuid());
}
}
}
private void CalculateUserRightZbq(String constantUserName,String buid){
Sgxt sgxt = sgxtDao.get(buid);
if(sgxt!=null){
sgxtDao.updateZbq(constantUserName, sgxt.getSjb());
if(!Strings.isNullOrEmpty(sgxt.getAuid())){
CalculateUserRightZbq(constantUserName, sgxt.getAuid());
}
if(!Strings.isNullOrEmpty(sgxt.getBuid())){
CalculateUserRightZbq(constantUserName, sgxt.getBuid());
}
}
}
public boolean callRemoteCharge(String call,int amount,String ip,String userName){
LogSystem.info("--,"+userName+""+""+call+""+","+amount+",ip"+ip+"");
_99douInterface _99dou = new _99douInterface();
String out_trade_id = userName+"-"+DateUtils.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM_SS_EN);
String account = call;
String account_info = "";
int quantity=1;
String value = amount+"";
String client_ip = ip;
int expired_mini = 5;
Ref<String> msg = new Ref<String>();
int result = -1;
try {
result =_99dou.Huafei(out_trade_id, account, account_info, quantity, value, client_ip, expired_mini, msg);
} catch (Exception e) {
LogSystem.error(e, "");
throw new ServiceException(100, "");
}
LogSystem.info(" :"+result+" :"+msg);
if(result==0){
return true;
}
return false;
}
public IPage<Vipxtgc> getVipxtgcPageList(String userName,String startDate,String endDate,int pageIndex,int pageSize){
return vipxtgcDao.getPage(userName, startDate, endDate, pageIndex, pageSize);
}
/**
* vip
* @param userName
* @param vipType 0vip 2vip 3vip
* @param vipuser
* @param vipgh
* @param vipnh
* @param vipzh
* @param phone
* @param qq
*/
@Transactional
public void updateUserVipInfo(String adminUserName,String userName,int vipType,String vipuser,String vipgh,String vipnh,String vipzh,String vipjh,String phone,String qq,String ip){
String commitParam = userName+":"+vipType+":"+vipuser+":"+vipgh+":"+vipnh+":"+vipjh+":"+vipzh+":"+phone+":"+qq;
if(vipType==0){ // vip
gcuserDao.updateVip(userName, 0);
sgxtDao.updateVip(userName, 0);
userVipLogDao.add(new UserVipLog(userName, 2, adminUserName, ip, commitParam, new Date()));
}else{ //vip
gcuserDao.updateVip(userName, vipType);
sgxtDao.updateVip(userName, 1);
gcuserDao.updateVipInfo(userName, vipuser, vipgh, vipjh, vipnh, vipzh, phone, qq);
userVipLogDao.add(new UserVipLog(userName, 1, adminUserName, ip, commitParam, new Date()));
}
}
/**
* payok
* @param userName
* @param payok
* @param regTime
* @return
*/
@Transactional
public String updateUserPayOk(String userName,Integer payok,String regTime,String password3End){
Date date = null;
if(regTime!=null){
date = DateUtils.StringToDate(regTime,DateStyle.YYYY_MM_DD);
}
StringBuffer result = new StringBuffer();
batchUpdateDownPayok(userName, result, date, payok,password3End);
return result.toString();
}
private void batchUpdateDownPayok(String userName,StringBuffer stringBuffer,Date date,Integer payok,String password3End){
Sgxt sgxt = sgxtDao.get(userName);
if(sgxt!=null){
if(!Strings.isNullOrEmpty(sgxt.getAuid())){
updateUserPayOk(sgxt.getAuid(), stringBuffer,date,payok,password3End);
batchUpdateDownPayok(sgxt.getAuid(), stringBuffer, date, payok,password3End);
}
if(!Strings.isNullOrEmpty(sgxt.getBuid())){
updateUserPayOk(sgxt.getBuid(), stringBuffer,date,payok,password3End);
batchUpdateDownPayok(sgxt.getBuid(), stringBuffer, date, payok,password3End);
}
}
}
private void updateUserPayOk(String userName,StringBuffer stringBuffer,Date date,Integer payok,String password3End){
Gcuser gcuser = gcuserDao.getUser(userName);
if(date==null||gcuser.getRegtime().getTime()>date.getTime()){
// LogSystem.info("["+userName+"]pend="+password3End);
gcuserDao.updatePayOkAndPassword3End(gcuser.getName(), gcuser.getUserid(), payok,password3End);
stringBuffer.append("["+gcuser.getUsername()+"]");
}
}
public List<String> getAllVipName(){
List<Gcuser> list = gcuserDao.getAllVip();
List<String> result = Lists.newArrayList();
for(Gcuser gcuser:list){
result.add(gcuser.getUsername());
}
return result;
}
public void editYbSale(String userName,String opPass,int fhpay,int vippay){
if(!opPass.equals("yc201503yc")){
throw new ServiceException(1, "");
}
if(!gcuserDao.updateFhpayAndVippay(userName, fhpay, vippay)){
throw new ServiceException(2, "");
}
}
// private String[] arrayRandomName = new String[]{"sineg","siwnrw","aneing","064300","uie168","shs888","8515mycq","abc888888a","742ymjc","kuang888","niw168"};
private String getRadomUserName(List<Gcuser> gcuser){
int random = new Random().nextInt(gcuser.size());
return gcuser.get(random).getUsername();
}
public synchronized void dealJfMrOrderForChaiFen(String date){
if(Strings.isNullOrEmpty(date)){
LogSystem.info("date");
return;
}
LogSystem.info(",date="+date);
final int pageSize = 500;
List<Gpjy> page = null;
List<Gcuser> listRandomUserName = gcuserDao.getCompanlyUser();
while(true){
page = gpjyDao.getMrPageForSystem(pageSize,date);
if(page!=null&&page.size()>0){
LogSystem.info(" ="+page.size()+",[]");
long sigleStartTime = System.currentTimeMillis();
for(Gpjy gpjy:page){
try {
mcJfForSystem(getRadomUserName(listRandomUserName), gpjy);
} catch (Exception e) {
LogSystem.error(e, "[]---gpgy="+gpjy);
}
}
long sigleEndTime = System.currentTimeMillis();
LogSystem.info(" ="+page.size()+",="+(sigleEndTime-sigleStartTime)/1000+"");
}else{
break;
}
}
LogSystem.info("");
}
private void mcJfForSystem(String userName,Gpjy gpjy1){
Gcuser dfuser = gcuserDao.getUser(gpjy1.getUsername());
if (!gpjyDao.updateBuySuccess(gpjy1.getId(), userName, "",(int)(dfuser.getJyg()+gpjy1.getMysl()))) {
throw new ServiceException(2, "");
}
gpjyDao.deleteIndex(gpjy1.getId());
gcuserDao.updateJyg(gpjy1.getUsername(), -gpjy1.getMysl().intValue());
String mydj = gpjy1.getPay() < 1 ? "0" + gpjy1.getPay() : "" + gpjy1.getPay();
String d = DateUtils.DateToString(gpjy1.getCgdate(), DateStyle.YYYY_MM_DD_HH_MM_SS);
String dStr = d==null?"":d;
logService.updateRegId(gpjy1.getJyid(),dStr
+ "" + userName + "-" + gpjy1.getMysl() + "-" + mydj);
// fcxtDao.update(2, gpjy1.getMysl().intValue());
}
private final String beishu = "1.6";
private final double dijia = 0.78;
public synchronized void JygChaifen(){
Fcxt fcxt = fcxtDao.get(10);
Date d = DateUtils.addDay(fcxt.getJsdate(), 3);
int updateNum = gcuserDao.updateJfChaifen(beishu, d);
int insertNum = gcuserDao.insertIntoChaifenLog(beishu, d);
fcxtDao.updateChaiFen(2, dijia);
gcuserDao.updateJygdateAndJygt1(">50000", 0, new Date(), 1);
gcuserDao.updateJygdateAndJygt1("<=50000", 1, null, 0);
LogSystem.info("At"+DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS)+":"+DateUtils.DateToString(d, DateStyle.YYYY_MM_DD_HH_MM_SS)+","+beishu+","+dijia+",gcuser"+updateNum+",gpjy:"+insertNum+"");
}
/**
* 370%
*/
public synchronized void jfdm(){
int maxId = gcuserDao.getMaxId();
int startId = 1;
int endId = 500;
int cap = 500;
List<Gcuser> list = null;
while(true){
long start = System.currentTimeMillis();
LogSystem.info("--idstart="+startId+",end="+endId+",Id="+maxId);
list = gcuserDao.getByIdDistance(startId, endId);
if(list!=null&&list.size()>0){
LogSystem.info(""+list.size());
for(Gcuser gcuser:list){
int blsl = getBlsl(gcuser.getSjb());
int kmcsl = gcuser.getJyg()-blsl;
if(kmcsl>0){
int mcbs = getMcbs(kmcsl);
String clname = gcuser.getUsername();
int jygall = gcuser.getJyg();
int jygnumber = gcuser.getJyg()-blsl;
int ForCount = (int)(jygnumber/mcbs);
int lasenumber=jygnumber % mcbs;
if(ForCount>0){
for(int j=1;j<=ForCount;j++){
addGpjyForChaiFeng(clname,mcbs,jygall-j*mcbs);
}
}
if(lasenumber>0){
addGpjyForChaiFeng(clname,lasenumber,jygall-ForCount*mcbs-lasenumber);
}
gcuserDao.resetCfc(gcuser.getUsername(), blsl);
}
}
}
long end = System.currentTimeMillis();
LogSystem.info("--idstart="+startId+",end="+endId+"="+(end-start)/1000+"");
if(endId>=maxId){
break;
}
startId = endId+1;
endId = endId+cap;
}
gcuserDao.updateJygdateAndJygt1(">50000", 0, new Date(), 1);
gcuserDao.updateJygdateAndJygt1("<=50000", 1, null, 0);
}
private void addGpjyForChaiFeng(String clname,int mcsl,double jyg){
Gpjy gpjy = new Gpjy();
gpjy.setUsername(clname);
gpjy.setMcsl(mcsl*1d);
gpjy.setSysl(jyg);
gpjy.setPay(dijia);
gpjy.setJy(0);
gpjy.setBz("()");
gpjy.setJypay((int)(mcsl*dijia+0.1)/1d);
gpjy.setNewjy(3);
gpjyDao.add(gpjy);
}
private int getBlsl(int sjb){
if(sjb==100){
return 25000;
}else if(sjb==40){
return 15000;
} else if(sjb==20){
return 10000;
}else if(sjb==10){
return 5000;
}else if(sjb==4){
return 2000;
}else if(sjb==2){
return 1000;
}
return 0;
}
private int getMcbs(int kmcsl){
if(kmcsl>30000){
return 2000;
}else if(kmcsl>20000){
return 1500;
}else if(kmcsl>10000){
return 1200;
}else if(kmcsl>5000){
return 800;
}else if(kmcsl>3000){
return 500;
}
return kmcsl;
}
/**
*
* @param userName
* @param startYear
* @param endYear
* @return
*/
private int getUserThisYearSiglePerformance(String userName,String startTime,String endTime){
if(startTime!=null&&endTime!=null){
startTime = startTime + " 00:00:00";
endTime = endTime + " 23:59:59";
}
Gcuser gcuser = gcuserDao.getUser(userName);
return gcuserDao.getUserSigleSumSjbByTime(userName,gcuser.getUserid(), startTime, endTime);
}
/**
*
* @param userName
* @param startYear
* @param endYear
* @return
*/
// private int getUserThisYearAllPerformance(String userName,String startTime,String endTime){
// int zAll = zuoMingxiDao.getZUserAllPerformanceByTime(userName, startTime, endTime);
// int yAll = youMingXiDao.getYUserAllPerformanceByTime(userName, startTime, endTime);
// return zAll+yAll;
/**
* 5
* @param userName
* @return
*/
private boolean isFiveStepFull(String userName){
for(int i=1;i<=5;i++){
if(zuoMingxiDao.getDownCountByStep(userName,i)<Math.pow(2, i)/2||youMingXiDao.getDownCountByStep(userName,i)<Math.pow(2, i)/2){
return false;
}
}
return true;
}
/**
*
* @param userName
* @param startTime
* @param endTime
* @return
*/
public UserPerformanceSearch getUserPerformanceSearch(String userName,String startTime,String endTime){
UserPerformanceSearch result = new UserPerformanceSearch();
result.setSigleAllPerformance(getUserThisYearSiglePerformance(userName, null, null));
result.setSigleTimeAllPerformance(getUserThisYearSiglePerformance(userName, startTime, endTime));
startTime = startTime + " 00:00:00";
endTime = endTime + " 23:59:59";
result.setFiveLeftPerformance(zuoMingxiDao.getZUserAllPerformanceByTime(userName, null, null,5));
result.setFiveLeftTimePerformance(zuoMingxiDao.getZUserAllPerformanceByTime(userName, startTime, endTime,5));
result.setFiveRightPerformance(youMingXiDao.getYUserAllPerformanceByTime(userName, null, null,5));
result.setFiveRightTimePerformance(youMingXiDao.getYUserAllPerformanceByTime(userName, startTime, endTime,5));
result.setSgxt(sgxtDao.get(userName));
result.setAllTimeLeftPerformance(zuoMingxiDao.getZUserAllPerformanceByTime(userName, startTime, endTime,0));
result.setAllTimeRightPerformance(youMingXiDao.getYUserAllPerformanceByTime(userName, startTime, endTime,0));
result.setIsFiveFull(isFiveStepFull(userName));
result.setPerformance(getUserFiveStepPerformance(userName));
Sgxt up = sgxtDao.getByAOrBuid(userName);
result.setUp(up);
return result;
}
/**
* 5
* @param userName
* @return
*/
public Performance getUserFiveStepPerformance(String userName){
Performance performance = generatorCommonPerformance(userName);
generatorDownMap(performance,1,5);
return performance;
}
/**
*
* @param userName
* @return
*/
private Performance generatorCommonPerformance(String userName){
Sgxt sgxt = sgxtDao.get(userName);
if(sgxt!=null){
Performance performance = new Performance();
performance.setUserName(userName);
performance.setBdbdate(sgxt.getBddate());
performance.setSjb(sgxt.getSjb());
performance.setZaq(sgxt.getZaq());
performance.setZbq(sgxt.getZbq());
return performance;
}else{
return null;
}
}
/**
*
* @param performance
* @param count
* @param max
*/
private void generatorDownMap(Performance performance,int count,int max){
if(performance==null||count>max){
return;
}
Sgxt sgxt = sgxtDao.get(performance.getUserName());
if(!Strings.isNullOrEmpty(sgxt.getAuid())){
Performance left = generatorCommonPerformance(sgxt.getAuid());
if(left!=null){
performance.setLeft(left);
left.setParent(performance);
generatorDownMap(left,count+1,max);
}
}
if(!Strings.isNullOrEmpty(sgxt.getBuid())){
Performance right = generatorCommonPerformance(sgxt.getBuid());
if(right!=null){
performance.setRight(right);
right.setParent(performance);
generatorDownMap(right,count+1,max);
}
}
}
public void shareMoney(){
Fcxt fcxt = fcxtDao.get(10);
Date date = DateUtils.addDay(fcxt.getJsdate(), 2);
long allStartTime = System.currentTimeMillis();
LogSystem.info("---"+new Date());
String dyRation = "0.12";
String xyRation = "0.01";
String cmRation = "0.005";
LogSystem.info("---"+DateUtils.DateToString(date, DateStyle.YYYY_MM_DD_HH_MM_SS_CN)+""+new Date());
executeDyRegTimeShareMoney(dyRation, date);
LogSystem.info("---"+DateUtils.DateToString(date, DateStyle.YYYY_MM_DD_HH_MM_SS_CN)+""+new Date());
LogSystem.info("---"+DateUtils.DateToString(date, DateStyle.YYYY_MM_DD_HH_MM_SS_CN)+""+new Date());
executeXyRegTimeShareMoney(xyRation, date);
LogSystem.info("---"+DateUtils.DateToString(date, DateStyle.YYYY_MM_DD_HH_MM_SS_CN)+""+new Date());
LogSystem.info(""+new Date());
executeCommonRegTimeShareMoney(cmRation);
LogSystem.info(""+new Date());
long allEndTime = System.currentTimeMillis();
LogSystem.info(""+(allEndTime-allStartTime)/1000+"");
}
@Transactional
public void executeDyRegTimeShareMoney(String ration,Date date){
int uNum = gcuserDao.updateMemberSharePayDyDate(date, ration);
int insertGcfhNum = gcuserDao.insertMemberShareGcfhLogDyDate(date, ration);
int insertDatepayNum = gcuserDao.insertMemberShareDatepayLogDyDate(date, ration);
LogSystem.info("["+uNum+"],gcfh["+insertGcfhNum+"],datepay["+insertDatepayNum+"]");
}
@Transactional
public void executeXyRegTimeShareMoney(String ration,Date date){
int uNum = gcuserDao.updateMemberSharePayXyDate(date, ration);
int insertGcfhNum = gcuserDao.insertMemberShareGcfhLogXyDate(date, ration);
int insertDatepayNum = gcuserDao.insertMemberShareDatepayLogXyDate(date, ration);
LogSystem.info("["+uNum+"],gcfh["+insertGcfhNum+"],datepay["+insertDatepayNum+"]");
}
@Transactional
public void executeCommonRegTimeShareMoney(String ration){
int uNum =gcuserDao.updateCommonSharePay(ration);
int insertGcfhNum = gcuserDao.insertCommonShareGcfhLogXyDate(ration);
int insertDatepayNum = gcuserDao.insertCommonShareDatepayLogXyDate(ration);
LogSystem.info("["+uNum+"],gcfh["+insertGcfhNum+"],datepay["+insertDatepayNum+"]");
}
@Transactional
public synchronized void insertPosition(String userName,String zOry,String insertUser,int sjb){
Sgxt sgxt = sgxtDao.get(userName);
if(sgxt==null){
throw new ServiceException(1, "");
}
String beReplaceUser = null;
if(zOry.equals("z")){
if(Strings.isNullOrEmpty(sgxt.getAuid())){
throw new ServiceException(2, "");
}
beReplaceUser = sgxt.getAuid();
}else if(zOry.equals("y")){
if(Strings.isNullOrEmpty(sgxt.getBuid())){
throw new ServiceException(3, "");
}
beReplaceUser = sgxt.getBuid();
}else{
throw new ServiceException(4, "zy,"+zOry);
}
Gcuser gcuser = gcuserDao.getUser(insertUser);
Sgxt sgxtBeReplace = sgxtDao.get(beReplaceUser);
if(gcuser==null||sgxtBeReplace==null){
throw new ServiceException(5, ""+insertUser);
}
Sgxt insertUserSgx = sgxtDao.get(insertUser);
if(insertUserSgx!=null){
throw new ServiceException(6, ""+insertUser);
}
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("DROP TABLE IF EXISTS `sgxt1`;CREATE TABLE `sgxt1` LIKE `sgxt`;");
stringBuffer.append("insert into sgxt1 select * from sgxt where username='"+beReplaceUser+"';");
stringBuffer.append("update sgxt1 set id=(select max(id)+1 from sgxt),username='"+insertUser+"',sjb="+sjb+" where username='"+beReplaceUser+"';");
stringBuffer.append("insert into sgxt select * from sgxt1 where username='"+insertUser+"';");
stringBuffer.append("update zuo_mingxi set down='"+insertUser+"',sjb="+sjb+" where down='"+beReplaceUser+"';");
stringBuffer.append("update you_mingxi set down='"+insertUser+"',sjb="+sjb+" where down='"+beReplaceUser+"';");
stringBuffer.append("update zuo_mingxi set tjuser='"+insertUser+"' where tjuser='"+beReplaceUser+"';");
stringBuffer.append("update you_mingxi set tjuser='"+insertUser+"' where tjuser='"+beReplaceUser+"';");
if(zOry.equals("z")){
stringBuffer.append("update sgxt set auid='"+insertUser+"' where username='"+userName+"';");
stringBuffer.append("insert into zuo_mingxi values(null,'"+insertUser+"','"+beReplaceUser+"',"+sgxtBeReplace.getSjb()+",1);");
}else{
stringBuffer.append("update sgxt set buid='"+insertUser+"' where username='"+userName+"';");
stringBuffer.append("insert into you_mingxi values(null,'"+insertUser+"','"+beReplaceUser+"',"+sgxtBeReplace.getSjb()+",1);");
}
stringBuffer.append("update sgxt set auid='"+beReplaceUser+"',buid=null where username='"+insertUser+"';");
stringBuffer.append("insert into zuo_mingxi select null,z.tjuser,'"+beReplaceUser+"',"+sgxtBeReplace.getSjb()+",z.count+1 from zuo_mingxi z where down='"+insertUser+"';");
stringBuffer.append("insert into you_mingxi select null,z.tjuser,'"+beReplaceUser+"',"+sgxtBeReplace.getSjb()+",z.count+1 from you_mingxi z where down='"+insertUser+"';");
stringBuffer.append("insert into zuo_mingxi select null,'"+beReplaceUser+"',z.down,z.sjb,z.count+1 from zuo_mingxi z where tjuser='"+insertUser+"';");
stringBuffer.append("insert into you_mingxi select null,'"+beReplaceUser+"',z.down,z.sjb,z.count+1 from you_mingxi z where tjuser='"+insertUser+"';");
//zaqzbq
stringBuffer.append("update sgxt set zaq=zaq+"+sjb+" where username in(select tjuser from zuo_mingxi where down='"+insertUser+"');");
stringBuffer.append("update sgxt set zbq=zbq+"+sjb+" where username in(select tjuser from you_mingxi where down='"+insertUser+"');");
stringBuffer.append("update sgxt set zaq="+(sgxtBeReplace.getZaq()+sgxtBeReplace.getZbq()+sgxtBeReplace.getSjb())+" where username ='"+insertUser+"';");
stringBuffer.append("update sgxt set zbq=0,bq=0 where username ='"+insertUser+"';");
LogSystem.info(" sql"+stringBuffer.toString());
String[] sqlArray = stringBuffer.toString().split(";");
for(int i=0;i<sqlArray.length;i++){
int result = sgxtDao.executeSql(sqlArray[i]);
LogSystem.info("sql"+sqlArray[i]+""+result);
}
// sgxtDao.executeSql(stringBuffer.toString());
gcuserDao.updateSjb(insertUser, sjb);
}
// public void generatorTopReward(Date date){
// LogSystem.info("="+DateUtils.getDate(date));
// long startTimes = System.currentTimeMillis();
// List<UserPerformance> searchs = Lists.newArrayList();
// int year = DateUtils.getYear(date);
// String startTime = year+"-01-01 00:00:00";
// String endTimeStr = DateUtils.getDate(date);
// String endTime = endTimeStr+" 23:59:59";
// List<TopReward> list = gcuserDao.getUserTopReward(startTime);
// if(list!=null&&list.size()>0){
// for(TopReward tr:list){
// searchs.add(getUserPerformanceBO(tr.getUp(),startTime, endTime));
// if(searchs.size()>0){
// userPerformanceDao.insert(searchs);
// long endTimes = System.currentTimeMillis();
// LogSystem.info("="+DateUtils.getDate(date)+","+searchs.size()+",="+(endTimes-startTimes)/1000+"");
public List<UserPerformance> getUserPerformancePage(){
// return userPerformanceDao.getListPage(time, pageIndex, pageSize);
Date end = DateUtils.StringToDate("2016-01-02 00:00:00", DateStyle.YYYY_MM_DD_HH_MM_SS);
String d = DateUtils.getDate(new Date());
if(new Date().getTime()>end.getTime()){
d = "2016-01-01";
}
List<UserPerformance> searchs = userPerformanceDao.getListPage(d);
if(searchs!=null&&searchs.size()>0){
return searchs;
}
String startTime = "2015-01-01 00:00:00";
String endTime = "2015-12-31 23:59:59";
List<TopReward> list = gcuserDao.getUserTopReward(startTime);
if(list!=null&&list.size()>0){
for(TopReward tr:list){
UserPerformance t = getUserPerformanceBO(tr.getUp(),startTime, endTime);
if(t!=null){
searchs.add(t);
}
}
userPerformanceDao.removeAll();
userPerformanceDao.insert(searchs);
}
return searchs;
}
public UserPerformance getUserPerformanceBO(String userName,String startTime,String endTime){
UserPerformance result = new UserPerformance();
result.setSigleAllPerformance(getUserThisYearSiglePerformance(userName, null, null));
result.setSigleTimeAllPerformance(getUserThisYearSiglePerformance(userName, startTime, endTime));
// startTime = startTime + " 00:00:00";
// endTime = endTime + " 23:59:59";
result.setFiveLeftPerformance(zuoMingxiDao.getZUserAllPerformanceByTime(userName, null, null,5));
result.setFiveLeftTimePerformance(zuoMingxiDao.getZUserAllPerformanceByTime(userName, startTime, endTime,5));
result.setFiveRightPerformance(youMingXiDao.getYUserAllPerformanceByTime(userName, null, null,5));
result.setFiveRightTimePerformance(youMingXiDao.getYUserAllPerformanceByTime(userName, startTime, endTime,5));
Sgxt sgxt = sgxtDao.get(userName);
result.setZaq(sgxt.getZaq());
result.setZbq(sgxt.getZbq());
result.setAllTimeLeftPerformance(zuoMingxiDao.getZUserAllPerformanceByTime(userName, startTime, endTime,0));
result.setAllTimeRightPerformance(youMingXiDao.getYUserAllPerformanceByTime(userName, startTime, endTime,0));
boolean isfivefull = isFiveStepFull(userName);
result.setFu(isfivefull?1:0);
result.setAddTime(new Date());
result.setUserName(userName);
return result;
}
public void setVerifile(String userName,int verify){
if(verify==0){
userExtinfoDao.updateUserExtinfo(userName, verify);
}else{
if(!userExtinfoDao.updateUserExtinfo(userName, verify)){
userExtinfoDao.add(new UserExtinfo(userName,verify));
}
}
}
public Fcxt getFcxt(int id){
return fcxtDao.get(id);
}
public void updateJy5wRation(int ration){
fcxtDao.updateJy5wRation(ration);
}
public void updateCz04(int cz04){
fcxtDao.updateCz04(cz04+"");
}
public YbCjbBean getStatBean(String userName,String startDate,String endDate){
if(!Strings.isNullOrEmpty(startDate)&&!Strings.isNullOrEmpty(endDate)){
startDate = startDate +" 00:00:00";
endDate = endDate+" 23:59:59";
}
YbCjbBean bean = new YbCjbBean();
bean.setInCjb(vipcjglDao.getSumVipSr(userName, startDate, endDate));
bean.setOutCjb(vipcjglDao.getSumVipZc(userName, startDate, endDate));
bean.setInYb(datePayDao.getSumSyjz(userName, startDate, endDate));
bean.setOutYb(datePayDao.getSumjc(userName, startDate, endDate));
Gcuser gcuser = gcuserDao.getUser(userName);
bean.setNowYb(gcuser.getPay());
bean.setNowCjb(gcuser.getVipcjcjb());
return bean;
}
public IPage<PointsChangeLog> getPointChangeLogPage(int pageIndex,int pageSize){
return pointsChangeLogDao.getPageList(pageIndex, pageSize, "order by id desc");
}
/**
*
* @param userName
* @param sjbCount
* @return
*/
public void addAqOrBqForUserNoLog(String userName,int sjbCount,String desc){
String tag = "["+desc+"],["+userName+"]["+sjbCount+"]"+"time=["+new Date()+"]==>";
List<ZuoMingxi> zList = zuoMingxiDao.getDownList(userName);
for(ZuoMingxi zm:zList){
int sumCountSjb = zuoMingxiDao.getSumSjb(zm.getTjuser(), zm.getCount());
Sgxt sg = sgxtDao.get(zm.getTjuser());
int canAdd = sg.getCfd()-sumCountSjb;
if(canAdd>0){
if(sgxtDao.updateAq(zm.getTjuser(), canAdd)){
LogSystem.log(tag+"["+zm.getTjuser()+"]["+zm.getCount()+"]"+canAdd+"["+sumCountSjb+"],"+sg.getCfd());
}else{
LogSystem.log(tag+"["+zm.getTjuser()+"]["+zm.getCount()+"]"+canAdd+"["+sumCountSjb+"],"+sg.getCfd());
}
}else{
LogSystem.log(tag+"["+zm.getTjuser()+"]["+zm.getCount()+"]["+sumCountSjb+"],["+sg.getCfd()+"]");
}
}
List<YouMingxi> yList = youMingXiDao.getDownList(userName);
for(YouMingxi ym:yList){
int sumCountSjb = youMingXiDao.getSumSjb(ym.getTjuser(), ym.getCount());
Sgxt sg = sgxtDao.get(ym.getTjuser());
int canAdd = sg.getCfd()-sumCountSjb;
if(canAdd>0){
if(sgxtDao.updateAq(ym.getTjuser(), canAdd)){
LogSystem.log(tag+"["+ym.getTjuser()+"]["+ym.getCount()+"]"+canAdd+"["+sumCountSjb+"],"+sg.getCfd());
}else{
LogSystem.log(tag+"["+ym.getTjuser()+"]["+ym.getCount()+"]"+canAdd+"["+sumCountSjb+"],"+sg.getCfd());
}
}else{
LogSystem.log(tag+"["+ym.getTjuser()+"]["+ym.getCount()+"]["+sumCountSjb+"],["+sg.getCfd()+"]");
}
}
LogSystem.log(tag+"");
}
/**
*
* @param opUser
* @param user
* @param addAq
* @param addBq
* @param ip
* @return
*/
public boolean updateUserAqOrBq(String opUser,String user,int addAq,int addBq,String ip){
String logTag = "["+opUser+"]AQBQ,IP=["+ip+"],date="+new Date()+"user=["+user+"],addAq=["+addAq+"],addBq=["+addBq+"]==>";
boolean result1 = sgxtDao.updateAq(user, addAq);
boolean result2 = sgxtDao.updateBq(user, addBq);
LogSystem.log(logTag+",aqResult=["+result1+"],bqResult=["+result2+"]");
return result1&result2;
}
public static void main(String[] args) {
String str = "0.820000000000";
System.out.println(StringUtils.substring(str, 0, 5));
}
} |
package de.prob2.ui.chart;
import java.util.ArrayList;
import java.util.List;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import de.prob.animator.domainobjects.AbstractEvalResult;
import de.prob.animator.domainobjects.ClassicalB;
import de.prob.animator.domainobjects.EvalResult;
import de.prob.animator.domainobjects.EvaluationException;
import de.prob.animator.domainobjects.IEvalElement;
import de.prob.animator.domainobjects.IdentifierNotInitialised;
import de.prob.statespace.State;
import de.prob.statespace.StateSpace;
import de.prob.statespace.TraceElement;
import de.prob2.ui.history.HistoryView;
import de.prob2.ui.internal.StageManager;
import de.prob2.ui.layout.FontSize;
import de.prob2.ui.prob2fx.CurrentTrace;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public final class HistoryChartStage extends Stage {
private static final class ClassicalBListCell extends ListCell<ClassicalB> {
private ClassicalBListCell() {
super();
}
@Override
protected void updateItem(final ClassicalB item, final boolean empty) {
super.updateItem(item, empty);
this.setText(item == null || empty ? null : item.getCode());
this.setGraphic(null);
}
@Override
public void startEdit() {
super.startEdit();
if (!this.isEditing()) {
return;
}
final TextField textField = new TextField(this.getText());
textField.setOnAction(event -> {
textField.getStyleClass().remove("text-field-error");
final ClassicalB formula;
try {
formula = new ClassicalB(textField.getText());
} catch (EvaluationException e) {
LOGGER.debug("Could not parse user-entered formula", e);
textField.getStyleClass().add("text-field-error");
return;
}
this.commitEdit(formula);
});
textField.textProperty().addListener(observable -> textField.getStyleClass().remove("text-field-error"));
this.setText(null);
this.setGraphic(textField);
}
}
private static class TraceElementStringConverter extends StringConverter<TraceElement> {
@Override
public String toString(final TraceElement object) {
return object == DUMMY_TRACE_ELEMENT ? "(no model loaded)"
: HistoryView.transitionToString(object.getTransition());
}
@Override
public TraceElement fromString(final String string) {
throw new UnsupportedOperationException("Cannot convert from string to TraceElement");
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(HistoryChartStage.class);
private static final TraceElement DUMMY_TRACE_ELEMENT = new TraceElement(new State("Dummy state", null));
@FXML
private FlowPane chartsPane;
@FXML
private LineChart<Number, Number> singleChart;
@FXML
private ListView<ClassicalB> formulaList;
@FXML
private Button addButton;
@FXML
private Button removeButton;
@FXML
private CheckBox separateChartsCheckBox;
@FXML
private ChoiceBox<TraceElement> startChoiceBox;
private final StageManager stageManager;
private final CurrentTrace currentTrace;
private final Injector injector;
private final ObservableList<LineChart<Number, Number>> separateCharts;
@Inject
private HistoryChartStage(final StageManager stageManager, final CurrentTrace currentTrace,
final Injector injector) {
super();
this.stageManager = stageManager;
this.currentTrace = currentTrace;
this.separateCharts = FXCollections.observableArrayList();
this.injector = injector;
stageManager.loadFXML(this, "history_chart_stage.fxml", this.getClass().getName());
}
@FXML
private void initialize() {
this.formulaList.setCellFactory(view -> new ClassicalBListCell());
this.formulaList.getItems().addListener((ListChangeListener<ClassicalB>) change -> {
while (change.next()) {
if (change.wasRemoved()) {
this.removeCharts(change.getFrom(), change.getFrom() + change.getRemovedSize());
}
if (change.wasAdded()) {
this.addCharts(change.getFrom(), change.getTo(), change.getList());
}
}
this.updateCharts();
});
this.removeButton.disableProperty()
.bind(Bindings.isEmpty(this.formulaList.getSelectionModel().getSelectedIndices()));
this.separateChartsCheckBox.selectedProperty().addListener((observable, from, to) -> {
if (to) {
this.chartsPane.getChildren().setAll(this.separateCharts);
} else {
this.chartsPane.getChildren().setAll(this.singleChart);
}
});
this.separateChartsCheckBox.setSelected(true);
this.startChoiceBox.setConverter(new HistoryChartStage.TraceElementStringConverter());
this.startChoiceBox.valueProperty().addListener((observable, from, to) -> this.updateCharts());
this.singleChart.prefWidthProperty().bind(this.chartsPane.widthProperty());
this.singleChart.prefHeightProperty().bind(this.chartsPane.heightProperty());
this.showingProperty().addListener((observable, from, to) -> {
if (to) {
this.updateStartChoiceBox();
}
});
this.currentTrace.addListener((observable, from, to) -> this.updateStartChoiceBox());
this.updateStartChoiceBox();
FontSize fontsize = injector.getInstance(FontSize.class);
((FontAwesomeIconView) (addButton.getGraphic())).glyphSizeProperty().bind(fontsize.multiply(1.2));
((FontAwesomeIconView) (removeButton.getGraphic())).glyphSizeProperty().bind(fontsize.multiply(1.2));
}
@FXML
private void handleAdd() {
this.formulaList.getItems().add(new ClassicalB("0"));
this.formulaList.edit(this.formulaList.getItems().size() - 1);
}
@FXML
private void handleRemove() {
this.formulaList.getItems().remove(this.formulaList.getSelectionModel().getSelectedIndex());
}
private void removeCharts(final int start, final int end) {
this.singleChart.getData().remove(start, end);
this.separateCharts.remove(start, end);
if (this.separateChartsCheckBox.isSelected()) {
this.chartsPane.getChildren().remove(start, end);
}
}
private void addCharts(final int start, final int end, final List<? extends ClassicalB> charts) {
for (int i = start; i < end; i++) {
final XYChart.Series<Number, Number> seriesSingle = new XYChart.Series<>(charts.get(i).getCode(),
FXCollections.observableArrayList());
this.singleChart.getData().add(i, seriesSingle);
final XYChart.Series<Number, Number> seriesSeparate = new XYChart.Series<>(charts.get(i).getCode(),
FXCollections.observableArrayList());
final NumberAxis separateXAxis = new NumberAxis();
separateXAxis.getStyleClass().add("time-axis");
separateXAxis.setAutoRanging(false);
separateXAxis.setTickUnit(1.0);
separateXAxis.setUpperBound(0.0);
final NumberAxis separateYAxis = new NumberAxis();
final LineChart<Number, Number> separateChart = new LineChart<>(separateXAxis, separateYAxis,
FXCollections.singletonObservableList(seriesSeparate));
separateChart.getStyleClass().add("history-chart");
seriesSingle.getData().addListener((ListChangeListener<XYChart.Data<Number, Number>>) change -> {
// Update the separate chart series whenever the single chart
// series is updated.
while (change.next()) {
if (change.wasRemoved()) {
seriesSeparate.getData().remove(change.getFrom(), change.getFrom() + change.getRemovedSize());
}
if (change.wasAdded()) {
seriesSeparate.getData().addAll(change.getFrom(), change.getAddedSubList());
}
}
// Update the upper bound of the X axis of the separate chart
separateXAxis.setUpperBound(change.getList().isEmpty() ? 1.0
: change.getList().get(change.getList().size() - 1).getXValue().doubleValue());
});
separateChart.setMinWidth(160);
separateChart.setMinHeight(80);
separateChart.setMaxWidth(Double.POSITIVE_INFINITY);
separateChart.setMaxHeight(Double.POSITIVE_INFINITY);
// Adjust the sizes of all separate charts so they always fill the
// entire flow pane, and are as close as possible to 320px * 240px.
// We subtract 1.0 from the resulting width/height, to ensure that
// the sum is not larger than the flow pane's width/height.
// Otherwise the charts jump around as the flow pane tries to make
// them fit.
separateChart.prefWidthProperty()
.bind(Bindings.createDoubleBinding(
() -> (chartsPane.getWidth() / Math.round(chartsPane.getWidth() / 320.0)) - 1.0,
chartsPane.widthProperty()));
separateChart.prefHeightProperty()
.bind(Bindings.createDoubleBinding(
() -> (chartsPane.getHeight() / Math.round(chartsPane.getHeight() / 240.0)) - 1.0,
chartsPane.heightProperty()));
this.separateCharts.add(i, separateChart);
if (this.separateChartsCheckBox.isSelected()) {
this.chartsPane.getChildren().add(i, separateChart);
}
}
}
private void updateStartChoiceBox() {
if (!this.isShowing()) {
return;
}
if (this.currentTrace.exists()) {
final TraceElement startElement = this.startChoiceBox.getValue();
this.startChoiceBox.getItems().clear();
TraceElement element = currentTrace.get().getCurrent();
TraceElement prevElement = element;
while (element != null) {
this.startChoiceBox.getItems().add(element);
prevElement = element;
element = element.getPrevious();
}
this.startChoiceBox
.setValue(startElement == null || startElement == DUMMY_TRACE_ELEMENT ? prevElement : startElement);
} else {
this.startChoiceBox.getItems().setAll(DUMMY_TRACE_ELEMENT);
this.startChoiceBox.setValue(DUMMY_TRACE_ELEMENT);
}
this.updateCharts();
}
private void updateCharts() {
if (!this.isShowing()) {
return;
}
final List<List<XYChart.Data<Number, Number>>> newDatas = new ArrayList<>();
for (int i = 0; i < this.singleChart.getData().size(); i++) {
newDatas.add(new ArrayList<>());
}
int elementCounter = 0;
if (this.currentTrace.exists()) {
final StateSpace stateSpace = this.currentTrace.getStateSpace();
// Workaround for StateSpace.eval only taking exactly a
// List<IEvalElement>, and not a List<ClassicalB>
final List<IEvalElement> formulas = new ArrayList<>(this.formulaList.getItems());
final TraceElement startElement = this.startChoiceBox.getValue();
TraceElement element = this.currentTrace.get().getCurrent();
TraceElement prevElement = element;
boolean showErrors = true;
while (element != null && prevElement != startElement) {
final List<AbstractEvalResult> results = stateSpace.eval(element.getCurrentState(), formulas);
for (int i = 0; i < results.size(); i++) {
final AbstractEvalResult result = results.get(i);
if (result instanceof IdentifierNotInitialised) {
continue;
}
final int value;
try {
value = resultToInt(result, showErrors);
} catch (IllegalArgumentException e) {
LOGGER.debug("Not convertible to int, ignoring", e);
continue;
}
newDatas.get(i).add(0, new XYChart.Data<>(elementCounter, value));
}
prevElement = element;
element = element.getPrevious();
elementCounter++;
// Only display errors to the user for the current state (otherwise errors are repeated for every state)
showErrors = false;
}
}
double maxXBound = 1.0;
for (int i = 0; i < newDatas.size(); i++) {
final List<XYChart.Data<Number, Number>> newData = newDatas.get(i);
for (XYChart.Data<Number, Number> newDatum : newData) {
newDatum.setXValue(elementCounter - newDatum.getXValue().intValue() - 1);
}
if (!newData.isEmpty()) {
final double lastX = newData.get(newData.size() - 1).getXValue().doubleValue();
if (lastX > maxXBound) {
maxXBound = lastX;
}
}
this.singleChart.getData().get(i).getData().setAll(newData);
}
((NumberAxis) this.singleChart.getXAxis()).setUpperBound(maxXBound);
}
private int resultToInt(final AbstractEvalResult aer, final boolean showErrors) {
if (aer instanceof EvalResult) {
final String value = ((EvalResult) aer).getValue();
if ("TRUE".equals(value)) {
return 1;
} else if ("FALSE".equals(value)) {
return 0;
} else {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
if (showErrors) {
stageManager.makeAlert(Alert.AlertType.ERROR, "Could not evaluate formula for history chart: Not a valid integer: " + e.getMessage()).show();
}
throw new IllegalArgumentException("Could not evaluate formula for history chart: Not a valid integer", e);
}
}
} else {
if (showErrors) {
stageManager.makeAlert(Alert.AlertType.ERROR, "Could not evaluate formula for history chart: Invalid result: " + aer).show();
}
throw new IllegalArgumentException("Could not evaluate formula for history chart: Expected an EvalResult, not " + aer.getClass().getName());
}
}
} |
package edu.uib.info310.search;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.uib.info310.transformation.XslTransformer;
public class LastFMSearch {
private static final String similarArtistRequest = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=";
private static final String artistEvents = "http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist=";
private static final String apiKey = "&api_key=a7123248beb0bbcb90a2e3a9ced3bee9";
private static final Logger LOGGER = LoggerFactory.getLogger(LastFMSearch.class);
public InputStream getArtistEvents (String artist) throws Exception {
URL lastFMRequest = new URL(artistEvents+artist+apiKey);
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
public InputStream getSimilarArtist(String artist) throws Exception {
URL lastFMRequest = new URL(similarArtistRequest+artist+apiKey);
URLConnection lastFMConnection = lastFMRequest.openConnection();
return lastFMConnection.getInputStream();
}
public static void main(String[] args) throws Exception {
File xsl = new File("src/main/resources/XSL/Events.xsl");
LastFMSearch search = new LastFMSearch();
XslTransformer transform = new XslTransformer();
transform.setXml(search.getArtistEvents("Metallica"));
transform.setXsl(xsl);
System.out.println(transform.transform());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.