answer
stringlengths 17
10.2M
|
|---|
package org.usfirst.frc.team1492.robot;
//import java.awt.dnd.Autoscroll;
import java.util.HashMap;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.Joystick.AxisType;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Ultrasonic;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
public class Robot extends SampleRobot {
Talon motorLeft;
Talon motorRight;
Talon motorCenter; // Motor controller for the middle of the H
Talon motorLift;
Talon motorArm;
DoubleSolenoid pistonArmTilt1;
DoubleSolenoid pistonArmTilt2;
DoubleSolenoid pistonLiftWidth;
Solenoid pistonCenterSuspension;
// PIDController PIDControllerLift;
AnalogInput analogLift;
DigitalInput digitalInLiftTop;
DigitalInput digitalInLiftBottom;
DigitalInput digitalInArmUp;
DigitalInput digitalInArmDown;
PowerDistributionPanel pdp;
AnalogInput frontDistanceSensor;
Joystick stickLeft;
Joystick stickRight;
Joystick stickAux;
boolean[] stickAuxLastButton;
double SETTING_hDriveDampening;
double SETTING_motorLiftSpeed;
double SETTING_armLiftSpeed;
int liftPos = 0;
int liftPosMax = 4;
int liftPosMin = 0;
double[] liftPosPresets = { 0, .25, .5, .75, 1 };
HashMap<Integer, String> autoModes = new HashMap<Integer, String>();
final int autoModeNone = 0;
final int autoModeToZone = 1;
final int autoModeToZoneOver = 2;
final int autoModeGrabToZone = 3;
final int autoModeGrabToZoneOver = 4;
/*final int autoModeDriveToAutoZone = 1;
final int autoModeDriveToAutoZoneOverPlatform = 2;
final int autoModeGrabCanAndDriveToAutoZone = 3;
final int autoModeGrabCanAndDriveToAutoZoneOverScoringPlatform = 4;
final int autoModeDriveIntoAutoZoneFromLandfill = 5;
final int autoModeGrabCanOffStep = 6;
final int autoModeGrabToteOrCanMoveBack = 7;
final int autoModeGrabToteOrCanMoveBackOverScoringPlatform = 8;*/
int autoMode = autoModeNone;
Command autoCommand;
SendableChooser autoChooser;
public Robot() {
motorLeft = new Talon(1);
motorRight = new Talon(2);
motorCenter = new Talon(0);
motorLift = new Talon(4);
motorArm = new Talon(3);
pistonArmTilt1 = new DoubleSolenoid(1, 0);
pistonArmTilt2 = new DoubleSolenoid(2, 3);
pistonLiftWidth = new DoubleSolenoid(4, 5);
pistonCenterSuspension = new Solenoid(6);
analogLift = new AnalogInput(0);
digitalInLiftTop = new DigitalInput(0);
digitalInLiftBottom = new DigitalInput(1);
digitalInArmUp = new DigitalInput(3);
digitalInArmDown = new DigitalInput(2);
//schuyler 480 526 1606
pdp = new PowerDistributionPanel();
frontDistanceSensor = new AnalogInput(1);
//sonicVex = new Ultrasonic(5, 6);
//sonicVex.setAutomaticMode(true);
/*
* PIDControllerLift = new PIDController(0, 0, 0, analogLift,
* motorLift); PIDControllerLift.setInputRange(0, 1);
* PIDControllerLift.setOutputRange(0, .5); PIDControllerLift.disable();
*/
stickLeft = new Joystick(0);
stickRight = new Joystick(1);
stickAux = new Joystick(2);
stickAuxLastButton = new boolean[stickAux.getButtonCount()];
autoModes.put(autoModeNone, "None");
autoModes.put(autoModeToZone, "Move to Zone");
autoModes.put(autoModeToZoneOver, "Move over platform to Zone");
autoModes.put(autoModeGrabToZone, "Grab and move to zone");
autoModes.put(autoModeGrabToZoneOver, "Grab and move over platform to zone");
/*autoModes.put(autoModeDriveToAutoZone, "(Tested) Drive to Auto Zone");
autoModes.put(autoModeDriveToAutoZoneOverPlatform, "(Untested) Drive to Auto Zone Over Platform");
autoModes.put(autoModeGrabCanAndDriveToAutoZone, "(Tested) Grab Can and drive to Auto Zone");
autoModes.put(autoModeGrabCanAndDriveToAutoZoneOverScoringPlatform, "(Untested) Grab Can to and drive Auto Zone over Scoring Platform");
autoModes.put(autoModeDriveIntoAutoZoneFromLandfill, "(Untested) Drive into Auto Zone from Landfill");
autoModes.put(autoModeGrabCanOffStep, "(Untested) Grab Can off step");
autoModes.put(autoModeGrabToteOrCanMoveBack, "(Untested) Grab Tote or can and move to auto zone");
autoModes.put(autoModeGrabToteOrCanMoveBackOverScoringPlatform, "(Untested) Grab Tote or can and move to auto zone (driving over scoring platform)");
*/
autoChooser = new SendableChooser();
autoChooser.addDefault("No Auto", 0);
int i = 0;
int counter = 0;
while(counter < autoModes.size()){
if(autoModes.containsKey(i)){
autoChooser.addObject(autoModes.get(i), i);
counter++;
}
i++;
}
SmartDashboard.putData("Auto Mode", autoChooser);
}
@Override
public void autonomous() {
autoMode = (Integer) autoChooser.getSelected();
SmartDashboard.putString("Start Auto", autoModes.get(autoMode));
SmartDashboard.putString("End Auto", "");
double rotate90DegreeTime = .75; // Time it takes to rotate 90 degrees
//pull up 5th wheel
pistonCenterSuspension.set(false);
double moveShort = 1.8;
double moveLong = 2.0;
switch(autoMode){
case autoModeToZoneOver:
case autoModeToZone:{
//move forward
setDriveMotors(.5, .5);
Timer.delay(autoMode == autoModeGrabToZoneOver? moveLong : moveShort); // Time it takes to be enclosed by the Auto Zone
setDriveMotors(0, 0);
Timer.delay(.5);
//rotate right
setDriveMotors(1, -1);
Timer.delay(rotate90DegreeTime);
setDriveMotors(0, 0);
break;
}
case autoModeGrabToZoneOver:
case autoModeGrabToZone: {
//Start with claws open and almost touching can
//close claws
pistonLiftWidth.set(Value.kForward);
Timer.delay(1);
//lift up
motorLift.set(.5);
Timer.delay(1); // Time it takes to lift can
motorLift.set(0);
Timer.delay(.5);
//move backward
setDriveMotors(-.5, -.5);
Timer.delay(autoMode == autoModeGrabToZoneOver? moveLong : moveShort); // Time it takes to be enclosed by the Auto Zone
setDriveMotors(0, 0);
Timer.delay(.5);
//rotate right
setDriveMotors(1, -1);
Timer.delay(rotate90DegreeTime);
setDriveMotors(0, 0);
break;
}
}
SmartDashboard.putString("End Auto", autoModes.get(autoMode));
SmartDashboard.putString("Start Auto", "");
autoMode = autoModeNone;
}
@Override
public void operatorControl() {
/*CameraThread camThread = new CameraThread();
camThread.start();
SmartDashboard.putBoolean("Camera thread working", true);*/
// PIDControllerLift.enable();
while (isOperatorControl() && isEnabled()) {
// SmartDashboard.putBoolean("CameraThread Running",
// camThread.running);
driveControl();
manipulatorControl();
SmartDashboard.putNumber("Total current draw", pdp.getTotalCurrent());
SmartDashboard.putNumber("Voltage", pdp.getVoltage());
Timer.delay(0.005);
}
// PIDControllerLift.disable();
//camThread.finish();
}
@Override
public void test() {
}
public void driveControl() {
SETTING_hDriveDampening = SmartDashboard
.getNumber("hDriveDampening", 5);
double leftSide = -stickLeft.getAxis(AxisType.kY);
double rightSide = -stickRight.getAxis(AxisType.kY);
double h = farthestFrom0(stickLeft.getAxis(AxisType.kX),
stickRight.getAxis(AxisType.kX));
h = deadbandScale(h, .2);
// h /= 2;
if (stickRight.getRawButton(8)) {
setDriveMotors(rightSide, rightSide, 0);
} else {
setDriveMotors(leftSide, rightSide, h);
}
if(stickLeft.getRawButton(1) || stickRight.getRawButton(1)) {
pistonCenterSuspension.set(false);
} else {
pistonCenterSuspension.set(true);
}
double distanceValue = frontDistanceSensor.getValue();
SmartDashboard.putNumber("Front Sensor Distance", distanceValue);
//double rangeTotalInches = sonicVex.getRangeInches();
//int rangePartFeet = (int)(rangeTotalInches / 12);
//int rangePartInches = ((int)rangeTotalInches) % 12;
//SmartDashboard.putString("Vex Range:", rangePartFeet+"' "+rangePartInches+"\"");
//SmartDashboard.putNumber("Vex Range Feet", rangePartFeet);
//SmartDashboard.putNumber("Vex Range Inches", rangePartInches);
}
public void manipulatorControl() {
// Calibration:
SETTING_motorLiftSpeed = ((-stickAux.getAxis(AxisType.kZ)) / 2) + .5;
SmartDashboard.putNumber("motorLiftSpeed (auxStick)",
SETTING_motorLiftSpeed);
SETTING_armLiftSpeed = ((-stickRight.getAxis(AxisType.kZ)) / 2) + .5;
SmartDashboard.putNumber("armLiftSpeed (rightStick)",
SETTING_armLiftSpeed);
SmartDashboard.putNumber("AnalogLift PID (" + analogLift.getChannel()
+ ")", analogLift.pidGet());
// All the digital inputs:
SmartDashboard.putBoolean(
"digitalInLiftTop (" + digitalInLiftTop.getChannel() + ")",
digitalInLiftTop.get());
SmartDashboard.putBoolean(
"digitalInLiftBottom (" + digitalInLiftBottom.getChannel()
+ ")", digitalInLiftBottom.get());
SmartDashboard.putBoolean(
"digitalInArmUp (" + digitalInArmUp.getChannel() + ")",
digitalInArmUp.get());
SmartDashboard.putBoolean(
"digitalInArmDown (" + digitalInArmDown.getChannel() + ")",
digitalInArmDown.get());
// Lift Up/Down
/*
* DISABLED PID if(stickAux.getRawButton(3) &&
* !stickAuxLastButton[3]){//up liftPos ++; }
* if(stickAux.getRawButton(2) && !stickAuxLastButton[2]){//down liftPos
* --; }
*
* if (liftPos > liftPosMax) { liftPos = liftPosMax; } if (liftPos <
* liftPosMin) { liftPos = liftPosMin; }
*
* PIDControllerLift.setSetpoint(liftPosPresets[liftPos]);
*
* if ((digitalInLiftTop.get() && liftPos == liftPosMax) ||
* (digitalInLiftBottom.get() && liftPos == liftPosMin)) {
* motorLift.set(0); }
*/
// Instead of PID
double liftSpeed = 0;
if (stickAux.getRawButton(3) && digitalInLiftTop.get()) {
liftSpeed = SETTING_motorLiftSpeed;
}
if (stickAux.getRawButton(2) && digitalInLiftBottom.get()) {
liftSpeed = -SETTING_motorLiftSpeed;
}
motorLift.set(liftSpeed);
// Arm Up/Down
double armSpeed = stickAux.getAxis(AxisType.kY) * SETTING_armLiftSpeed;
if ((!digitalInArmUp.get() && armSpeed < 0) || (!digitalInArmDown.get()
&& armSpeed > 0)) { armSpeed = 0; }
motorArm.set(armSpeed);
// Lift Width in/out
if (stickAux.getRawButton(4)) { // left out
pistonLiftWidth.set(Value.kForward);
}
if (stickAux.getRawButton(5)) { // right in
pistonLiftWidth.set(Value.kReverse);
}
// arm tilt
// pistonArmTilt1.set(Value.kOff);
// pistonArmTilt2.set(Value.kOff);
if (stickAux.getRawButton(6)) { // tilt forward
pistonArmTilt1.set(Value.kForward);
pistonArmTilt2.set(Value.kForward);
}
if (stickAux.getRawButton(7)) { // tilt backward
pistonArmTilt1.set(Value.kReverse);
pistonArmTilt2.set(Value.kReverse);
}
for (int i = 1; i < stickAuxLastButton.length; i++) {
stickAuxLastButton[i] = stickAux.getRawButton(7);
}
}
double deadbandScale(double input, double threshold) {
return input > threshold ? (input - threshold) / (1 - threshold)
: input < -threshold ? (input + threshold) / (1 - threshold)
: 0;
}
double farthestFrom0(double a, double b) {
return (Math.abs(a) > Math.abs(b)) ? a : b;
}
void setDriveMotors(double left, double right, double middle) {
motorLeft.set(left);
motorRight.set(-right);
motorCenter.set(middle);
}
void setDriveMotors(double left, double right) {
setDriveMotors(left, right, 0);
}
}
|
package org.javarosa.service.transport.securehttp;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.javarosa.core.log.WrappedException;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.transport.payload.IDataPayload;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.services.transport.TransportService;
import org.javarosa.services.transport.impl.BasicTransportMessage;
import org.javarosa.services.transport.impl.TransportMessageStatus;
import org.javarosa.services.transport.impl.simplehttp.HttpRequestProperties;
import de.enough.polish.util.StreamUtil;
/**
* An AuthenticatedHttpTransportMessage is a transport message which is used to
* either perform a GET or POST request to an HTTP server, which includes the
* capacity for authenticating with that server if a WWW-Authenticate challenge
* is issued.
*
* AuthenticatedHttpTransportMessage are currently unable to cache themselves
* natively with the transport service.
*
* @author ctsims
*
*/
public class AuthenticatedHttpTransportMessage extends BasicTransportMessage {
String URL;
HttpAuthenticator authenticator;
int responseCode;
InputStream response;
String authentication;
IDataPayload payload;
private AuthenticatedHttpTransportMessage(String URL, HttpAuthenticator authenticator) {
this.setCreated(new Date());
this.setStatus(TransportMessageStatus.QUEUED);
this.URL = URL;
this.authenticator = authenticator;
}
/**
* Creates a message which will perform an HTTP GET Request to the server referenced at
* the given URL.
*
* @param URL The requested server URL
* @param authenticator An authenticator which is capable of providing credentials upon
* request.
* @return A new authenticated HTTP message ready for sending.
*/
public static AuthenticatedHttpTransportMessage AuthenticatedHttpRequest(String URL, HttpAuthenticator authenticator) {
return new AuthenticatedHttpTransportMessage(URL, authenticator);
}
/**
* Creates a message which will perform an HTTP POST Request to the server referenced at
* the given URL.
*
* @param URL The requested server URL
* @param authenticator An authenticator which is capable of providing credentials upon
* request.
* @param payload A data payload which will be posted to the remote server.
* @return A new authenticated HTTP message ready for sending.
*/
public static AuthenticatedHttpTransportMessage AuthenticatedHttpPOST(String URL, IDataPayload payload, HttpAuthenticator authenticator) {
AuthenticatedHttpTransportMessage message = new AuthenticatedHttpTransportMessage(URL, authenticator);
message.payload = payload;
return message;
}
/**
* @return The HTTP request method (Either GET or POST) for
* this message.
*/
public String getMethod() {
return (payload == null ? HttpConnection.GET : HttpConnection.POST);
}
/**
* @return The HTTP URL of the server for this message
*/
public String getUrl() {
return URL;
}
/* (non-Javadoc)
* @see org.javarosa.services.transport.TransportMessage#isCacheable()
*/
public boolean isCacheable() {
return false;
}
/* (non-Javadoc)
* @see org.javarosa.services.transport.TransportMessage#setCacheIdentifier(java.lang.String)
*/
public void setCacheIdentifier(String id) {
Logger.log("transport", "warn: setting cache ID on non-cacheable message");
//suppress; these messages are not cacheable
}
public void setSendingThreadDeadline(long queuingDeadline) {
Logger.log("transport", "warn: setting cache expiry on non-cacheable message");
//suppress; these messages are not cacheable
}
/**
* @param code The response code of the most recently attempted
* request.
*/
public void setResponseCode(int code) {
this.responseCode = code;
}
/**
* @return code The response code of the most recently attempted
* request.
*/
public int getResponseCode() {
return responseCode;
}
/**
* Sets the stream of the response from a delivery attempt
* @param response The stream provided from the http connection
* from a deliver attempt
*/
protected void setResponseStream(InputStream response) {
this.response = response;
}
/**
* @return The stream provided from the http connection
* from the previous deliver attempt
*/
public InputStream getResponse() {
return response;
}
/**
* @return The properties for this http request (other than
* authorization headers).
*/
public HttpRequestProperties getRequestProperties() {
return new HttpRequestProperties();
}
public InputStream getContentStream() {
if (payload == null) {
return new ByteArrayInputStream("".getBytes());
} else {
return payload.getPayloadStream();
}
}
/*
* (non-Javadoc)
*
* @see org.javarosa.services.transport.Transporter#send()
*/
public void send() {
try {
//Open the connection assuming either cached credentials
//or no Authentication
HttpConnection connection = getConnection();
int response = connection.getResponseCode();
if (response == HttpConnection.HTTP_UNAUTHORIZED) {
String challenge = getChallenge(connection);
//If authentication is needed, issue the challenge
if (this.issueChallenge(connection, challenge)) {
// The challenge was handled, and authentication
// is now provided, try the request again after
//closing the current connection.
connection.close();
connection = getConnection();
//Handle the new response as-is, if authentication failed,
//the sending process can issue a new request.
handleResponse(connection);
} else {
// The challenge couldn't be addressed. Set the message to
// failure.
handleResponse(connection);
}
} else {
//The message did not fail due to authorization problems, so
//handle the response.
handleResponse(connection);
}
} catch (IOException e) {
e.printStackTrace();
this.setStatus(TransportMessageStatus.FAILED);
this.setFailureReason(WrappedException.printException(e));
}
}
private String getChallenge(HttpConnection connection ) throws IOException {
//technically the standard
String challenge = connection.getHeaderField("WWW-Authenticate");
if(challenge == null) {
//j2me sometimes lowercases everything;
System.out.println("lowercase fallback!");
challenge = connection.getHeaderField("www-authenticate");
}
return challenge;
}
/**
* Issues an authentication challenge from the provided HttpConnection
*
* @param connection The connection which issued the challenge
* @param challenge The WWW-Authenticate challenge issued.
* @return True if the challenge was addressed by the message's authenticator,
* and the request should be retried, False if the challenge could not be
* addressed.
*/
public boolean issueChallenge(HttpConnection connection, String challenge) {
authentication = this.authenticator.challenge(connection, challenge, this);
if(authentication == null) {
return false;
} else {
return true;
}
}
/**
* @return the current best-guess authorization header for this message,
* either produced as a response to a WWW-Authenticate challenge, or
* provided by the authentication cache based on previous requests
* (if enabled and relevant in the message's authenticator).
*/
public String getAuthString() {
if(authentication == null) {
//generally pre-challenge
return authenticator.checkCache(this);
}
return authentication;
}
private void handleResponse(HttpConnection connection) throws IOException {
int responseCode = connection.getResponseCode();
long responseLength = connection.getLength();
if (responseLength > TransportService.PAYLOAD_SIZE_REPORTING_THRESHOLD) {
Logger.log("recv", "size " + responseLength);
}
if(responseCode >= 200 && responseCode < 300) {
//It's all good, message was a success.
this.setResponseCode(responseCode);
this.setStatus(TransportMessageStatus.SENT);
//Wire up the input stream from the connection to the message.
this.setResponseStream(new InputStreamC(connection.openInputStream(), responseLength, this.getTag()));
} else {
this.setStatus(TransportMessageStatus.FAILED);
this.setResponseCode(responseCode);
//We'll assume that any failures come with a message which is sufficiently
//small that they can be fit into memory.
byte[] response = StreamUtil.readFully(connection.openInputStream());
String reason = responseCode + ": " + new String(response);
reason = PropertyUtils.trim(reason, 400);
this.setFailureReason(reason);
}
}
/**
*
* @return
* @throws IOException
*/
private HttpConnection getConnection() throws IOException {
HttpConnection conn = (HttpConnection) Connector.open(this.getUrl());
if (conn == null)
throw new RuntimeException("Null conn in getConnection()");
HttpRequestProperties requestProps = this.getRequestProperties();
if (requestProps == null) {
throw new RuntimeException("Null message.getRequestProperties() in getConnection()");
}
conn.setRequestMethod(this.getMethod());
conn.setRequestProperty("User-Agent", requestProps.getUserAgent());
conn.setRequestProperty("Content-Language", requestProps.getContentLanguage());
conn.setRequestProperty("MIME-version", requestProps.getMimeVersion());
conn.setRequestProperty("Content-Type", requestProps.getContentType());
//Retrieve either the response auth header, or the cached guess
String authorization = this.getAuthString();
if(authorization != null) {
conn.setRequestProperty("Authorization", authorization);
}
// any others
Enumeration keys = requestProps.getOtherProperties().keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = (String) requestProps.getOtherProperties().get(key);
conn.setRequestProperty(key, value);
}
return conn;
}
protected class InputStreamC extends InputStream {
private InputStream is;
private long total;
private long read;
private String tag;
boolean logged = false;
public InputStreamC (InputStream is, long totalLength, String tag) {
this.is = is;
this.total = totalLength;
this.read = 0;
this.tag = tag;
}
public int read() throws IOException {
try {
int c = is.read();
read += 1;
return c;
} catch (IOException ioe) {
log(true);
throw ioe;
}
}
public int read(byte[] b) throws IOException {
try {
int k = is.read(b);
read += Math.max(k, 0);
return k;
} catch (IOException ioe) {
log(true);
throw ioe;
}
}
public int read(byte[] b, int off, int len) throws IOException {
try {
int k = is.read(b, off, len);
read += Math.max(k, 0);
return k;
} catch (IOException ioe) {
log(true);
throw ioe;
}
}
public long skip(long n) throws IOException {
try {
long k = is.skip(n);
read += k;
return k;
} catch (IOException ioe) {
log(true);
throw ioe;
}
}
public void close() throws IOException {
log(false);
is.close();
}
private void log (boolean ex) {
if (logged)
return;
logged = true;
try {
boolean hasLength = (total >= 0); //whether we have total length
boolean diff; //whether bytes read differed from total length
boolean logIt; //whether to log stats
if (hasLength) {
diff = (total != read);
logIt = diff;
} else {
logIt = (read > TransportService.PAYLOAD_SIZE_REPORTING_THRESHOLD || ex);
diff = false;
}
if (logIt) {
Logger.log("recv", "<" + tag + "> " + read + (diff ? " of " + total : ""));
}
} catch (Exception e) {
//extrasafe
Logger.exception("InputStreamC.log", e);
}
}
public int available() throws IOException {
System.err.println("don't expect this to ever be called");
return is.available();
}
public void mark(int rl) {
System.err.println("don't expect this to ever be called");
is.mark(rl);
}
public void reset() throws IOException {
System.err.println("don't expect this to ever be called");
is.reset();
}
public boolean markSupported() {
System.err.println("don't expect this to ever be called");
return is.markSupported();
}
}
/* (non-Javadoc)
* @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory)
*/
public void readExternal(DataInputStream in, PrototypeFactory pf)
throws IOException, DeserializationException {
//doesn't cache;
}
/* (non-Javadoc)
* @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream)
*/
public void writeExternal(DataOutputStream out) throws IOException {
//doesn't cache;
}
}
|
package org.usfirst.frc.team5275.robot;
import org.usfirst.frc.team5275.robot.commands.*;
import org.usfirst.frc.team5275.robot.subsystems.DriveTrain;
import org.usfirst.frc.team5275.robot.subsystems.ExampleSubsystem;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
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.
*/
//on eclipse linux this line will throw an error, however, the project seems to build just fine.
// it's safe to ignore this error, as eclipse for linux seems to handle a few things differently
//than the windows version does.
public class Robot extends IterativeRobot {
public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
public static OI oi;
Command autonomousCommand;
public Command teleopCommand = new teleop();
SendableChooser chooser;
public static DriveTrain drive = new DriveTrain();
public static RobotDrive rd = new RobotDrive(1,2,3,4);
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
oi = new OI();
chooser = new SendableChooser();
chooser.addDefault("Default Auto", new ExampleCommand());
chooser.addObject("teleop", new teleop());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
autonomousCommand = (Command) chooser.getSelected();
/* String autoSelected = SmartDashboard.getString("Auto Selector", "Default");
switch(autoSelected) {
case "My Auto":
autonomousCommand = new MyAutoCommand();
break;
case "Default Auto":
default:
autonomousCommand = new ExampleCommand();
break;
} */
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
|
package org.frc1675.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.frc1675.OI;
import org.frc1675.subsystems.Jaw;
import org.frc1675.subsystems.Puncher;
import org.frc1675.subsystems.Roller;
import org.frc1675.subsystems.Shoulder;
/**
* The base for all commands. All atomic commands should subclass CommandBase.
* CommandBase stores creates and stores each control system. To access a
* subsystem elsewhere in your code in your code use CommandBase.exampleSubsystem
* @author Author
*/
public abstract class CommandBase extends Command {
public static OI oi;
// Create a single static instance of all of the subsystems
public static Jaw jaw = new Jaw();
public static Puncher puncher = new Puncher();
public static Roller rollerClaw = new Roller();
public static Shoulder shoulder = new Shoulder();
public static void init() {
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
}
public CommandBase(String name) {
super(name);
}
public CommandBase() {
super();
}
}
|
package nl.tudelft.lifetiles.tree.view;
import javafx.geometry.Point2D;
import javafx.scene.control.Tooltip;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcTo;
import javafx.scene.shape.FillRule;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Shape;
import nl.tudelft.lifetiles.sequence.SequenceColor;
import nl.tudelft.lifetiles.sequence.model.Sequence;
import nl.tudelft.lifetiles.tree.model.PhylogeneticTreeItem;
/**
* A {@link SunburstRingSegment} represents a segment of the sunburst diagrams
* rings.
*
* @author Albert Smit
*
*/
public class SunburstRingSegment extends AbstractSunburstNode {
/**
* the max brightness for the color of a Node.
*/
private static final double MAX_BRIGHTNESS = 0.8;
/**
* The default saturation of the color of a Node.
*/
private static final double SATURATION = 0.9;
/**
* Creates a SunburstRingSegment.
*
*
* @param value
* the {@link PhylogeneticTreeItem} this part of the ring will
* represent
* @param layer
* the layer at which it is located in the tree, layer 0 is the
* first layer
* @param degreeStart
* the start position in degrees
* @param degreeEnd
* the end position in degrees
* @param center
* the coordinates of the center of the circle
* @param scale
* the scaling factor
*/
public SunburstRingSegment(final PhylogeneticTreeItem value,
final int layer, final double degreeStart, final double degreeEnd,
final Point2D center, final double scale) {
// set the value, and create the text and semi-circle
setValue(value);
String name = getValue().getName();
setDisplay(createRing(layer, degreeStart, degreeEnd, center, scale));
double distance = getValue().getDistance();
String tooltip;
if (name == null) {
tooltip = "Distance: " + distance;
} else {
tooltip = name + "\nDistance: " + distance;
}
setName(new Tooltip(tooltip));
// add the text and semicircle to the group
getChildren().add(getDisplay());
}
/**
* Creates a semi-circle with in the specified location.
*
* layer starts at 0
*
* @param layer
* The layer to place this element at, the first child of root is
* layer 0.
* @param degreeStart
* the start position in degrees
* @param degreeEnd
* the end position in degrees
* @param center
* the coordinates of the center of the circle
* @param scale
* the scaling factor
* @return a semi-circle with the specified dimensions
*/
private Shape createRing(final int layer, final double degreeStart,
final double degreeEnd, final Point2D center, final double scale) {
Path result = new Path();
result.setFill(createColor(degreeStart, layer));
result.setFillRule(FillRule.EVEN_ODD);
// check if this is a large arc
double arcSize = AbstractSunburstNode.calculateAngle(degreeStart,
degreeEnd);
boolean largeArc = arcSize > AbstractSunburstNode.CIRCLEDEGREES / 2;
// calculate the radii of the two arcs
double innerRadius = scale * (CENTER_RADIUS + (layer * RING_WIDTH));
double outerRadius = innerRadius + scale * RING_WIDTH;
// convert degrees to radians for Math.sin and Math.cos
double angleAlpha = Math.toRadians(degreeStart);
double angleAlphaNext = Math.toRadians(degreeEnd);
// draw the semi-circle
// first go to the start point
double startX = center.getX() + innerRadius * Math.sin(angleAlpha);
double startY = center.getY() - innerRadius * Math.cos(angleAlpha);
MoveTo move1 = new MoveTo(startX, startY);
// draw a line from point 1 to point 2
LineTo line1To2 = createLine(outerRadius, center, angleAlpha);
// draw an arc from point 2 to point 3
ArcTo arc2To3 = createArc(outerRadius, center, angleAlphaNext, true,
largeArc);
// draw a line from point 3 to point 4
LineTo line3To4 = createLine(innerRadius, center, angleAlphaNext);
// draw an arc from point 4 back to point 1
ArcTo arc4To1 = createArc(innerRadius, center, angleAlpha, false,
largeArc);
// add all elements to the path
result.getElements()
.addAll(move1, line1To2, arc2To3, line3To4, arc4To1);
return result;
}
/**
* Creates an {@link ArcTo} with the specified parameters.
*
* Coordinates of the end point of the arc are given in polar form relative
* to the center of the arcs.
*
* @param radius
* The radius of the arc.
* @param center
* The center coordinates of the arc.
* @param angle
* The angle of the end point.
* @param sweep
* The draw direction of the arc.
* @param largeArc
* if true draw an arc larger than 180 degrees.
* @return an ArcTo with the specified parameters.
*/
private ArcTo createArc(final double radius, final Point2D center,
final double angle, final boolean sweep, final boolean largeArc) {
// calculate the end point of the arc
double endX = center.getX() + radius * Math.sin(angle);
double endY = center.getY() - radius * Math.cos(angle);
// create the arc
ArcTo result = new ArcTo();
result.setRadiusX(radius);
result.setRadiusY(radius);
result.setX(endX);
result.setY(endY);
result.setSweepFlag(sweep);
result.setLargeArcFlag(largeArc);
return result;
}
/**
* Creates a {@link LineTo} with the specified parameters.
*
* Coordinates of the end point of the arc are given in polar form relative
* to the center of the arcs.
*
* @param radius
* The radius of the arc.
* @param center
* The center coordinates of the arc.
* @param angle
* The angle of the end point.
* @return the LineTo with the specified parameters.
*/
private LineTo createLine(final double radius, final Point2D center,
final double angle) {
// calculate the end point coordinates
double endX = center.getX() + radius * Math.sin(angle);
double endY = center.getY() - radius * Math.cos(angle);
return new LineTo(endX, endY);
}
/**
* Creates a {@link Color} for this node. the color will be red by default,
* and the color associated with the sequence when the node has a sequence.
*
* @param degrees
* the location where the ringSeqment is drawn, will become the
* hue of the color.
* @param layer
* the layer where the ringSegment is drawn, is used for the
* brightness
* @return a Color object that specifies what color this node will be.
*/
private Color createColor(final double degrees, final int layer) {
Sequence sequence = getValue().getSequence();
if (sequence == null) {
double brightness = Math.min(MAX_BRIGHTNESS, 1d / layer);
brightness = Math.abs(brightness - 1);
return Color.hsb(degrees, SATURATION, brightness);
} else {
return SequenceColor.getColor(sequence);
}
}
}
|
package picoded.JSql.struct;
import java.util.*;
import java.util.logging.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import picoded.struct.*;
import picoded.enums.JSqlType;
import picoded.JSql.*;
import picoded.conv.*;
import picoded.JStruct.*;
import picoded.JStruct.internal.*;
import picoded.security.NxtCrypt;
import org.apache.commons.lang3.RandomUtils;
/// JSql implmentation of KeyValueMap
public class JSql_KeyValueMap extends JStruct_KeyValueMap {
/// Temporary logger used to make sure incomplete implmentation is noted
/// Standard java logger
public static Logger logger = Logger.getLogger(JSql_KeyValueMap.class.getName());
/// Constructor setup
/// The inner sql object
public JSql sqlObj = null;
/// The tablename for the key value pair map
public String sqlTableName = null;
/// JSql setup
public JSql_KeyValueMap(JSql inJSql, String tablename) {
super();
sqlObj = inJSql;
sqlTableName = tablename;
}
/// Internal config vars
/// Primary key type
public String pKeyColumnType = "BIGINT PRIMARY KEY AUTOINCREMENT";
/// Timestamp field type
public String tStampColumnType = "BIGINT";
/// Key name field type
public String keyColumnType = "VARCHAR(64)";
/// Value field type
public String valueColumnType = "VARCHAR(MAX)";
/// Backend system setup / teardown
/// Setsup the backend storage table, etc. If needed
public void systemSetup() {
try {
// Table constructor
sqlObj.createTableQuerySet(
sqlTableName,
new String[] {
// Primary key, as classic int, this is used to lower SQL
// fragmentation level, and index memory usage. And is not accessible.
// Sharding and uniqueness of system is still maintained by meta keys
"pKy",
// Time stamps
"cTm", //value created time
"eTm", //value expire time
// Storage keys
"kID",
// Value storage
"kVl"
},
new String[] {
pKeyColumnType, //Primary key
// Time stamps
tStampColumnType, tStampColumnType,
// Storage keys
keyColumnType,
// Value storage
valueColumnType }
).execute();
// Unique index
sqlObj.createTableIndexQuerySet(
sqlTableName, "kID", "UNIQUE", "unq"
).execute();
// Value search index
if( sqlObj.sqlType == JSqlType.mysql ) {
sqlObj.createTableIndexQuerySet(
sqlTableName, "kVl(255)", null, "valMap"
).execute();
} else {
sqlObj.createTableIndexQuerySet(
sqlTableName, "kVl", null, "valMap"
).execute();
}
} catch (JSqlException e) {
throw new RuntimeException(e);
}
}
/// Teardown and delete the backend storage table, etc. If needed
/// @TODO properly handle this: Especially adding (and testing) the IF EXISTS clause
public void systemTeardown() {
try {
sqlObj.execute("DROP TABLE IF EXISTS " + sqlTableName); //IF EXISTS
} catch (JSqlException e) {
logger.log(Level.SEVERE, "systemTeardown JSqlException (@TODO properly handle this): ", e);
}
}
/// Perform maintenance, mainly removing of expired data if applicable
public void maintenance() {
try {
long now = currentSystemTimeInSeconds();
sqlObj.execute("DELETE FROM `" + sqlTableName + "` WHERE eTm <= ?", now);
} catch (JSqlException e) {
throw new RuntimeException(e);
}
}
/// Expiration and lifespan handling (to override)
/// Gets the expire time from the JSqlResult
public long getExpiryRaw(JSqlResult r) throws JSqlException {
// Search for the key
Object rawTime = null;
// Has value
if (r != null && r.rowCount() > 0) {
rawTime = r.get("eTm").get(0);
} else {
return -1; //No value (-1)
}
long ret = 0;
if (rawTime != null) {
if (rawTime instanceof Number) {
ret = ((Number) rawTime).longValue();
} else {
ret = (Long.parseLong(rawTime.toString()));
}
}
if (ret <= 0) {
return 0;
} else {
return ret;
}
}
/// [Internal use, to be extended in future implementation]
/// Returns the expire time stamp value, raw without validation
/// Handles re-entrant lock where applicable
/// @param key as String
/// @returns long
public long getExpiryRaw(String key) {
try {
// Search for the key
JSqlResult r = sqlObj.selectQuerySet(sqlTableName, "eTm", "kID=?", new Object[] { key }).query();
return getExpiryRaw(r);
} catch (JSqlException e) {
throw new RuntimeException(e);
}
}
/// [Internal use, to be extended in future implementation]
/// Sets the expire time stamp value, raw without validation
/// Handles re-entrant lock where applicable
/// @param key as String
/// @returns long
public void setExpiryRaw(String key, long time) {
try {
sqlObj.execute("UPDATE " + sqlTableName + " SET eTm=? WHERE kID = ?", time, key);
} catch (JSqlException e) {
throw new RuntimeException(e);
}
return;
}
/// put, get, etc (to override)
/// [Internal use, to be extended in future implementation]
/// Returns the value, with validation
/// Handles re-entrant lock where applicable
/// @param key as String
/// @param now timestamp
/// @returns String value
public String getValueRaw(String key, long now) {
try {
// Search for the key
JSqlResult r = sqlObj.selectQuerySet(sqlTableName, "*", "kID=?", new Object[] { key }).query();
long expiry = getExpiryRaw(r);
if (expiry != 0 && expiry < now) {
return null;
}
return r.get("kVl").get(0).toString();
} catch (JSqlException e) {
throw new RuntimeException(e);
}
}
/// [Internal use, to be extended in future implementation]
/// Sets the value, with validation
/// Handles re-entrant lock where applicable
/// @param key
/// @param value, null means removal
/// @param expire timestamp in seconds, 0 means NO expire
/// @returns null
public String setValueRaw(String key, String value, long expire) {
try {
long now = currentSystemTimeInSeconds();
sqlObj.upsertQuerySet(
sqlTableName,
new String[] { "kID" }, //unique cols
new Object[] { key }, //unique value
new String[] { "cTm", "eTm", "kVl" }, //insert cols
new Object[] { now, expire, value } //insert values
).execute();
} catch (JSqlException e) {
throw new RuntimeException(e);
}
return null;
}
/// Search using the value, all the relevent key mappings
/// Handles re-entrant lock where applicable
/// @param key, note that null matches ALL
/// @returns array of keys
public Set<String> getKeys(String value) {
try {
long now = currentSystemTimeInSeconds();
JSqlResult r = null;
if (value == null) {
r = sqlObj.selectQuerySet(sqlTableName, "kID", "eTm <= ? OR eTm > ?", new Object[] { 0, now }).query();
} else {
r = sqlObj.selectQuerySet(sqlTableName, "kID", "kVl = ? AND (eTm <= ? OR eTm > ?)",
new Object[] { value, 0, now }).query();
}
if (r == null || r.get("kID") == null) {
return new HashSet<String>();
}
return ListValueConv.toStringSet(r.get("kID"));
} catch (JSqlException e) {
throw new RuntimeException(e);
}
}
/// Returns all the valid keys
/// @returns the full keyset
public Set<String> keySet() {
return getKeys(null);
}
/// Remove the value, given the key
/// @param key param find the thae meta key
/// @returns null
public String remove(Object key) {
try {
String keyName = key.toString();
sqlObj.execute("DELETE FROM `" + sqlTableName + "` WHERE kID = ?", keyName);
} catch (JSqlException e) {
throw new RuntimeException(e);
}
return null;
}
}
|
// $Id: RpcDispatcher.java,v 1.2 2003/10/27 06:06:06 belaban Exp $
package org.jgroups.blocks;
import java.io.Serializable;
import java.util.Vector;
import org.jgroups.*;
import org.jgroups.util.*;
import org.jgroups.log.Trace;
/**
* Dispatches and receives remote group method calls. Is the equivalent of RpcProtocol
* on the application rather than protocol level.
* @author Bela Ban
*/
public class RpcDispatcher extends MessageDispatcher implements ChannelListener {
MethodLookup method_lookup=new MethodLookupClos();
protected Object server_obj=null;
protected Marshaller marshaller=null;
public RpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj) {
super(channel, l, l2);
channel.setChannelListener(this);
this.server_obj=server_obj;
}
public RpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj,
boolean deadlock_detection) {
super(channel, l, l2, deadlock_detection);
channel.setChannelListener(this);
this.server_obj=server_obj;
}
public RpcDispatcher(PullPushAdapter adapter, Serializable id,
MessageListener l, MembershipListener l2, Object server_obj) {
super(adapter, id, l, l2);
// Fixes bug #804956
// channel.setChannelListener(this);
if(this.adapter != null) {
Transport t=this.adapter.getTransport();
if(t != null && t instanceof Channel) {
((Channel)t).setChannelListener(this);
}
}
this.server_obj=server_obj;
}
public interface Marshaller {
byte[] objectToByteBuffer(Object obj) throws Exception;
Object objectFromByteBuffer(byte[] buf) throws Exception;
}
public String getName() {return "RpcDispatcher";}
public MethodLookup getMethodLookup() {return method_lookup;}
public void setMethodLookup(MethodLookup method_lookup) {
this.method_lookup=method_lookup;
}
public void setMarshaller(Marshaller m) {this.marshaller=m;}
public Marshaller getMarshaller() {return marshaller;}
public RspList castMessage(Vector dests, Message msg, int mode, long timeout) {
Trace.error("RpcDispatcher.castMessage()", "this method should not be used with " +
"RpcDispatcher, but MessageDispatcher. Returning null");
return null;
}
public Object sendMessage(Message msg, int mode, long timeout) throws TimeoutException, SuspectedException {
Trace.error("RpcDispatcher.sendMessage()", "this method should not be used with " +
"RpcDispatcher, but MessageDispatcher. Returning null");
return null;
}
/**
* @deprecated use callRemoteMethods(Vector,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public RspList callRemoteMethods(Vector dests, String method_name, int mode, long timeout) {
MethodCall method_call=new MethodCall(method_name);
return callRemoteMethods(dests, method_call, mode, timeout);
}
/**
* @deprecated use callRemoteMethods(Vector,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public RspList callRemoteMethods(Vector dests, String method_name, Object arg1,
int mode, long timeout) {
MethodCall method_call=new MethodCall(method_name, arg1);
return callRemoteMethods(dests, method_call, mode, timeout);
}
/**
* @deprecated use callRemoteMethods(Vector,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public RspList callRemoteMethods(Vector dests, String method_name, Object arg1, Object arg2,
int mode, long timeout) {
MethodCall method_call=new MethodCall(method_name, arg1, arg2);
return callRemoteMethods(dests, method_call, mode, timeout);
}
/**
* @deprecated use callRemoteMethods(Vector,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public RspList callRemoteMethods(Vector dests, String method_name, Object arg1, Object arg2,
Object arg3, int mode, long timeout) {
MethodCall method_call=new MethodCall(method_name, arg1, arg2, arg3);
return callRemoteMethods(dests, method_call, mode, timeout);
}
public RspList callRemoteMethods(Vector dests, String method_name, Object[] args,
Class[] types, int mode, long timeout) {
MethodCall method_call=new MethodCall(method_name, args, types);
return callRemoteMethods(dests, method_call, mode, timeout);
}
public RspList callRemoteMethods(Vector dests, String method_name, Object[] args,
String[] signature, int mode, long timeout) {
MethodCall method_call=new MethodCall(method_name, args, signature);
return callRemoteMethods(dests, method_call, mode, timeout);
}
public RspList callRemoteMethods(Vector dests, MethodCall method_call, int mode, long timeout) {
byte[] buf=null;
Message msg=null;
try {
buf=marshaller != null? marshaller.objectToByteBuffer(method_call) : Util.objectToByteBuffer(method_call);
}
catch(Exception e) {
Trace.error("RpcProtocol.callRemoteMethods()", "exception=" + e);
return null;
}
msg=new Message(null, null, buf);
return super.castMessage(dests, msg, mode, timeout);
}
/**
* Calls the remote methods in a number of receivers and returns the results asynchronously via
* the RspCollector interface.
* @param dests The destination membership. All members if null
* @param req_id The request id. Used to match requests and responses. has to be unique for this process
* @param method_call The method to be called
* @param coll The RspCollector to be called when a message arrives
*/
// public void callRemoteMethods(Vector dests, long req_id, MethodCall method_call, RspCollector coll) {
// byte[] buf=null;
// Message msg=null;
// try {
// buf=marshaller != null? marshaller.objectToByteBuffer(method_call) : Util.objectToByteBuffer(method_call);
// catch(Exception e) {
// Trace.error("RpcProtocol.callRemoteMethods()", "exception=" + e);
// return;
// msg=new Message(null, null, buf);
// super.castMessage(dests, req_id, msg, coll);
/**
* @deprecated use callRemoteMethod(Address,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public Object callRemoteMethod(Address dest, String method_name, int mode, long timeout)
throws TimeoutException, SuspectedException {
MethodCall method_call=new MethodCall(method_name);
return callRemoteMethod(dest, method_call, mode, timeout);
}
/**
* @deprecated use callRemoteMethod(Address,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public Object callRemoteMethod(Address dest, String method_name, Object arg1, int mode, long timeout)
throws TimeoutException, SuspectedException {
MethodCall method_call=new MethodCall(method_name, arg1);
return callRemoteMethod(dest, method_call, mode, timeout);
}
/**
* @deprecated use callRemoteMethod(Address,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public Object callRemoteMethod(Address dest, String method_name, Object arg1, Object arg2,
int mode, long timeout) throws TimeoutException, SuspectedException {
MethodCall method_call=new MethodCall(method_name, arg1, arg2);
return callRemoteMethod(dest, method_call, mode, timeout);
}
/**
* @deprecated use callRemoteMethod(Address,MethodCall, int, long);
* @see #callRemoteMethod(Address,MethodCall, int, long)
*/
public Object callRemoteMethod(Address dest, String method_name, Object arg1, Object arg2,
Object arg3, int mode, long timeout) throws TimeoutException, SuspectedException {
MethodCall method_call=new MethodCall(method_name, arg1, arg2, arg3);
return callRemoteMethod(dest, method_call, mode, timeout);
}
public Object callRemoteMethod(Address dest, String method_name, Object[] args,
Class[] types, int mode, long timeout)
throws TimeoutException, SuspectedException {
MethodCall method_call=new MethodCall(method_name, args, types);
return callRemoteMethod(dest, method_call, mode, timeout);
}
public Object callRemoteMethod(Address dest, String method_name, Object[] args,
String[] signature, int mode, long timeout)
throws TimeoutException, SuspectedException {
MethodCall method_call=new MethodCall(method_name, args, signature);
return callRemoteMethod(dest, method_call, mode, timeout);
}
public Object callRemoteMethod(Address dest, MethodCall method_call, int mode, long timeout)
throws TimeoutException, SuspectedException {
byte[] buf=null;
Message msg=null;
try {
buf=marshaller != null? marshaller.objectToByteBuffer(method_call) : Util.objectToByteBuffer(method_call);
}
catch(Exception e) {
Trace.error("RpcProtocol.callRemoteMethod()", "exception=" + e);
return null;
}
msg=new Message(dest, null, buf);
return super.sendMessage(msg, mode, timeout);
}
/**
* Message contains MethodCall. Execute it against *this* object and return result.
* Use MethodCall.invoke() to do this. Return result.
*/
public Object handle(Message req) {
Object body=null;
MethodCall method_call;
if(server_obj == null) {
Trace.error("RpcDispatcher.handle()", "no method handler is registered. Discarding request.");
return null;
}
if(req == null || req.getBuffer() == null) {
Trace.error("RpcProtocol.handle()", "message or message buffer is null");
return null;
}
try {
body=marshaller != null? marshaller.objectFromByteBuffer(req.getBuffer()) :
Util.objectFromByteBuffer(req.getBuffer());
}
catch(Exception e) {
Trace.error("RpcDispatcher.handle()", "exception=" + e);
return e;
}
if(body == null || !(body instanceof MethodCall)) {
Trace.error("RpcDispatcher.handle()", "message does not contain a MethodCall object");
return null;
}
method_call=(MethodCall)body;
try {
return method_call.invoke(server_obj, method_lookup);
}
catch(Throwable x) {
Trace.error("RpcDispatcher.handle()", Trace.getStackTrace(x));
return x;
}
}
public void channelConnected(Channel channel) {
start();
}
public void channelDisconnected(Channel channel) {
stop();
}
public void channelClosed(Channel channel) {
stop();
}
public void channelShunned() {
}
public void channelReconnected(Address new_addr) {
}
}
|
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public static int buildNumber = 403;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
|
package org.javarosa.services.transport.download;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.javarosa.services.transport.impl.TransportMessageStatus;
import org.javarosa.services.transport.listeners.IGetTransportMessage;
import org.javarosa.services.transport.listeners.IGetTransporter;
import org.javarosa.services.transport.util.StreamsUtil;
public class HttpGetTransporter implements IGetTransporter {
private Date downloadWatchDate;
private HttpGetTransportMessage message;
public HttpGetTransporter() {
}
public IGetTransportMessage get() {
byte[] data = null;
HttpConnection conn = null;
try{
conn = getConnection(message.geDestinationURL());
if(conn.getResponseCode() == HttpConnection.HTTP_OK){
data = readFromConnection(conn);
message = setMessageDetail(message, data);
}
conn.close();
}catch(Exception e){
System.out.println("Connection to the server has failed: " + e.getMessage());
message.setFailureReason(e.getMessage());
}
finally{
if(conn != null)
try{
conn.close();
}
catch(IOException e){
e.printStackTrace();
}
}
return message;
}
private HttpGetTransportMessage setMessageDetail(HttpGetTransportMessage message, byte[] data) {
HttpGetTransportMessage downloadedMessage = message;
downloadedMessage.setReturnedContent(data);
downloadedMessage.setDownloadedDate(downloadWatchDate.getTime());
downloadedMessage.setStatus(TransportMessageStatus.DOWNLOADED);
return downloadedMessage;
}
private byte[] readFromConnection(HttpConnection conn) throws Exception {
byte[] data = null;
DataInputStream in = null;
try{
in = conn.openDataInputStream();
System.out.println("Reading from URL: " + conn.getURL());
data = StreamsUtil.readFromStream(in);
}
catch(Exception e){
e.printStackTrace();
throw e;
}
finally{
if(in != null){
in.close();
}
}
return data;
}
private HttpConnection getConnection(String url) throws IOException {
HttpConnection conn;
Object o = Connector.open(url);
if (o instanceof HttpConnection) {
conn = (HttpConnection) o;
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("MIME-version", "1.0");
conn.setRequestProperty("Content-Type", "text/plain");
} else {
throw new IllegalArgumentException("Not HTTP URL:" + url);
}
return conn;
}
}
|
// $Id: RpcDispatcher.java,v 1.49 2010/03/26 12:48:05 belaban Exp $
package org.jgroups.blocks;
import org.jgroups.*;
import org.jgroups.util.*;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
/**
* This class allows a programmer to invoke remote methods in all (or single)
* group members and optionally wait for the return value(s).
* An application will typically create a channel and layer the
* RpcDispatcher building block on top of it, which allows it to
* dispatch remote methods (client role) and at the same time be
* called by other members (server role).
* This class is derived from MessageDispatcher.
* Is the equivalent of RpcProtocol on the application rather than protocol level.
* @author Bela Ban
*/
public class RpcDispatcher extends MessageDispatcher implements ChannelListener {
protected Object server_obj=null;
/** Marshaller to marshall requests at the caller and unmarshal requests at the receiver(s) */
protected Marshaller2 req_marshaller=null;
/** Marshaller to marshal responses at the receiver(s) and unmarshal responses at the caller */
protected Marshaller2 rsp_marshaller=null;
protected final List<ChannelListener> additionalChannelListeners=new ArrayList<ChannelListener>();
protected MethodLookup method_lookup=null;
public RpcDispatcher() {
}
public RpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj) {
super(channel, l, l2);
channel.addChannelListener(this);
this.server_obj=server_obj;
}
@Deprecated
public RpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj,
boolean deadlock_detection) {
super(channel, l, l2);
channel.addChannelListener(this);
this.server_obj=server_obj;
}
@Deprecated
public RpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj,
boolean deadlock_detection, boolean concurrent_processing) {
super(channel, l, l2, false, concurrent_processing);
channel.addChannelListener(this);
this.server_obj=server_obj;
}
@Deprecated
public RpcDispatcher(PullPushAdapter adapter, Serializable id,
MessageListener l, MembershipListener l2, Object server_obj) {
super(adapter, id, l, l2);
// Fixes bug #804956
// channel.setChannelListener(this);
if(this.adapter != null) {
Transport t=this.adapter.getTransport();
if(t != null && t instanceof Channel) {
((Channel)t).addChannelListener(this);
}
}
this.server_obj=server_obj;
}
public interface Marshaller {
byte[] objectToByteBuffer(Object obj) throws Exception;
Object objectFromByteBuffer(byte[] buf) throws Exception;
}
public interface Marshaller2 extends Marshaller {
/**
* Marshals the object into a byte[] buffer and returns a Buffer with a ref to the underlying byte[] buffer,
* offset and length.<br/>
* <em>
* Note that the underlying byte[] buffer must not be changed as this would change the buffer of a message which
* potentially can get retransmitted, and such a retransmission would then carry a ref to a changed byte[] buffer !
* </em>
* @param obj
* @return
* @throws Exception
*/
Buffer objectToBuffer(Object obj) throws Exception;
Object objectFromByteBuffer(byte[] buf, int offset, int length) throws Exception;
}
/** Used to provide a Marshaller2 interface to a Marshaller. This class is for internal use only, and will be
* removed in 3.0 when Marshaller and Marshaller2 get merged. Do not use, but provide an implementation of
* Marshaller directly, e.g. in setRequestMarshaller().
*/
public static class MarshallerAdapter implements Marshaller2 {
private final Marshaller marshaller;
public MarshallerAdapter(Marshaller marshaller) {
this.marshaller=marshaller;
}
public byte[] objectToByteBuffer(Object obj) throws Exception {
return marshaller.objectToByteBuffer(obj);
}
public Object objectFromByteBuffer(byte[] buf) throws Exception {
return buf == null? null : marshaller.objectFromByteBuffer(buf);
}
public Buffer objectToBuffer(Object obj) throws Exception {
byte[] buf=marshaller.objectToByteBuffer(obj);
return new Buffer(buf, 0, buf.length);
}
public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws Exception {
if(buf == null || (offset == 0 && length == buf.length))
return marshaller.objectFromByteBuffer(buf);
byte[] tmp=new byte[length];
System.arraycopy(buf, offset, tmp, 0, length);
return marshaller.objectFromByteBuffer(tmp);
}
}
public static String getName() {return "RpcDispatcher";}
public Marshaller getRequestMarshaller() {return req_marshaller;}
public void setRequestMarshaller(Marshaller m) {
if(m == null)
this.req_marshaller=null;
else if(m instanceof Marshaller2)
this.req_marshaller=(Marshaller2)m;
else
this.req_marshaller=new MarshallerAdapter(m);
}
public Marshaller getResponseMarshaller() {return rsp_marshaller;}
public void setResponseMarshaller(Marshaller m) {
if(m == null)
this.rsp_marshaller=null;
else if(m instanceof Marshaller2)
this.rsp_marshaller=(Marshaller2)m;
else
this.rsp_marshaller=new MarshallerAdapter(m);
if(corr != null)
corr.setMarshaller(this.rsp_marshaller);
}
public Marshaller getMarshaller() {return req_marshaller;}
public void setMarshaller(Marshaller m) {setRequestMarshaller(m);}
public Object getServerObject() {return server_obj;}
public void setServerObject(Object server_obj) {
this.server_obj=server_obj;
}
public MethodLookup getMethodLookup() {
return method_lookup;
}
public void setMethodLookup(MethodLookup method_lookup) {
this.method_lookup=method_lookup;
}
@Deprecated
public RspList callRemoteMethods(Vector<Address> dests, String method_name, Object[] args,
Class[] types, int mode, long timeout) {
return callRemoteMethods(dests, method_name, args, types, mode, timeout, false);
}
@Deprecated
public RspList callRemoteMethods(Vector<Address> dests, String method_name, Object[] args,
Class[] types, int mode, long timeout, boolean use_anycasting) {
return callRemoteMethods(dests, method_name, args, types, mode, timeout, use_anycasting, null);
}
@Deprecated
public RspList callRemoteMethods(Vector<Address> dests, String method_name, Object[] args,
Class[] types, int mode, long timeout, boolean use_anycasting, RspFilter filter) {
MethodCall method_call=new MethodCall(method_name, args, types);
return callRemoteMethods(dests, method_call,
new RequestOptions(mode, timeout, use_anycasting, filter, (byte)0));
}
public RspList callRemoteMethods(Collection<Address> dests, String method_name, Object[] args,
Class[] types, RequestOptions options) {
MethodCall method_call=new MethodCall(method_name, args, types);
return callRemoteMethods(dests, method_call, options);
}
@Deprecated
public RspList callRemoteMethods(Vector<Address> dests, String method_name, Object[] args,
String[] signature, int mode, long timeout) {
return callRemoteMethods(dests, method_name, args, signature, mode, timeout, false);
}
@Deprecated
public RspList callRemoteMethods(Vector<Address> dests, String method_name, Object[] args,
String[] signature, int mode, long timeout, boolean use_anycasting) {
MethodCall method_call=new MethodCall(method_name, args, signature);
return callRemoteMethods(dests, method_call, new RequestOptions(mode, timeout, use_anycasting, null, (byte)0));
}
@Deprecated
public RspList callRemoteMethods(Vector<Address> dests, MethodCall method_call, int mode, long timeout) {
return callRemoteMethods(dests, method_call, new RequestOptions().setMode(mode).setTimeout(timeout));
}
/**
* Invokes a method in all members contained in dests (or all members if dests is null).
* @param dests A list of addresses. If null, the method will be invoked on all cluster members
* @param method_call The method (plus args) to be invoked
* @param options A collection of call options, e.g. sync versus async, timeout etc
* @return RspList A list of return values and flags (suspected, not received) per member
* @since 2.9
*/
public RspList callRemoteMethods(Collection<Address> dests, MethodCall method_call, RequestOptions options) {
if(dests != null && dests.isEmpty()) { // don't send if dest list is empty
if(log.isTraceEnabled())
log.trace(new StringBuilder("destination list of ").append(method_call.getName()).
append("() is empty: no need to send message"));
return RspList.EMPTY_RSP_LIST;
}
if(log.isTraceEnabled())
log.trace(new StringBuilder("dests=").append(dests).append(", method_call=").append(method_call).
append(", options=").append(options));
Object buf;
try {
buf=req_marshaller != null? req_marshaller.objectToBuffer(method_call) : Util.objectToByteBuffer(method_call);
}
catch(Exception e) {
// if(log.isErrorEnabled()) log.error("exception", e);
// we will change this in 3.0 to add the exception to the signature
// signature in 2.3, otherwise 2.3 would be *not* API compatible to prev releases
throw new RuntimeException("failure to marshal argument(s)", e);
}
Message msg=new Message();
if(buf instanceof Buffer)
msg.setBuffer((Buffer)buf);
else
msg.setBuffer((byte[])buf);
msg.setFlag(options.getFlags());
if(options.getScope() > 0)
msg.setScope(options.getScope());
RspList retval=super.castMessage(dests, msg, options);
if(log.isTraceEnabled()) log.trace("responses: " + retval);
return retval;
}
@Deprecated
public NotifyingFuture<RspList> callRemoteMethodsWithFuture(Vector<Address> dests, MethodCall method_call, int mode, long timeout,
boolean use_anycasting, boolean oob, RspFilter filter) {
RequestOptions options=new RequestOptions(mode, timeout, use_anycasting, filter);
if(oob) options.setFlags(Message.OOB);
return callRemoteMethodsWithFuture(dests, method_call, options);
}
@Deprecated
public NotifyingFuture<RspList> callRemoteMethodsWithFuture(Vector<Address> dests, MethodCall method_call) {
return callRemoteMethodsWithFuture(dests, method_call, new RequestOptions());
}
public NotifyingFuture<RspList> callRemoteMethodsWithFuture(Collection<Address> dests, MethodCall method_call, RequestOptions options) {
if(dests != null && dests.isEmpty()) { // don't send if dest list is empty
if(log.isTraceEnabled())
log.trace(new StringBuilder("destination list of ").append(method_call.getName()).
append("() is empty: no need to send message"));
return new NullFuture<RspList>(RspList.EMPTY_RSP_LIST);
}
if(log.isTraceEnabled())
log.trace(new StringBuilder("dests=").append(dests).append(", method_call=").append(method_call).
append(", options=").append(options));
Object buf;
try {
buf=req_marshaller != null? req_marshaller.objectToBuffer(method_call) : Util.objectToByteBuffer(method_call);
}
catch(Exception e) {
// if(log.isErrorEnabled()) log.error("exception", e);
// we will change this in 2.4 to add the exception to the signature
// signature in 2.3, otherwise 2.3 would be *not* API compatible to prev releases
throw new RuntimeException("failure to marshal argument(s)", e);
}
Message msg=new Message();
if(buf instanceof Buffer)
msg.setBuffer((Buffer)buf);
else
msg.setBuffer((byte[])buf);
msg.setFlag(options.getFlags());
if(options.getScope() > 0)
msg.setScope(options.getScope());
NotifyingFuture<RspList> retval=super.castMessageWithFuture(dests, msg, options);
if(log.isTraceEnabled()) log.trace("responses: " + retval);
return retval;
}
@Deprecated
public Object callRemoteMethod(Address dest, String method_name, Object[] args,
Class[] types, int mode, long timeout) throws Throwable {
MethodCall method_call=new MethodCall(method_name, args, types);
return callRemoteMethod(dest, method_call, mode, timeout);
}
public Object callRemoteMethod(Address dest, String method_name, Object[] args,
Class[] types, RequestOptions options) throws Throwable {
MethodCall method_call=new MethodCall(method_name, args, types);
return callRemoteMethod(dest, method_call, options);
}
@Deprecated
public Object callRemoteMethod(Address dest, String method_name, Object[] args,
String[] signature, int mode, long timeout) throws Throwable {
MethodCall method_call=new MethodCall(method_name, args, signature);
return callRemoteMethod(dest, method_call, mode, timeout);
}
@Deprecated
public Object callRemoteMethod(Address dest, MethodCall method_call, int mode, long timeout) throws Throwable {
return callRemoteMethod(dest, method_call, mode, timeout, false);
}
@Deprecated
public Object callRemoteMethod(Address dest, MethodCall method_call, int mode, long timeout, boolean oob) throws Throwable {
RequestOptions options=new RequestOptions(mode, timeout, false, null);
if(oob) options.setFlags(Message.OOB);
return callRemoteMethod(dest, method_call, options);
}
@Deprecated
public Object callRemoteMethod(Address dest, MethodCall call) throws Throwable {
return callRemoteMethod(dest, call, new RequestOptions());
}
public Object callRemoteMethod(Address dest, MethodCall call, RequestOptions options) throws Throwable {
if(log.isTraceEnabled())
log.trace("dest=" + dest + ", method_call=" + call + ", options=" + options);
Object buf=req_marshaller != null? req_marshaller.objectToBuffer(call) : Util.objectToByteBuffer(call);
Message msg=new Message(dest, null, null);
if(buf instanceof Buffer)
msg.setBuffer((Buffer)buf);
else
msg.setBuffer((byte[])buf);
msg.setFlag(options.getFlags());
if(options.getScope() > 0)
msg.setScope(options.getScope());
Object retval=super.sendMessage(msg, options);
if(log.isTraceEnabled()) log.trace("retval: " + retval);
if(retval instanceof Throwable)
throw (Throwable)retval;
return retval;
}
@Deprecated
public <T> NotifyingFuture<T> callRemoteMethodWithFuture(Address dest, MethodCall method_call, int mode, long timeout, boolean oob) throws Throwable {
RequestOptions options=new RequestOptions(mode, timeout, false, null);
if(oob) options.setFlags(Message.OOB);
return callRemoteMethodWithFuture(dest, method_call, options);
}
@Deprecated
public <T> NotifyingFuture<T> callRemoteMethodWithFuture(Address dest, MethodCall call) throws Throwable {
return callRemoteMethodWithFuture(dest, call, new RequestOptions());
}
public <T> NotifyingFuture<T> callRemoteMethodWithFuture(Address dest, MethodCall call, RequestOptions options) throws Throwable {
if(log.isTraceEnabled())
log.trace("dest=" + dest + ", method_call=" + call + ", options=" + options);
Object buf=req_marshaller != null? req_marshaller.objectToBuffer(call) : Util.objectToByteBuffer(call);
Message msg=new Message(dest, null, null);
if(buf instanceof Buffer)
msg.setBuffer((Buffer)buf);
else
msg.setBuffer((byte[])buf);
msg.setFlag(options.getFlags());
if(options.getScope() > 0)
msg.setScope(options.getScope());
return super.sendMessageWithFuture(msg, options);
}
protected void correlatorStarted() {
if(corr != null)
corr.setMarshaller(rsp_marshaller);
}
/**
* Message contains MethodCall. Execute it against *this* object and return result.
* Use MethodCall.invoke() to do this. Return result.
*/
public Object handle(Message req) {
Object body;
MethodCall method_call;
if(server_obj == null) {
if(log.isErrorEnabled()) log.error("no method handler is registered. Discarding request.");
return null;
}
if(req == null || req.getLength() == 0) {
if(log.isErrorEnabled()) log.error("message or message buffer is null");
return null;
}
try {
body=req_marshaller != null?
req_marshaller.objectFromByteBuffer(req.getBuffer(), req.getOffset(), req.getLength())
: req.getObject();
}
catch(Throwable e) {
if(log.isErrorEnabled()) log.error("exception marshalling object", e);
return e;
}
if(!(body instanceof MethodCall)) {
if(log.isErrorEnabled()) log.error("message does not contain a MethodCall object");
// create an exception to represent this and return it
return new IllegalArgumentException("message does not contain a MethodCall object") ;
}
method_call=(MethodCall)body;
try {
if(log.isTraceEnabled())
log.trace("[sender=" + req.getSrc() + "], method_call: " + method_call);
if(method_call.getMode() == MethodCall.ID) {
if(method_lookup == null)
throw new Exception("MethodCall uses ID=" + method_call.getId() + ", but method_lookup has not been set");
Method m=method_lookup.findMethod(method_call.getId());
if(m == null)
throw new Exception("no method found for " + method_call.getId());
method_call.setMethod(m);
}
return method_call.invoke(server_obj);
}
catch(Throwable x) {
return x;
}
}
/**
* Add a new channel listener to be notified on the channel's state change.
*
* @return true if the listener was added or false if the listener was already in the list.
*/
public boolean addChannelListener(ChannelListener l) {
synchronized(additionalChannelListeners) {
if (additionalChannelListeners.contains(l)) {
return false;
}
additionalChannelListeners.add(l);
return true;
}
}
/**
*
* @return true if the channel was removed indeed.
*/
public boolean removeChannelListener(ChannelListener l) {
synchronized(additionalChannelListeners) {
return additionalChannelListeners.remove(l);
}
}
public void channelConnected(Channel channel) {
synchronized(additionalChannelListeners) {
for(Iterator i = additionalChannelListeners.iterator(); i.hasNext(); ) {
ChannelListener l = (ChannelListener)i.next();
try {
l.channelConnected(channel);
}
catch(Throwable t) {
log.warn("channel listener failed", t);
}
}
}
}
public void channelDisconnected(Channel channel) {
stop();
synchronized(additionalChannelListeners) {
for(Iterator i = additionalChannelListeners.iterator(); i.hasNext(); ) {
ChannelListener l = (ChannelListener)i.next();
try {
l.channelDisconnected(channel);
}
catch(Throwable t) {
log.warn("channel listener failed", t);
}
}
}
}
public void channelClosed(Channel channel) {
stop();
synchronized(additionalChannelListeners) {
for(Iterator i = additionalChannelListeners.iterator(); i.hasNext(); ) {
ChannelListener l = (ChannelListener)i.next();
try {
l.channelClosed(channel);
}
catch(Throwable t) {
log.warn("channel listener failed", t);
}
}
}
}
public void channelShunned() {
}
public void channelReconnected(Address new_addr) {
}
}
|
package com.atlassian.jira.plugins.dvcs.dao.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.java.ao.EntityStreamCallback;
import net.java.ao.Query;
import net.java.ao.RawEntity;
import net.java.ao.schema.PrimaryKey;
import net.java.ao.schema.Table;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.jira.plugins.dvcs.activeobjects.ActiveObjectsUtils;
import com.atlassian.jira.plugins.dvcs.activeobjects.QueryHelper;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.ChangesetMapping;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.IssueToChangesetMapping;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.RepositoryToChangesetMapping;
import com.atlassian.jira.plugins.dvcs.dao.ChangesetDao;
import com.atlassian.jira.plugins.dvcs.dao.impl.transform.ChangesetTransformer;
import com.atlassian.jira.plugins.dvcs.model.Changeset;
import com.atlassian.jira.plugins.dvcs.model.ChangesetFile;
import com.atlassian.jira.plugins.dvcs.model.GlobalFilter;
import com.atlassian.jira.util.json.JSONArray;
import com.atlassian.jira.util.json.JSONException;
import com.atlassian.jira.util.json.JSONObject;
import com.atlassian.sal.api.transaction.TransactionCallback;
public class ChangesetDaoImpl implements ChangesetDao
{
private static final Logger log = LoggerFactory.getLogger(ChangesetDaoImpl.class);
private final ActiveObjects activeObjects;
private final ChangesetTransformer transformer = new ChangesetTransformer();
private QueryHelper queryHelper;
public ChangesetDaoImpl(ActiveObjects activeObjects, QueryHelper queryHelper)
{
this.activeObjects = activeObjects;
this.queryHelper = queryHelper;
}
private Changeset transform(ChangesetMapping changesetMapping, int defaultRepositoryId)
{
return transformer.transform(changesetMapping, defaultRepositoryId);
}
private Changeset transform(ChangesetMapping changesetMapping)
{
return transformer.transform(changesetMapping, 0);
}
private List<Changeset> transform(List<ChangesetMapping> changesetMappings)
{
List<Changeset> changesets = new ArrayList<Changeset>();
for (ChangesetMapping changesetMapping : changesetMappings)
{
Changeset changeset = transform(changesetMapping);
if (changeset != null)
{
changesets.add(changeset);
}
}
return changesets;
}
@Override
public void removeAllInRepository(final int repositoryId)
{
activeObjects.executeInTransaction(new TransactionCallback<Object>()
{
@Override
public Object doInTransaction()
{
// todo: transaction: plugin use SalTransactionManager and there is empty implementation of TransactionSynchronisationManager.
// todo: Therefore there are only entityCache transactions. No DB transactions.
// delete association repo - changesets
Query query = Query.select().where(RepositoryToChangesetMapping.REPOSITORY_ID + " = ?", repositoryId);
log.debug("deleting repo - changesets associations from RepoToChangeset with id = [ {} ]", new String[]{String.valueOf(repositoryId)});
ActiveObjectsUtils.delete(activeObjects, RepositoryToChangesetMapping.class, query);
// delete association issues - changeset
query = Query.select()
.alias(IssueToChangesetMapping.class, "i2c")
.alias(RepositoryToChangesetMapping.class, "r2c")
.join(RepositoryToChangesetMapping.class,
"i2c." + IssueToChangesetMapping.CHANGESET_ID + " = r2c." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("r2c.ID is null ");
log.debug("deleting orphaned issue-changeset associations");
ActiveObjectsUtils.delete(activeObjects, IssueToChangesetMapping.class, query);
// delete orphaned changesets
query = Query.select()
.alias(ChangesetMapping.class, "c")
.alias(RepositoryToChangesetMapping.class, "r2c")
.join(RepositoryToChangesetMapping.class, "c.ID = r2c." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("r2c.ID is null ");
log.debug("deleting orphaned changesets");
ActiveObjectsUtils.delete(activeObjects, ChangesetMapping.class, query);
return null;
}
});
}
@Override
public Changeset create(final Changeset changeset, final Set<String> extractedIssues)
{
ChangesetMapping changesetMapping = activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
{
@Override
public ChangesetMapping doInTransaction()
{
ChangesetMapping chm = getChangesetMapping(changeset);
if (chm == null)
{
chm = activeObjects.create(ChangesetMapping.class);
fillProperties(changeset, chm);
chm.save();
}
associateRepositoryToChangeset(chm, changeset.getRepositoryId());
if (extractedIssues != null)
{
associateIssuesToChangeset(chm, extractedIssues);
}
return chm;
}
});
changeset.setId(changesetMapping.getID());
return changeset;
}
@Override
public Changeset update(final Changeset changeset)
{
activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
{
@Override
public ChangesetMapping doInTransaction()
{
ChangesetMapping chm = getChangesetMapping(changeset);
if (chm != null)
{
fillProperties(changeset, chm);
chm.save();
} else
{
log.warn("Changest with node {} is not exists.", changeset.getNode());
}
return chm;
}
});
return changeset;
}
private ChangesetMapping getChangesetMapping(Changeset changeset)
{
// A Query is little bit more complicated, but:
// 1. previous implementation did not properly fill RAW_NODE, in some cases it is null, in some other cases it is empty string
String hasRawNode = "( " + ChangesetMapping.RAW_NODE + " is not null AND " + ChangesetMapping.RAW_NODE + " != '') ";
// 2. Latest implementation is using full RAW_NODE, but not all records contains it!
String matchRawNode = ChangesetMapping.RAW_NODE + " = ? ";
// 3. Previous implementation has used NODE, but it is mix in some cases it is short version, in some cases it is full version
String matchNode = ChangesetMapping.NODE + " like ? ";
String shortNode = changeset.getNode().substring(0, 12) + "%";
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class, "(" + hasRawNode + " AND " + matchRawNode + " ) OR ( NOT "
+ hasRawNode + " AND " + matchNode + " ) ", changeset.getRawNode(), shortNode);
if (mappings.length > 1)
{
log.warn("More changesets with same Node. Same changesets count: {}, Node: {}, Repository: {}", new Object[] { mappings.length,
changeset.getNode(), changeset.getRepositoryId() });
}
return (ArrayUtils.isNotEmpty(mappings)) ? mappings[0] : null;
}
public void fillProperties(Changeset changeset, ChangesetMapping chm)
{
// we need to remove null characters '\u0000' because PostgreSQL cannot store String values with such
// characters
// todo: remove NULL Chars before call setters
chm.setNode(changeset.getNode());
chm.setRawAuthor(ActiveObjectsUtils.stripToLimit(changeset.getRawAuthor(), 255));
chm.setAuthor(changeset.getAuthor());
chm.setDate(changeset.getDate());
chm.setRawNode(changeset.getRawNode());
chm.setBranch(ActiveObjectsUtils.stripToLimit(changeset.getBranch(), 255));
chm.setMessage(changeset.getMessage());
chm.setAuthorEmail(ActiveObjectsUtils.stripToLimit(changeset.getAuthorEmail(), 255));
chm.setSmartcommitAvailable(changeset.isSmartcommitAvaliable());
JSONArray parentsJson = new JSONArray();
for (String parent : changeset.getParents())
{
parentsJson.put(parent);
}
String parentsData = parentsJson.toString();
if (parentsData.length() > 255)
{
parentsData = ChangesetMapping.TOO_MANY_PARENTS;
}
chm.setParentsData(parentsData);
JSONObject filesDataJson = new JSONObject();
JSONArray filesJson = new JSONArray();
try
{
List<ChangesetFile> files = changeset.getFiles();
int count = changeset.getAllFileCount();
filesDataJson.put("count", count);
for (int i = 0; i < Math.min(count, Changeset.MAX_VISIBLE_FILES); i++)
{
ChangesetFile changesetFile = files.get(i);
JSONObject fileJson = new JSONObject();
fileJson.put("filename", changesetFile.getFile());
fileJson.put("status", changesetFile.getFileAction().getAction());
fileJson.put("additions", changesetFile.getAdditions());
fileJson.put("deletions", changesetFile.getDeletions());
filesJson.put(fileJson);
}
filesDataJson.put("files", filesJson);
chm.setFilesData(filesDataJson.toString());
} catch (JSONException e)
{
log.error("Creating files JSON failed!", e);
}
chm.setVersion(ChangesetMapping.LATEST_VERSION);
chm.save();
}
private void associateIssuesToChangeset(ChangesetMapping changesetMapping, Set<String> extractedIssues)
{
// remove all assoc issues-changeset
Query query = Query.select().where(IssueToChangesetMapping.CHANGESET_ID + " = ? ", changesetMapping);
ActiveObjectsUtils.delete(activeObjects, IssueToChangesetMapping.class, query);
// insert all
for (String extractedIssue : extractedIssues)
{
final Map<String, Object> map = new MapRemovingNullCharacterFromStringValues();
map.put(IssueToChangesetMapping.ISSUE_KEY, extractedIssue);
map.put(IssueToChangesetMapping.PROJECT_KEY, parseProjectKey(extractedIssue));
map.put(IssueToChangesetMapping.CHANGESET_ID, changesetMapping.getID());
activeObjects.create(IssueToChangesetMapping.class, map);
}
}
private void associateRepositoryToChangeset(ChangesetMapping changesetMapping, int repositoryId)
{
RepositoryToChangesetMapping[] mappings = activeObjects.find(RepositoryToChangesetMapping.class,
RepositoryToChangesetMapping.REPOSITORY_ID + " = ? and " +
RepositoryToChangesetMapping.CHANGESET_ID + " = ? ",
repositoryId,
changesetMapping);
if (ArrayUtils.isEmpty(mappings))
{
final Map<String, Object> map = new MapRemovingNullCharacterFromStringValues();
map.put(RepositoryToChangesetMapping.REPOSITORY_ID, repositoryId);
map.put(RepositoryToChangesetMapping.CHANGESET_ID, changesetMapping);
activeObjects.create(RepositoryToChangesetMapping.class, map);
}
}
public static String parseProjectKey(String issueKey)
{
return issueKey.substring(0, issueKey.indexOf("-"));
}
@Override
public Changeset getByNode(final int repositoryId, final String changesetNode)
{
final ChangesetMapping changesetMapping = activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
{
@Override
public ChangesetMapping doInTransaction()
{
Query query = Query.select()
.alias(ChangesetMapping.class, "chm")
.alias(RepositoryToChangesetMapping.class, "rtchm")
.join(RepositoryToChangesetMapping.class, "chm.ID = rtchm." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("chm." + ChangesetMapping.NODE + " = ? AND rtchm." + RepositoryToChangesetMapping.REPOSITORY_ID + " = ? ", changesetNode, repositoryId);
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class, query);
return mappings.length != 0 ? mappings[0] : null;
}
});
final Changeset changeset = transform(changesetMapping, repositoryId);
return changeset;
}
@Override
public List<Changeset> getByIssueKey(final Iterable<String> issueKeys, final boolean newestFirst)
{
final GlobalFilter gf = new GlobalFilter();
gf.setInIssues(issueKeys);
final String baseWhereClause = new GlobalFilterQueryWhereClauseBuilder(gf).build();
final List<ChangesetMapping> changesetMappings = activeObjects.executeInTransaction(new TransactionCallback<List<ChangesetMapping>>()
{
@Override
public List<ChangesetMapping> doInTransaction()
{
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class,
Query.select()
.alias(ChangesetMapping.class, "CHANGESET")
.alias(IssueToChangesetMapping.class, "ISSUE")
.join(IssueToChangesetMapping.class, "CHANGESET.ID = ISSUE." + IssueToChangesetMapping.CHANGESET_ID)
.where(baseWhereClause)
.order(ChangesetMapping.DATE + (newestFirst ? " DESC": " ASC")));
return Arrays.asList(mappings);
}
});
return transform(changesetMappings);
}
@Override
public List<Changeset> getLatestChangesets(final int maxResults, final GlobalFilter gf)
{
if (maxResults <= 0)
{
return Collections.emptyList();
}
final List<ChangesetMapping> changesetMappings = activeObjects.executeInTransaction(new TransactionCallback<List<ChangesetMapping>>()
{
@Override
public List<ChangesetMapping> doInTransaction()
{
String baseWhereClause = new GlobalFilterQueryWhereClauseBuilder(gf).build();
Query query = Query.select()
.alias(ChangesetMapping.class, "CHANGESET")
.alias(IssueToChangesetMapping.class, "ISSUE")
.join(IssueToChangesetMapping.class, "CHANGESET.ID = ISSUE." + IssueToChangesetMapping.CHANGESET_ID)
.where(baseWhereClause).limit(maxResults).order(ChangesetMapping.DATE + " DESC");
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class, query);
return Arrays.asList(mappings);
}
});
return transform(changesetMappings);
}
@Override
public void forEachLatestChangesetsAvailableForSmartcommitDo(final int repositoryId, final ForEachChangesetClosure closure)
{
Query query = createLatestChangesetsAvailableForSmartcommitQuery(repositoryId);
activeObjects.stream(ChangesetMapping.class, query, new EntityStreamCallback<ChangesetMapping, Integer>()
{
@Override
public void onRowRead(ChangesetMapping mapping)
{
closure.execute(mapping);
}
});
}
private Query createLatestChangesetsAvailableForSmartcommitQuery(int repositoryId)
{
return Query.select("*")
.from(ChangesetMapping.class)
.alias(ChangesetMapping.class, "chm")
.alias(RepositoryToChangesetMapping.class, "rtchm")
.join(RepositoryToChangesetMapping.class, "chm.ID = rtchm." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("rtchm." + RepositoryToChangesetMapping.REPOSITORY_ID + " = ? and chm."+ChangesetMapping.SMARTCOMMIT_AVAILABLE+" = ? " , repositoryId, Boolean.TRUE)
.order(ChangesetMapping.DATE + " DESC");
}
@Override
public Set<String> findReferencedProjects(int repositoryId)
{
Query query = Query.select(IssueToChangesetMapping.PROJECT_KEY).distinct()
.alias(ProjectKey.class, "pk")
.alias(ChangesetMapping.class, "chm")
.alias(RepositoryToChangesetMapping.class, "rtchm")
.join(ChangesetMapping.class, "chm.ID = pk." + IssueToChangesetMapping.CHANGESET_ID)
.join(RepositoryToChangesetMapping.class, "chm.ID = rtchm." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("rtchm." + RepositoryToChangesetMapping.REPOSITORY_ID + " = ?", repositoryId)
.order(IssueToChangesetMapping.PROJECT_KEY);
final Set<String> projectKeys = new HashSet<String>();
activeObjects.stream(ProjectKey.class, query, new EntityStreamCallback<ProjectKey, String>()
{
@Override
public void onRowRead(ProjectKey mapping)
{
projectKeys.add(mapping.getProjectKey());
}
});
return projectKeys;
}
@Table("IssueToChangeset")
static interface ProjectKey extends RawEntity<String>
{
@PrimaryKey(IssueToChangesetMapping.PROJECT_KEY)
String getProjectKey();
void setProjectKey();
}
@Override
public void markSmartcommitAvailability(int id, boolean available)
{
final ChangesetMapping changesetMapping = activeObjects.get(ChangesetMapping.class, id);
changesetMapping.setSmartcommitAvailable(available);
activeObjects.executeInTransaction(new TransactionCallback<Void>()
{
@Override
public Void doInTransaction()
{
changesetMapping.save();
return null;
}
});
}
@Override
public int getChangesetCount(final int repositoryId)
{
return activeObjects.executeInTransaction(new TransactionCallback<Integer>()
{
@Override
public Integer doInTransaction()
{
Query query = Query.select().where(RepositoryToChangesetMapping.REPOSITORY_ID + " = ?", repositoryId);
return activeObjects.count(RepositoryToChangesetMapping.class, query);
}
});
}
}
|
package pl.pwr.hiervis.measures;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import internal_measures.statistics.AvgWithStdev;
import pl.pwr.hiervis.hierarchy.LoadedHierarchy;
import pl.pwr.hiervis.util.Event;
public class MeasureManager
{
/** Sent when a measure task is posted for processing. */
public final Event<Pair<LoadedHierarchy, MeasureTask>> taskPosted = new Event<>();
/** Sent when a measure task computation failed due to an exception. */
public final Event<Pair<LoadedHierarchy, MeasureTask>> taskFailed = new Event<>();
/** Sent when a measure computation is started. */
public final Event<Pair<LoadedHierarchy, String>> measureComputing = new Event<>();
/** Sent when a measure computation is finished. */
public final Event<Triple<LoadedHierarchy, String, Object>> measureComputed = new Event<>();
private MeasureComputeThread computeThread = null;
private Map<String, Collection<MeasureTask>> measureGroupMap = null;
public MeasureManager()
{
measureGroupMap = new HashMap<>();
computeThread = new MeasureComputeThread();
computeThread.taskPosted.addListener( this::onTaskPosted );
computeThread.taskFailed.addListener( this::onTaskFailed );
computeThread.measureComputing.addListener( this::onMeasureComputing );
computeThread.measureComputed.addListener( this::onMeasureComputed );
computeThread.start();
}
/**
* Checks whether the measure with the specified name is scheduled for processing, or
* currently being processed.
*
* @param lh
* the hierarchy to check the measure for
* @param measureName
* identifier of the measure
* @return true if a measure with the specified identifier is pending calculation, or
* is currently being calculated. False otherwise.
*/
public boolean isMeasurePending( LoadedHierarchy lh, String measureName )
{
return computeThread.isMeasurePending( lh, measureName );
}
/**
* Posts a new task for the thread to process.
*
* @param lh
* the hierarchy to compute the measure for
* @param measure
* the measure to post
*/
public void postTask( LoadedHierarchy lh, MeasureTask measure )
{
computeThread.postTask( lh, measure );
}
/**
* Posts a new task for the thread to process.
*
* @param task
* the task to post
*/
public void postTask( Pair<LoadedHierarchy, MeasureTask> task )
{
computeThread.postTask( task.getLeft(), task.getRight() );
}
/**
* Removes the task from processing queue, if it is not already being processed.
*
* @param lh
* the hierarchy to remove the measure for
* @param measure
* the measure to remove.
* @return true if the task was found and removed, false otherwise.
*/
public boolean removeTask( LoadedHierarchy lh, MeasureTask measure )
{
return computeThread.removeTask( lh, measure );
}
/**
* Removes the task from processing queue, if it is not already being processed.
*
* @param task
* the task to remove.
* @return true if the task was found and removed, false otherwise.
*/
public boolean removeTask( Pair<LoadedHierarchy, MeasureTask> task )
{
return computeThread.removeTask( task.getLeft(), task.getRight() );
}
/**
* Clears any pending tasks that have been scheduled for computation, but haven't been started yet.
*/
public void clearPendingTasks()
{
computeThread.clearPendingTasks();
}
/**
* Loads {@link MeasureTask}s from script files in the specified directory.
*
* @param dirPath
* the directory containing all {@link MeasureTask} script files.
* @throws IOException
* if an IO error occurs
*/
public void loadMeasureFiles( Path dirPath ) throws IOException
{
if ( !Files.isDirectory( dirPath ) )
throw new IllegalArgumentException( "Argument must point to a directory!" );
MeasureTaskFactory factory = new JavascriptMeasureTaskFactory( false );
Files.walk( dirPath ).forEach(
filePath -> {
if ( Files.isRegularFile( filePath, LinkOption.NOFOLLOW_LINKS ) ) {
MeasureTask measure = factory.getMeasureTask( filePath );
if ( measure != null ) {
String groupPath = filePath.getParent().toString()
.replace( dirPath.toString(), "" )
.substring( 1 )
.replace( "\\", "/" );
Collection<MeasureTask> group = measureGroupMap.get( groupPath );
if ( group == null ) {
group = new ArrayList<MeasureTask>();
measureGroupMap.put( groupPath, group );
}
group.add( measure );
}
}
}
);
}
/**
* @param groupId
* id of the measure group we want to receive
* @return returns an unmodifiable collection of all measures belonging to
* the group with the specified id.
*/
public Collection<MeasureTask> getMeasureTaskGroup( String groupId )
{
if ( !measureGroupMap.containsKey( groupId ) )
throw new IllegalArgumentException( "No such measure task group: " + groupId );
return Collections.unmodifiableCollection( measureGroupMap.get( groupId ) );
}
/**
* @param predicate
* the predicate that {@link MeasureTask}s have to match in order
* to be included in the result.
* @return a list of {@link MeasureTask}s that match the specified predicate
*/
public Collection<MeasureTask> getMeasureTasks( Predicate<MeasureTask> predicate )
{
return measureGroupMap.values().stream()
.flatMap( Collection::stream )
.filter( predicate )
.collect( Collectors.toList() );
}
/**
* @return a list of all {@link MeasureTask}s the manager is aware of
*/
public Collection<MeasureTask> getAllMeasureTasks()
{
return getMeasureTasks( t -> true );
}
/**
* @return a sorted collection of ids of all measure groups that have been loaded.
*/
public Collection<String> listMeasureTaskGroups()
{
return measureGroupMap.keySet().stream()
.sorted()
.collect( Collectors.toList() );
}
public void dispose()
{
computeThread.shutdown();
}
public void dumpMeasures( Path destinationFile, LoadedHierarchy hierarchy )
{
final Function<Object, String> resultToCSV = data -> {
if ( data instanceof Number ) {
return Objects.toString( data ) + ";0.0;";
}
else if ( data instanceof AvgWithStdev ) {
AvgWithStdev avg = (AvgWithStdev)data;
return avg.getAvg() + ";" + avg.getStdev() + ";";
}
else {
throw new IllegalArgumentException( "Unexpected data type in measure result: " + data.getClass().getName() );
}
};
final Function<MeasureTask, String> dumpHistogram = task -> {
StringBuilder buf2 = new StringBuilder();
Object measureResult = hierarchy.measureHolder.getMeasureResultOrDefault( task.identifier, new double[0] );
if ( measureResult instanceof double[] == false )
throw new IllegalArgumentException( "Not a histogram measure: " + task.identifier );
double[] data = (double[])measureResult;
if ( data.length > 0 ) {
buf2.append( task.identifier ).append( '\n' );
for ( int i = 0; i < data.length; ++i )
buf2.append( i ).append( ';' );
buf2.append( '\n' );
for ( int i = 0; i < data.length; ++i )
buf2.append( data[i] ).append( ';' );
buf2.append( '\n' );
for ( int i = 0; i < data.length; ++i )
buf2.append( "0.0;" );
buf2.append( "\n\n" );
}
return buf2.toString();
};
StringBuilder buf = new StringBuilder();
// Measures
buf.append( "Use subtree for internal measures?;" );
Collection<MeasureTask> measures = getAllMeasureTasks();
measures.forEach(
task -> {
Object measureResult = hierarchy.measureHolder.getMeasureResult( task.identifier );
if ( measureResult instanceof Number || measureResult instanceof AvgWithStdev )
buf.append( task.identifier ).append( ";stdev;" );
}
);
buf.append( "\n" );
// Append data values
buf.append( hierarchy.options.isUseSubtree ).append( ';' );
measures.forEach(
task -> {
Object measureResult = hierarchy.measureHolder.getMeasureResult( task.identifier );
if ( measureResult instanceof Number || measureResult instanceof AvgWithStdev )
buf.append( resultToCSV.apply( measureResult ) );
}
);
buf.append( "\n\n" );
// Histograms
measures.forEach(
task -> {
Object measureResult = hierarchy.measureHolder.getMeasureResult( task.identifier );
if ( measureResult instanceof double[] )
buf.append( dumpHistogram.apply( task ) );
}
);
// String measures
measures.forEach(
task -> {
Object measureResult = hierarchy.measureHolder.getMeasureResult( task.identifier );
if ( measureResult instanceof String ) {
buf.append( task.identifier ).append( '\n' )
.append( measureResult ).append( "\n\n" );
}
}
);
try ( FileWriter writer = new FileWriter( destinationFile.toFile() ) ) {
writer.write( buf.toString() );
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
private void onTaskPosted( Pair<LoadedHierarchy, MeasureTask> task )
{
taskPosted.broadcast( task );
}
private void onTaskFailed( Pair<LoadedHierarchy, MeasureTask> task )
{
taskFailed.broadcast( task );
}
private void onMeasureComputing( Pair<LoadedHierarchy, String> task )
{
measureComputing.broadcast( task );
}
private void onMeasureComputed( Triple<LoadedHierarchy, String, Object> result )
{
result.getLeft().measureHolder.putMeasureResult( result.getMiddle(), result.getRight() );
measureComputed.broadcast( result );
}
}
|
// $Id: GMS.java,v 1.3 2003/11/21 09:06:13 belaban Exp $
package org.jgroups.protocols.pbcast;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import java.util.Iterator;
import org.jgroups.*;
import org.jgroups.util.*;
import org.jgroups.stack.*;
import org.jgroups.log.Trace;
/**
* Group membership protocol. Handles joins/leaves/crashes (suspicions) and emits new views
* accordingly. Use VIEW_ENFORCER on top of this layer to make sure new members don't receive
* any messages until they are members.
*/
public class GMS extends Protocol {
private GmsImpl impl=null;
public Properties props=null;
public Address local_addr=null;
public String group_addr=null;
public Membership members=new Membership(); // real membership
public Membership tmp_members=new Membership(); // base for computing next view
public Vector joining=new Vector(); // members joined but for which no view has been yet
public ViewId view_id=null;
public long ltime=0;
public long join_timeout=5000;
public long join_retry_timeout=2000;
public long leave_timeout=5000;
public long digest_timeout=5000; // time to wait for a digest (from PBCAST). should be fast
public long merge_timeout=10000; // time to wait for all MERGE_RSPS
public Object impl_mutex=new Object(); // synchronizes event entry into impl
private Object digest_mutex=new Object(); // synchronizes the GET_DIGEST/GET_DIGEST_OK events
private Digest digest=null; // holds result of GET_DIGEST event
private Hashtable impls=new Hashtable();
private boolean shun=true;
private boolean print_local_addr=true;
boolean disable_initial_coord=false; // can the member become a coord on startup or not ?
final String CLIENT="Client";
final String COORD="Coordinator";
final String PART="Participant";
TimeScheduler timer=null;
/** Max number of old members to keep in history */
protected int num_prev_mbrs=50;
/** Keeps track of old members (up to num_prev_mbrs) */
BoundedList prev_members=null;
public GMS() {
initState();
}
public String getName() {
return "GMS";
}
public Vector requiredDownServices() {
Vector retval=new Vector();
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.FIND_INITIAL_MBRS));
return retval;
}
public void setImpl(GmsImpl new_impl) {
synchronized(impl_mutex) {
impl=new_impl;
if(Trace.trace) Trace.info("GMS.setImpl()", "changed role to " + new_impl.getClass().getName());
}
}
public GmsImpl getImpl() {
return impl;
}
public void init() throws Exception {
prev_members=new BoundedList(num_prev_mbrs);
timer=stack != null? stack.timer : null;
if(timer == null)
throw new Exception("GMS.init(): timer is null");
if(impl != null)
impl.init();
}
public void start() throws Exception {
if(impl != null) impl.start();
}
public void stop() {
if(impl != null) impl.stop();
if(prev_members != null)
prev_members.removeAll();
}
public void becomeCoordinator() {
CoordGmsImpl tmp=(CoordGmsImpl)impls.get(COORD);
if(tmp == null) {
tmp=new CoordGmsImpl(this);
impls.put(COORD, tmp);
}
tmp.leaving=false;
setImpl(tmp);
if(Trace.trace) Trace.info("GMS.becomeCoordinator()", local_addr + " became coordinator");
}
public void becomeParticipant() {
ParticipantGmsImpl tmp=(ParticipantGmsImpl)impls.get(PART);
if(tmp == null) {
tmp=new ParticipantGmsImpl(this);
impls.put(PART, tmp);
}
tmp.leaving=false;
setImpl(tmp);
if(Trace.trace) Trace.info("GMS.becomeParticipant()", local_addr + " became participant");
}
public void becomeClient() {
ClientGmsImpl tmp=(ClientGmsImpl)impls.get(CLIENT);
if(tmp == null) {
tmp=new ClientGmsImpl(this);
impls.put(CLIENT, tmp);
}
tmp.initial_mbrs.removeAllElements();
setImpl(tmp);
if(Trace.trace) Trace.info("GMS.becomeClient", local_addr + " became client");
}
boolean haveCoordinatorRole() {
return impl != null && impl instanceof CoordGmsImpl;
}
/**
* Computes the next view. Returns a copy that has <code>old_mbrs</code> and
* <code>suspected_mbrs</code> removed and <code>new_mbrs</code> added.
*/
public View getNextView(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) {
Vector mbrs;
long vid=0;
View v;
Membership tmp_mbrs=null;
Address tmp_mbr;
synchronized(members) {
if(view_id == null) {
Trace.error("GMS.getNextView()", "view_id is null");
return null; // this should *never* happen !
}
vid=Math.max(view_id.getId(), ltime) + 1;
ltime=vid;
if(Trace.trace)
Trace.debug("GMS.getNextView()", "VID=" + vid + ", current members=" +
Util.printMembers(members.getMembers()) +
", new_mbrs=" + Util.printMembers(new_mbrs) +
", old_mbrs=" + Util.printMembers(old_mbrs) + ", suspected_mbrs=" +
Util.printMembers(suspected_mbrs));
tmp_mbrs=tmp_members.copy(); // always operate on the temporary membership
tmp_mbrs.remove(suspected_mbrs);
tmp_mbrs.remove(old_mbrs);
tmp_mbrs.add(new_mbrs);
mbrs=tmp_mbrs.getMembers();
v=new View(local_addr, vid, mbrs);
// Update membership (see DESIGN for explanation):
tmp_members.set(mbrs);
// Update joining list (see DESIGN for explanation)
if(new_mbrs != null) {
for(int i=0; i < new_mbrs.size(); i++) {
tmp_mbr=(Address)new_mbrs.elementAt(i);
if(!joining.contains(tmp_mbr))
joining.addElement(tmp_mbr);
}
}
if(Trace.trace)
Trace.debug("GMS.getNextView()", "new view is " + v);
return v;
}
}
/**
Compute a new view, given the current view, the new members and the suspected/left
members. Then simply mcast the view to all members. This is different to the VS GMS protocol,
in which we run a FLUSH protocol which tries to achive consensus on the set of messages mcast in
the current view before proceeding to install the next view.
The members for the new view are computed as follows:
<pre>
existing leaving suspected joining
1. new_view y n n y
2. tmp_view y y n y
(view_dest)
</pre>
<ol>
<li>
The new view to be installed includes the existing members plus the joining ones and
excludes the leaving and suspected members.
<li>
A temporary view is sent down the stack as an <em>event</em>. This allows the bottom layer
(e.g. UDP or TCP) to determine the members to which to send a multicast message. Compared
to the new view, leaving members are <em>included</em> since they have are waiting for a
view in which they are not members any longer before they leave. So, if we did not set a
temporary view, joining members would not receive the view (signalling that they have been
joined successfully). The temporary view is essentially the current view plus the joining
members (old members are still part of the current view).
</ol>
@return View The new view
*/
public View castViewChange(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) {
View new_view;
// next view: current mbrs + new_mbrs - old_mbrs - suspected_mbrs
new_view=getNextView(new_mbrs, old_mbrs, suspected_mbrs);
castViewChange(new_view);
return new_view;
}
public void castViewChange(View new_view) {
castViewChange(new_view, null);
}
public void castViewChange(View new_view, Digest digest) {
Message view_change_msg;
GmsHeader hdr;
if(Trace.trace)
Trace.info("GMS.castViewChange()", "mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n");
view_change_msg=new Message(); // bcast to all members
hdr=new GmsHeader(GmsHeader.VIEW, new_view);
hdr.digest=digest;
view_change_msg.putHeader(getName(), hdr);
passDown(new Event(Event.MSG, view_change_msg));
}
/**
* Sets the new view and sends a VIEW_CHANGE event up and down the stack. If the view is a MergeView (subclass
* of View), then digest will be non-null and has to be set before installing the view.
*/
public void installView(View new_view, Digest digest) {
if(digest != null)
mergeDigest(digest);
installView(new_view);
}
/**
* Sets the new view and sends a VIEW_CHANGE event up and down the stack.
*/
public void installView(View new_view) {
Address coord;
int rc;
ViewId vid=new_view.getVid();
Vector mbrs=new_view.getMembers();
if(Trace.trace) Trace.info("GMS.installView()", "[local_addr=" + local_addr + "] view is " + new_view);
// Discards view with id lower than our own. Will be installed without check if first view
if(view_id != null) {
rc=vid.compareTo(view_id);
if(rc <= 0) {
Trace.error("GMS.installView()", "received view <= current view;" +
" discarding it ! (current vid: " + view_id + ", new vid: " + vid + ")");
return;
}
}
ltime=Math.max(vid.getId(), ltime); // compute Lamport logical time
/* Check for self-inclusion: if I'm not part of the new membership, I just discard it.
This ensures that messages sent in view V1 are only received by members of V1 */
if(checkSelfInclusion(mbrs) == false) {
if(Trace.trace)
Trace.warn("GMS.installView()", "checkSelfInclusion() failed, " + local_addr +
" is not a member of view " + new_view + "; discarding view");
// only shun if this member was previously part of the group. avoids problem where multiple
// members (e.g. X,Y,Z) join {A,B} concurrently, X is joined first, and Y and Z get view
// {A,B,X}, which would cause Y and Z to be shunned as they are not part of the membership
// bela Nov 20 2003
if(shun && local_addr != null && prev_members.contains(local_addr)) {
if(Trace.trace)
Trace.warn("GMS.installView()", "I (" + local_addr +
") am being shunned, will leave and rejoin group. " +
"prev_members are " + prev_members);
passUp(new Event(Event.EXIT));
}
return;
}
synchronized(members) { // serialize access to views
// assign new_view to view_id
view_id=vid.copy();
// Set the membership. Take into account joining members
if(mbrs != null && mbrs.size() > 0) {
members.set(mbrs);
tmp_members.set(members);
joining.removeAll(mbrs); // remove all members in mbrs from joining
tmp_members.add(joining); // adjust temporary membership
// add to prev_members
for(Iterator it=mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!prev_members.contains(addr))
prev_members.add(addr);
}
}
// Send VIEW_CHANGE event up and down the stack:
Event view_event=new Event(Event.VIEW_CHANGE, new_view.clone());
passDown(view_event); // needed e.g. by failure detector or UDP
passUp(view_event);
coord=determineCoordinator();
if(coord != null && coord.equals(local_addr) && !(coord.equals(vid.getCoordAddress()))) {
becomeCoordinator();
}
else {
if(haveCoordinatorRole() && !local_addr.equals(coord))
becomeParticipant();
}
}
}
protected Address determineCoordinator() {
synchronized(members) {
return members != null && members.size() > 0? (Address)members.elementAt(0) : null;
}
}
/** Checks whether the potential_new_coord would be the new coordinator (2nd in line) */
protected boolean wouldBeNewCoordinator(Address potential_new_coord) {
Address new_coord=null;
if(potential_new_coord == null) return false;
synchronized(members) {
if(members.size() < 2) return false;
new_coord=(Address)members.elementAt(1); // member at 2nd place
if(new_coord != null && new_coord.equals(potential_new_coord))
return true;
return false;
}
}
/** Returns true if local_addr is member of mbrs, else false */
protected boolean checkSelfInclusion(Vector mbrs) {
Object mbr;
if(mbrs == null)
return false;
for(int i=0; i < mbrs.size(); i++) {
mbr=mbrs.elementAt(i);
if(mbr != null && local_addr.equals(mbr))
return true;
}
return false;
}
public View makeView(Vector mbrs) {
Address coord=null;
long id=0;
if(view_id != null) {
coord=view_id.getCoordAddress();
id=view_id.getId();
}
return new View(coord, id, mbrs);
}
public View makeView(Vector mbrs, ViewId vid) {
Address coord=null;
long id=0;
if(vid != null) {
coord=vid.getCoordAddress();
id=vid.getId();
}
return new View(coord, id, mbrs);
}
/** Send down a SET_DIGEST event */
public void setDigest(Digest d) {
passDown(new Event(Event.SET_DIGEST, d));
}
/** Send down a MERGE_DIGEST event */
public void mergeDigest(Digest d) {
passDown(new Event(Event.MERGE_DIGEST, d));
}
/** Sends down a GET_DIGEST event and waits for the GET_DIGEST_OK response, or
timeout, whichever occurs first */
public Digest getDigest() {
Digest ret=null;
synchronized(digest_mutex) {
digest=null;
passDown(new Event(Event.GET_DIGEST));
try {
digest_mutex.wait(digest_timeout);
}
catch(Exception ex) {
}
if(digest != null) {
ret=digest;
digest=null;
return ret;
}
else {
Trace.error("GMS.getDigest()", "digest could not be fetched from PBCAST layer");
return null;
}
}
}
public void up(Event evt) {
Object obj;
Message msg;
GmsHeader hdr;
MergeData merge_data;
switch(evt.getType()) {
case Event.MSG:
msg=(Message)evt.getArg();
obj=msg.getHeader(getName());
if(obj == null || !(obj instanceof GmsHeader))
break;
hdr=(GmsHeader)msg.removeHeader(getName());
switch(hdr.type) {
case GmsHeader.JOIN_REQ:
handleJoinRequest(hdr.mbr);
break;
case GmsHeader.JOIN_RSP:
impl.handleJoinResponse(hdr.join_rsp);
break;
case GmsHeader.LEAVE_REQ:
if(Trace.trace)
Trace.info("GMS.up()", "received LEAVE_REQ " + hdr + " from " + msg.getSrc());
if(hdr.mbr == null) {
if(Trace.trace)
Trace.error("GMS.up()", "LEAVE_REQ's mbr field is null");
return;
}
sendLeaveResponse(hdr.mbr);
impl.handleLeave(hdr.mbr, false);
break;
case GmsHeader.LEAVE_RSP:
impl.handleLeaveResponse();
break;
case GmsHeader.VIEW:
if(hdr.view == null) {
Trace.error("GMS.up()", "[VIEW]: view == null");
return;
}
impl.handleViewChange(hdr.view, hdr.digest);
break;
case GmsHeader.MERGE_REQ:
impl.handleMergeRequest(msg.getSrc(), hdr.merge_id);
break;
case GmsHeader.MERGE_RSP:
merge_data=new MergeData(msg.getSrc(), hdr.view, hdr.digest);
merge_data.merge_rejected=hdr.merge_rejected;
impl.handleMergeResponse(merge_data, hdr.merge_id);
break;
case GmsHeader.INSTALL_MERGE_VIEW:
impl.handleMergeView(new MergeData(msg.getSrc(), hdr.view, hdr.digest), hdr.merge_id);
break;
case GmsHeader.CANCEL_MERGE:
impl.handleMergeCancelled(hdr.merge_id);
break;
default:
Trace.error("GMS.up()", "GmsHeader with type=" + hdr.type + " not known");
}
return; // don't pass up
case Event.CONNECT_OK: // sent by someone else, but WE are responsible for sending this !
case Event.DISCONNECT_OK: // dito (e.g. sent by UDP layer). Don't send up the stack
return;
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
if(print_local_addr) {
System.out.println("\n
"GMS: address is " + local_addr +
"\n
}
break; // pass up
case Event.SUSPECT:
impl.suspect((Address)evt.getArg());
break; // pass up
case Event.UNSUSPECT:
impl.unsuspect((Address)evt.getArg());
return; // discard
case Event.MERGE:
impl.merge((Vector)evt.getArg());
return; // don't pass up
}
if(impl.handleUpEvent(evt))
passUp(evt);
}
/**
This method is overridden to avoid hanging on getDigest(): when a JOIN is received, the coordinator needs
to retrieve the digest from the PBCAST layer. It therefore sends down a GET_DIGEST event, to which the PBCAST layer
responds with a GET_DIGEST_OK event.<p>
However, the GET_DIGEST_OK event will not be processed because the thread handling the JOIN request won't process
the GET_DIGEST_OK event until the JOIN event returns. The receiveUpEvent() method is executed by the up-handler
thread of the lower protocol and therefore can handle the event. All we do here is unblock the mutex on which
JOIN is waiting, allowing JOIN to return with a valid digest. The GET_DIGEST_OK event is then discarded, because
it won't be processed twice.
*/
public void receiveUpEvent(Event evt) {
if(evt.getType() == Event.GET_DIGEST_OK) {
synchronized(digest_mutex) {
digest=(Digest)evt.getArg();
digest_mutex.notifyAll();
}
return;
}
super.receiveUpEvent(evt);
}
public void down(Event evt) {
switch(evt.getType()) {
case Event.CONNECT:
passDown(evt);
try {
group_addr=(String)evt.getArg();
}
catch(ClassCastException cce) {
Trace.error("GMS.down()", "[CONNECT]: group address must be a string (channel name)");
}
if(local_addr == null)
Trace.fatal("GMS.down()", "[CONNECT] local_addr is null");
impl.join(local_addr);
passUp(new Event(Event.CONNECT_OK));
return; // don't pass down: was already passed down
case Event.DISCONNECT:
impl.leave((Address)evt.getArg());
passUp(new Event(Event.DISCONNECT_OK));
initState(); // in case connect() is called again
break; // pass down
}
if(impl.handleDownEvent(evt))
passDown(evt);
}
/** Setup the Protocol instance according to the configuration string */
public boolean setProperties(Properties props) {
String str;
str=props.getProperty("shun");
if(str != null) {
shun=new Boolean(str).booleanValue();
props.remove("shun");
}
str=props.getProperty("print_local_addr");
if(str != null) {
print_local_addr=new Boolean(str).booleanValue();
props.remove("print_local_addr");
}
str=props.getProperty("join_timeout"); // time to wait for JOIN
if(str != null) {
join_timeout=new Long(str).longValue();
props.remove("join_timeout");
}
str=props.getProperty("join_retry_timeout"); // time to wait between JOINs
if(str != null) {
join_retry_timeout=new Long(str).longValue();
props.remove("join_retry_timeout");
}
str=props.getProperty("leave_timeout"); // time to wait until coord responds to LEAVE req.
if(str != null) {
leave_timeout=new Long(str).longValue();
props.remove("leave_timeout");
}
str=props.getProperty("merge_timeout"); // time to wait for MERGE_RSPS from subgroup coordinators
if(str != null) {
merge_timeout=new Long(str).longValue();
props.remove("merge_timeout");
}
str=props.getProperty("digest_timeout"); // time to wait for GET_DIGEST_OK from PBCAST
if(str != null) {
digest_timeout=new Long(str).longValue();
props.remove("digest_timeout");
}
str=props.getProperty("disable_initial_coord");
if(str != null) {
disable_initial_coord=new Boolean(str).booleanValue();
props.remove("disable_initial_coord");
}
str=props.getProperty("num_prev_mbrs");
if(str != null) {
num_prev_mbrs=Integer.parseInt(str);
props.remove("num_prev_mbrs");
}
if(props.size() > 0) {
System.err.println("GMS.setProperties(): the following properties are not recognized:");
props.list(System.out);
return false;
}
return true;
}
void initState() {
becomeClient();
view_id=null;
}
void handleJoinRequest(Address mbr) {
JoinRsp join_rsp;
Message m;
GmsHeader hdr;
if(mbr == null) {
if(Trace.trace)
Trace.error("GMS.handleJoinRequest()", "mbr is null");
return;
}
if(Trace.trace)
Trace.debug("GMS.handleJoinRequest()", "mbr=" + mbr);
// 1. Get the new view and digest
join_rsp=impl.handleJoin(mbr);
if(join_rsp == null)
Trace.error("GMS.handleJoinRequest()", impl.getClass().toString() + ".handleJoin(" + mbr +
") returned null: will not be able to multicast new view");
// 2. Send down a local TMP_VIEW event. This is needed by certain layers (e.g. NAKACK) to compute correct digest
// in case client's next request (e.g. getState()) reaches us *before* our own view change multicast.
// Check NAKACK's TMP_VIEW handling for details
if(join_rsp != null && join_rsp.getView() != null)
passDown(new Event(Event.TMP_VIEW, join_rsp.getView()));
// 3. Return result to client
m=new Message(mbr, null, null);
hdr=new GmsHeader(GmsHeader.JOIN_RSP, join_rsp);
m.putHeader(getName(), hdr);
passDown(new Event(Event.MSG, m));
// 4. Bcast the new view
if(join_rsp != null)
castViewChange(join_rsp.getView());
}
void sendLeaveResponse(Address mbr) {
Message msg=new Message(mbr, null, null);
GmsHeader hdr=new GmsHeader(GmsHeader.LEAVE_RSP);
msg.putHeader(getName(), hdr);
passDown(new Event(Event.MSG, msg));
}
public static class GmsHeader extends Header {
public static final int JOIN_REQ=1;
public static final int JOIN_RSP=2;
public static final int LEAVE_REQ=3;
public static final int LEAVE_RSP=4;
public static final int VIEW=5;
public static final int MERGE_REQ=6;
public static final int MERGE_RSP=7;
public static final int INSTALL_MERGE_VIEW=8;
public static final int CANCEL_MERGE=9;
int type=0;
View view=null; // used when type=VIEW or MERGE_RSP or INSTALL_MERGE_VIEW
Address mbr=null; // used when type=JOIN_REQ or LEAVE_REQ
JoinRsp join_rsp=null; // used when type=JOIN_RSP
Digest digest=null; // used when type=MERGE_RSP or INSTALL_MERGE_VIEW
Serializable merge_id=null; // used when type=MERGE_REQ or MERGE_RSP or INSTALL_MERGE_VIEW or CANCEL_MERGE
boolean merge_rejected=false; // used when type=MERGE_RSP
public GmsHeader() {
} // used for Externalization
public GmsHeader(int type) {
this.type=type;
}
/** Used for VIEW header */
public GmsHeader(int type, View view) {
this.type=type;
this.view=view;
}
/** Used for JOIN_REQ or LEAVE_REQ header */
public GmsHeader(int type, Address mbr) {
this.type=type;
this.mbr=mbr;
}
/** Used for JOIN_RSP header */
public GmsHeader(int type, JoinRsp join_rsp) {
this.type=type;
this.join_rsp=join_rsp;
}
public String toString() {
StringBuffer sb=new StringBuffer("GmsHeader");
sb.append("[" + type2String(type) + "]");
switch(type) {
case JOIN_REQ:
sb.append(": mbr=" + mbr);
break;
case JOIN_RSP:
sb.append(": join_rsp=" + join_rsp);
break;
case LEAVE_REQ:
sb.append(": mbr=" + mbr);
break;
case LEAVE_RSP:
break;
case VIEW:
sb.append(": view=" + view);
break;
case MERGE_REQ:
sb.append(": merge_id=" + merge_id);
break;
case MERGE_RSP:
sb.append(": view=" + view + ", digest=" + digest + ", merge_rejected=" + merge_rejected +
", merge_id=" + merge_id);
break;
case INSTALL_MERGE_VIEW:
sb.append(": view=" + view + ", digest=" + digest);
break;
case CANCEL_MERGE:
sb.append(", <merge cancelled>, merge_id=" + merge_id);
break;
}
sb.append("\n");
return sb.toString();
}
public static String type2String(int type) {
switch(type) {
case JOIN_REQ:
return "JOIN_REQ";
case JOIN_RSP:
return "JOIN_RSP";
case LEAVE_REQ:
return "LEAVE_REQ";
case LEAVE_RSP:
return "LEAVE_RSP";
case VIEW:
return "VIEW";
case MERGE_REQ:
return "MERGE_REQ";
case MERGE_RSP:
return "MERGE_RSP";
case INSTALL_MERGE_VIEW:
return "INSTALL_MERGE_VIEW";
case CANCEL_MERGE:
return "CANCEL_MERGE";
default:
return "<unknown>";
}
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(type);
out.writeObject(view);
out.writeObject(mbr);
out.writeObject(join_rsp);
out.writeObject(digest);
out.writeObject(merge_id);
out.writeBoolean(merge_rejected);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type=in.readInt();
view=(View)in.readObject();
mbr=(Address)in.readObject();
join_rsp=(JoinRsp)in.readObject();
digest=(Digest)in.readObject();
merge_id=(Serializable)in.readObject();
merge_rejected=in.readBoolean();
}
}
}
|
/*
* $Id: RepairCrawler.java,v 1.16 2004-03-10 22:20:13 troberts Exp $
*/
package org.lockss.crawler;
import java.util.*;
import java.net.*;
import java.io.*;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.util.urlconn.*;
import org.lockss.daemon.*;
import org.lockss.protocol.*;
import org.lockss.proxy.ProxyManager;
import org.lockss.plugin.*;
import org.lockss.plugin.base.*;
import org.lockss.state.*;
public class RepairCrawler extends CrawlerImpl {
private static Logger logger = Logger.getLogger("RepairCrawler");
private IdentityManager idMgr = null;
protected Collection repairUrls = null;
public static final String PARAM_FETCH_FROM_OTHER_CACHE =
Configuration.PREFIX + "crawler.fetch_from_other_caches";
private float percentFetchFromCache = 0;
public RepairCrawler(ArchivalUnit au, CrawlSpec spec,
AuState aus, Collection repairUrls,
float percentFetchFromCache) {
super(au, spec, aus);
if (repairUrls == null) {
throw new IllegalArgumentException("Called with null repairUrls");
} else if (repairUrls.size() == 0) {
throw new IllegalArgumentException("Called with empty repairUrls list");
}
this.repairUrls = repairUrls;
this.percentFetchFromCache = percentFetchFromCache;
crawlStatus = new Crawler.Status(au, repairUrls, getType());
}
public int getType() {
return Crawler.REPAIR;
}
protected Iterator getStartingUrls() {
return repairUrls.iterator();
}
protected boolean doCrawl0() {
boolean windowClosed = false;
logger.info("Beginning crawl of "+au);
crawlStatus.signalCrawlStarted();
CachedUrlSet cus = au.getAuCachedUrlSet();
Iterator it = getStartingUrls();
while (it.hasNext() && !crawlAborted) {
String url = (String)it.next();
//catch and warn if there's a url in the start urls
//that we shouldn't cache
// check crawl window during crawl
if ((spec!=null) && (!spec.canCrawl())) {
logger.debug("Crawl canceled: outside of crawl window");
windowClosed = true;
// break from while loop
break;
}
if (spec.isIncluded(url)) {
boolean crawlRes = false;
try {
crawlRes = doCrawlLoop(url, cus);
} catch (RuntimeException e) {
logger.warning("Unexpected exception in crawl", e);
}
if (!crawlRes) {
if (crawlStatus.getCrawlError() == 0) {
crawlStatus.setCrawlError(Crawler.STATUS_ERROR);
}
}
} else {
logger.warning("Called with a starting url we aren't suppose to "+
"cache: "+url);
}
if (windowClosed) {
// break from for loop
break;
}
}
// unsuccessful crawl if window closed
if (windowClosed) {
crawlStatus.setCrawlError(Crawler.STATUS_WINDOW_CLOSED);
}
if (crawlStatus.getCrawlError() != 0) {
logger.info("Finished crawl (errors) of "+au);
} else {
logger.info("Finished crawl of "+au);
}
if (au instanceof BaseArchivalUnit) {
BaseArchivalUnit bau = (BaseArchivalUnit)au;
long cacheHits = bau.getCrawlSpecCacheHits();
long cacheMisses = bau.getCrawlSpecCacheMisses();
double per = ((float)cacheHits /
((float)cacheHits + (float)cacheMisses));
logger.info("Had "+cacheHits+" cache hits, with a percentage of "+per);
}
return (crawlStatus.getCrawlError() == 0);
}
protected boolean doCrawlLoop(String url, CachedUrlSet cus) {
int error = 0;
logger.debug2("Dequeued url from list: "+url);
UrlCacher uc = makeUrlCacher(cus, url);
// don't cache if already cached, unless overwriting
try {
if (wdog != null) {
wdog.pokeWDog();
}
if (shouldFetchFromCache()) {
try {
logger.debug3("Trying to fetch from a cache");
fetchFromCache(uc);
} catch (CantProxyException e) {
logger.debug3("Failed, so trying to fetch from publisher");
cache(uc);
}
} else {
logger.debug3("Trying to fetch from publisher");
cache(uc);
}
numUrlsFetched++;
} catch (FileNotFoundException e) {
logger.warning(uc+" not found on publisher's site");
} catch (IOException ioe) {
//XXX handle this better. Requeue?
logger.error("Problem caching "+uc+". Ignoring", ioe);
error = Crawler.STATUS_FETCH_ERROR;
}
return (error == 0);
}
private boolean shouldFetchFromCache() {
return ProbabilisticChoice.choose(percentFetchFromCache);
}
protected void fetchFromCache(UrlCacher uc) throws IOException {
IdentityManager idm = getIdentityManager();
Map map = idm.getAgreed(au);
Iterator it = map.keySet().iterator();
if (it.hasNext()) {
fetchFromCache(uc, (String)it.next());
}
}
protected void fetchFromCache(UrlCacher uc, String id)
throws IOException {
ProxyManager proxyMan =
(ProxyManager)LockssDaemon.getManager(LockssDaemon.PROXY_MANAGER);
int proxyPort = proxyMan.getProxyPort();
// XXX fix this to use BaseUrlCacher
LockssUrlConnection conn = UrlUtil.openConnection(uc.getUrl(),
connectionPool);
if (!conn.canProxy()) {
throw new CantProxyException();
}
conn.setProxy(id, proxyPort);
conn.setRequestProperty("user-agent", LockssDaemon.getUserAgent());
conn.execute();
logger.debug("Trying to fetch from "+id);
uc.storeContent(conn.getResponseInputStream(),
getPropertiesFromConn(conn, uc.getUrl(), id));
}
// XXX fix this to use BaseUrlCacher
private CIProperties getPropertiesFromConn(LockssUrlConnection conn,
String url, String id)
throws IOException {
CIProperties props = new CIProperties();
// set header properties in which we have interest
props.setProperty(CachedUrl.PROPERTY_CONTENT_TYPE,
conn.getResponseContentType());
props.setProperty(CachedUrl.PROPERTY_FETCH_TIME,
Long.toString(TimeBase.nowMs()));
props.setProperty(CachedUrl.PROPERTY_ORIG_URL, url);
props.setProperty(CachedUrl.PROPERTY_REPAIR_FROM, id);
conn.storeResponseHeaderInto(props, CachedUrl.HEADER_PREFIX);
String actualURL = conn.getActualUrl();
if (!url.equals(actualURL)) {
logger.info("setProperty(\"redirected-to\", " + actualURL + ")");
props.setProperty(CachedUrl.PROPERTY_REDIRECTED_TO, actualURL);
}
return props;
}
private void cache(UrlCacher uc) throws IOException {
try {
uc.setForceRefetch(true);
uc.cache();
} catch (IOException e) {
logger.debug("Exception when trying to cache "+uc, e);
}
}
private IdentityManager getIdentityManager() {
if (idMgr == null) {
idMgr =
(IdentityManager)LockssDaemon.getManager(LockssDaemon.IDENTITY_MANAGER);
}
return idMgr;
}
static class CantProxyException extends IOException {
}
}
|
package org.eclipse.kura.web.client.ui.drivers.assets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.kura.web.client.messages.Messages;
import org.eclipse.kura.web.client.ui.AlertDialog;
import org.eclipse.kura.web.client.ui.EntryClassUi;
import org.eclipse.kura.web.client.ui.drivers.assets.AssetModel.ChannelModel;
import org.eclipse.kura.web.client.util.FailureHandler;
import org.eclipse.kura.web.shared.AssetConstants;
import org.eclipse.kura.web.shared.model.GwtChannelRecord;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.PanelBody;
import org.gwtbootstrap3.client.ui.gwt.CellTable;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.cell.client.TextInputCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.DefaultHeaderOrFooterBuilder;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextHeader;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
public class AssetDataUi extends Composite {
private static AssetDataUiBinder uiBinder = GWT.create(AssetDataUiBinder.class);
interface AssetDataUiBinder extends UiBinder<Widget, AssetDataUi> {
}
protected static final Messages MSGS = GWT.create(Messages.class);
private static final int MAXIMUM_PAGE_SIZE = 5;
private final ListDataProvider<AssetModel.ChannelModel> channelsDataProvider = new ListDataProvider<>();
private final SingleSelectionModel<AssetModel.ChannelModel> selectionModel = new SingleSelectionModel<>();
private AssetModel model;
private final Map<String, GwtChannelRecord> channelValues = new HashMap<>();
private final Set<String> modifiedWriteChannels = new HashSet<>();
private final TextInputCell valuesCell = new TextInputCell();
@UiField
PanelBody configurationPanelBody;
@UiField
Button applyDataChanges;
@UiField
Button refreshData;
@UiField
CellTable<AssetModel.ChannelModel> assetDataTable;
@UiField
SimplePager channelPager;
@UiField
AlertDialog alertDialog;
public AssetDataUi(AssetModel model) {
initWidget(uiBinder.createAndBindUi(this));
this.channelPager.setPageSize(MAXIMUM_PAGE_SIZE);
this.channelPager.setDisplay(this.assetDataTable);
this.assetDataTable.setSelectionModel(this.selectionModel);
this.channelsDataProvider.addDataDisplay(this.assetDataTable);
this.model = model;
initButtons();
initTable();
}
public void setModel(AssetModel model) {
this.model = model;
}
private void initButtons() {
this.applyDataChanges.addClickHandler(event -> write());
this.refreshData.addClickHandler(event -> renderForm());
this.applyDataChanges.setEnabled(false);
}
private void initTable() {
this.assetDataTable.setHeaderBuilder(
new DefaultHeaderOrFooterBuilder<AssetModel.ChannelModel>(this.assetDataTable, false));
this.assetDataTable.addColumn(new StaticColumn(AssetConstants.NAME.value()),
new TextHeader(MSGS.wiresChannelName()));
this.assetDataTable.addColumn(new StaticColumn(AssetConstants.TYPE.value()),
new TextHeader(MSGS.wiresChannelOperation()));
this.assetDataTable.addColumn(new StaticColumn(AssetConstants.VALUE_TYPE.value()),
new TextHeader(MSGS.wiresChannelValueType()));
final Column<AssetModel.ChannelModel, String> statusColumn = new Column<AssetModel.ChannelModel, String>(
new StatusCell()) {
@Override
public void onBrowserEvent(Context context, Element elem, ChannelModel object, NativeEvent event) {
if (getChannelStatus(object) == ChannelStatus.FAILURE) {
final GwtChannelRecord record = channelValues.get(object.getChannelName());
showFailureDetails(record);
}
}
@Override
public String getValue(final AssetModel.ChannelModel object) {
return getChannelStatus(object).getLabel();
}
@Override
public String getCellStyleNames(Context context, ChannelModel object) {
return getChannelStatus(object).getCellStyle();
}
@Override
public void render(final Context context, final ChannelModel object, final SafeHtmlBuilder sb) {
final ChannelStatus status = getChannelStatus(object);
sb.append(() -> "<i class=\"fa assets-status-icon " + status.getIconStyle() + "\"></i><span>"
+ SafeHtmlUtils.htmlEscape(getValue(object)) + "</span>");
}
};
this.assetDataTable.addColumn(statusColumn, new TextHeader(MSGS.wiresChannelStatus()));
final Column<AssetModel.ChannelModel, String> valueColumn = new Column<AssetModel.ChannelModel, String>(
valuesCell) {
@Override
public void onBrowserEvent(Context context, Element elem, ChannelModel object, NativeEvent event) {
if (!"READ".equals(object.getValue(AssetConstants.TYPE.value()))) {
super.onBrowserEvent(context, elem, object, event);
}
}
@Override
public String getCellStyleNames(Context context, ChannelModel object) {
if (getChannelStatus(object) == ChannelStatus.FAILURE) {
return "cell-readonly";
}
return null;
}
@Override
public String getValue(final AssetModel.ChannelModel object) {
if (getChannelStatus(object) == ChannelStatus.SUCCESS) {
final GwtChannelRecord result = channelValues.get(object.getChannelName());
return result.getValue();
}
return "Not available";
}
@Override
public void render(Context context, ChannelModel object, SafeHtmlBuilder sb) {
if ("READ".equals(object.getValue(AssetConstants.TYPE.value()))) {
sb.appendEscaped(getValue(object));
return;
}
if (!isDirty(object.getChannelName())) {
valuesCell.clearViewData(context.getKey());
}
super.render(context, object, sb);
}
};
valueColumn.setFieldUpdater((index, object, value) -> {
final String channelName = object.getChannelName();
GwtChannelRecord result = createWriteRecord(object);
result.setValue(value);
channelValues.put(channelName, result);
markAsDirty(channelName);
AssetDataUi.this.assetDataTable.redraw();
});
this.assetDataTable.addColumn(valueColumn, new TextHeader(MSGS.devicePropValue()));
}
private static void showFailureDetails(final GwtChannelRecord record) {
record.setUnescaped(true);
String reason = record.getExceptionMessage();
record.setUnescaped(false);
if (reason == null || reason.trim().isEmpty()) {
reason = "unknown";
}
FailureHandler.showErrorMessage("Channel failure details", "Reason: " + reason,
record.getExceptionStackTrace());
}
private GwtChannelRecord createWriteRecord(AssetModel.ChannelModel channel) {
final GwtChannelRecord result = new GwtChannelRecord();
result.setName(channel.getChannelName());
result.setValueType(channel.getValue(AssetConstants.VALUE_TYPE.value()));
return result;
}
private void write() {
if (!isDirty()) {
return;
}
final ArrayList<GwtChannelRecord> writeRecords = new ArrayList<>();
for (final String channelName : modifiedWriteChannels) {
final GwtChannelRecord record = channelValues.get(channelName);
if (record == null) {
continue;
}
writeRecords.add(record);
}
if (writeRecords.isEmpty()) {
return;
}
alertDialog.show(MSGS.driversAssetsWriteConfirm(model.getAssetPid()),
() -> DriversAndAssetsRPC.write(model.getAssetPid(), writeRecords, result -> {
final List<GwtChannelRecord> records = result.getRecords();
if (records != null) {
AssetDataUi.this.setDirty(false);
for (GwtChannelRecord channelRecord : records) {
channelValues.put(channelRecord.getName(), channelRecord);
}
AssetDataUi.this.channelsDataProvider.refresh();
AssetDataUi.this.assetDataTable.redraw();
} else {
FailureHandler.showErrorMessage("Channel operation failed", result.getExceptionMessage(),
result.getStackTrace());
}
}));
}
private boolean isDirty(final String channelName) {
return modifiedWriteChannels.contains(channelName);
}
private void markAsDirty(final String channelName) {
AssetDataUi.this.modifiedWriteChannels.add(channelName);
AssetDataUi.this.applyDataChanges.setEnabled(true);
}
public void setDirty(boolean flag) {
if (!flag) {
this.modifiedWriteChannels.clear();
}
if (this.isDirty()) {
this.applyDataChanges.setEnabled(true);
}
}
public boolean isDirty() {
return !this.modifiedWriteChannels.isEmpty();
}
public void renderForm() {
this.setDirty(false);
this.channelValues.clear();
this.applyDataChanges.setEnabled(false);
this.channelsDataProvider.getList().clear();
this.channelsDataProvider.refresh();
EntryClassUi.showWaitModal();
DriversAndAssetsRPC.readAllChannels(model.getAssetPid(), result -> {
final List<GwtChannelRecord> records = result.getRecords();
if (records != null) {
for (final GwtChannelRecord record : records) {
record.setUnescaped(true);
channelValues.put(record.getName(), record);
}
AssetDataUi.this.channelsDataProvider.getList().addAll(model.getChannels());
AssetDataUi.this.channelsDataProvider.refresh();
int size = AssetDataUi.this.channelsDataProvider.getList().size();
AssetDataUi.this.assetDataTable.setVisibleRange(0, size);
AssetDataUi.this.assetDataTable.redraw();
} else {
FailureHandler.showErrorMessage("Channel operation failed", result.getExceptionMessage(),
result.getStackTrace());
}
});
}
private ChannelStatus getChannelStatus(final ChannelModel model) {
final String channelName = model.getChannelName();
final GwtChannelRecord record = channelValues.get(model.getChannelName());
if ("false".equals(model.getValue(AssetConstants.ENABLED.value()))) {
return ChannelStatus.DISABLED;
} else if (modifiedWriteChannels.contains(channelName)) {
return ChannelStatus.DIRTY;
} else if (record == null) {
return ChannelStatus.UNKNOWN;
} else if (record.getValue() == null) {
return ChannelStatus.FAILURE;
} else {
return ChannelStatus.SUCCESS;
}
}
private static final class StaticColumn extends Column<AssetModel.ChannelModel, String> {
private final String key;
public StaticColumn(final String key) {
super(new TextCell());
this.key = key;
}
@Override
public String getValue(final AssetModel.ChannelModel object) {
return object.getValue(key);
}
}
private static final class StatusCell extends TextCell {
@Override
public Set<String> getConsumedEvents() {
final HashSet<String> set = new HashSet<>();
set.add(BrowserEvents.CLICK);
return set;
}
}
private enum ChannelStatus {
UNKNOWN("Unknown", "fa-times text-danger", "text-danger"),
SUCCESS("Success", "fa-check text-success", "text-success"),
FAILURE("Failure - click for details", "fa-times text-danger", "text-danger cell-clickable"),
DIRTY("Modified", "fa-pencil", ""),
DISABLED("Disabled", "", "");
private String label;
private String iconStyle;
private String cellStyle;
private ChannelStatus(final String label, final String iconStyle, final String cellStyle) {
this.label = label;
this.iconStyle = iconStyle;
this.cellStyle = cellStyle;
}
public String getLabel() {
return label;
}
public String getIconStyle() {
return iconStyle;
}
public String getCellStyle() {
return cellStyle;
}
}
}
|
package org.tappe.excel.schema;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Component;
@Component
public class ExcelTool {
private Logger logger = Logger.getLogger(this.getClass());
private static Map<Integer, ToolXmlBean> template = LoadXmlInfo.getData();
private static DecimalFormat df = new DecimalFormat("0.00");
private static String dataFormat = "yyyy-MM-dd";
private Workbook book;
private static SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
public static void setDataFormat(String dataFormat) {
ExcelTool.sdf = new SimpleDateFormat(dataFormat);
}
private static CellStyle cellStyle = null;
private static String stringCode = "UTF-8";
public static void setEncodeType(String code) {
stringCode = code;
}
public static void setCellStyle(CellStyle style) {
cellStyle = style;
}
private static String exp = "(\\{\\s*(\\w*[.]{0,1})\\w+\\s*\\})";
private static Pattern pattern = Pattern.compile(exp);
private static String blank = "";
private Map<String, Object> titleMap = new HashMap<String, Object>();
private Map<Integer, Object> bodyMap = new HashMap<Integer, Object>();
public ByteArrayOutputStream export(Object title, List<?> data, int index) {
ToolXmlBean bean = template.get(index);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
init(title, data, bean);
setData(title, data, bean);
book.write(os);
} catch (IOException e) {
e.printStackTrace();
}
return os;
}
private void init(Object title, List<?> data, ToolXmlBean bean) {
long st1 = System.currentTimeMillis();
try {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream(bean.getPath());
book = WorkbookFactory.create(stream);
} catch (Exception e1) {
logger.error(e1.getMessage() + "\t" + e1.getCause());
e1.printStackTrace();
}
long st2 = System.currentTimeMillis();
System.out.println((st2 - st1) + "ms ::: init time");
if (title != null) {
Field[] fieldTiles = title.getClass().getDeclaredFields();
for (Field field : fieldTiles) {
try {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), title.getClass());
Method readMethod = pd.getReadMethod();
Object value = readMethod.invoke(title);
titleMap.put(field.getName(), valueToString(pd.getReadMethod(), value));
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
if (bean.getPath() != null) {
Row row = book.getSheetAt(0).getRow(bean.getSplitLine());
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell != null && hasField(cell)) {
bodyMap.put(i, getFieldExp(cell.getStringCellValue()));
cell.setCellValue(blank);
}
}
}
}
private String valueToString(Method method, Object obj) {
if (obj == null)
return "";
Class<?> getClass = method.getReturnType();
if (String.class.equals(getClass)) {
return (String) obj;
}
if (Long.class.equals(getClass) || Integer.class.equals(getClass) || Boolean.class.equals(getClass)) {
return obj.toString();
}
if (Double.class.equals(getClass)) {
return convertDouble((Double) obj).toString();
}
if (Date.class.equals(getClass)) {
return sdf.format(obj);
} else {
return obj + blank;
}
}
private String valueToString(Object obj) {
if (obj == null) {
return blank;
}
Class<?> getClass = obj.getClass();
if (String.class.equals(getClass)) {
return (String) obj;
}
if (Long.class.equals(getClass) || Integer.class.equals(getClass) || Boolean.class.equals(getClass)) {
return obj.toString();
}
if (Double.class.equals(getClass)) {
return convertDouble((Double) obj).toString();
}
if (Date.class.equals(getClass)) {
return sdf.format(obj);
} else {
return obj + blank;
}
}
private Double convertDouble(Double value) {
long l1 = Math.round(value * 100);
Double ret = l1 / 100.0;
return ret;
}
private Object getFieldExp(String stringCellValue) {
int point;
String half = "\\w";
if ((point = stringCellValue.indexOf(".")) > 0) {
half = stringCellValue.substring(point + 1, stringCellValue.indexOf("}")).trim();
} else {
half = stringCellValue.substring(stringCellValue.indexOf("{") + 1, stringCellValue.indexOf("}")).trim();
}
// inField.put(half, "(\\{\\s*(\\w*[.]{0,1})(" + half + ")\\s*\\})");
return half;
}
private String getField(String orglStr) {
int point = orglStr.indexOf(".");
if (point > 0) {
orglStr = orglStr.substring(point + 1, orglStr.indexOf("}")).trim();
} else {
orglStr = orglStr.substring(orglStr.indexOf("{") + 1, orglStr.indexOf("}")).trim();
}
return orglStr;
}
private boolean hasField(Cell cell) {
String value = cell.getStringCellValue();
if (value == null || blank.equals(value)) {
return false;
}
Matcher matcher = pattern.matcher(value);
return matcher.find();
}
private void setData(Object title, List<?> data, ToolXmlBean bean) {
long st1 = System.currentTimeMillis();
if (bean == null || bean.getPath() == null)
return;
int line = bean.getSplitLine();
Sheet sheet = book.getSheetAt(0);
// setTitle
for (int i = 0; i < line; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
if (cell != null) {
replaceValue(cell);
}
}
}
// setBody
if (data != null && data.size() > 0) {
Field[] fields = data.get(0).getClass().getDeclaredFields();
Map<String, Method> fieldMap = new HashMap<String, Method>();
try {
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), data.get(0).getClass());
fieldMap.put(field.getName(), pd.getReadMethod());
}
for (int i = line; i < data.size() + line; i++) {
Row row = sheet.createRow(i);
for (Integer index : bodyMap.keySet()) {
Cell cell = row.createCell(index);
Object dataObj = data.get(i - line);
String fieldName = (String) bodyMap.get(index);
Method readMethod = fieldMap.get(fieldName);
String value = valueToString(readMethod, readMethod.invoke(dataObj));
// put list data
cell.setCellValue(value);
cell.setCellStyle(cellStyle);
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
long st2 = System.currentTimeMillis();
System.out.println((st2 - st1) + "ms :::: setData time!!!");
}
private void replaceValue(Cell cell) {
if (hasField(cell)) {
String field = getField(cell.getStringCellValue());
Object value = titleMap.get(field);
if (value == null) {
value = blank;
}
String newValue = cell.getStringCellValue().replaceAll("(\\{\\s*(\\w*[.]{0,1})(" + field + ")\\s*\\})",
(String) value);
cell.setCellValue(newValue);
}
}
public void exportByMap(Object title, List<Map<?, ?>> data, int index, HttpServletResponse response)
throws IOException {
ToolXmlBean bean = template.get(index);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Long initTime = System.currentTimeMillis();
init(title, data, bean);
setMapData(title, data, bean);
book.write(os);
Long endTime = System.currentTimeMillis();
logger.info("export excel in " + (df.format((endTime - initTime) * 1.0 / 1000)) + " S ");
} catch (IOException e) {
e.printStackTrace();
}
response.setContentLength(os.size());
response.setCharacterEncoding(stringCode);
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(bean.getFileName(), stringCode));
OutputStream outputStream = response.getOutputStream();
outputStream.write(os.toByteArray());
outputStream.close();
}
private void setMapData(Object title, List<Map<?, ?>> data, ToolXmlBean bean) {
long st1 = System.currentTimeMillis();
if (bean == null || bean.getPath() == null)
return;
int line = bean.getSplitLine();
Sheet sheet = book.getSheetAt(0);
// setTitle
for (int i = 0; i < line; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
if (cell != null) {
replaceValue(cell);
}
}
}
// setBody
if (data != null && data.size() > 0) {
Field[] fields = data.get(0).getClass().getDeclaredFields();
Map<String, Method> fieldMap = new HashMap<String, Method>();
try {
// for (Field field : fields) {
// PropertyDescriptor pd = new PropertyDescriptor(field.getName(), data.get(0).getClass());
// fieldMap.put(field.getName(), pd.getReadMethod());
for (int i = line; i < data.size() + line; i++) {
Row row = sheet.createRow(i);
Map<?, ?> rowsData = data.get(i-line);
for (Integer index : bodyMap.keySet()) {
Cell cell = row.createCell(index);
String fieldName = (String) bodyMap.get(index);
Object value = rowsData.get(fieldName);
String stringValue = valueToString(value);
cell.setCellValue(stringValue);
cell.setCellStyle(cellStyle);
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
long st2 = System.currentTimeMillis();
System.out.println((st2 - st1) + "ms :::: setData time!!!");
}
public void export(Object title, List<?> data, int index, HttpServletResponse response) throws IOException {
ToolXmlBean bean = template.get(index);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Long initTime = System.currentTimeMillis();
init(title, data, bean);
setData(title, data, bean);
book.write(os);
Long endTime = System.currentTimeMillis();
logger.info("export excel in " + (df.format((endTime - initTime) * 1.0 / 1000)) + " S ");
} catch (IOException e) {
e.printStackTrace();
}
response.setContentLength(os.size());
response.setCharacterEncoding(stringCode);
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(bean.getFileName(), stringCode));
OutputStream outputStream = response.getOutputStream();
outputStream.write(os.toByteArray());
outputStream.close();
}
public static String PropertyStr(Class<?> beanClass) {
Field[] fields = beanClass.getDeclaredFields();
String result = blank;
for (Field field : fields) {
result += "{" + field.getName() + "} \t";
}
return result;
}
}
|
package org.languagetool.rules.pt;
import java.util.Arrays;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.UserConfig;
import org.languagetool.rules.AbstractFillerWordsRule;
/**
* A rule that gives hints on the use of Portuguese filler words.
* The hints are only given when the percentage of filler words per paragraph exceeds the given limit.
* A limit of 0 shows all used filler words. Direct speech or citation is excluded otherwise.
* This rule detects no grammar error but gives stylistic hints (default off).
* @author Fred Kruse
* @since 4.2
*/
public class PortugueseFillerWordsRule extends AbstractFillerWordsRule {
private static final Set<String> fillerWords = new HashSet<>(Arrays.asList( "abundante", "acrescentou", "acrescidamente",
"adição", "agora", "ainda", "além", "algo", "algum", "alguma", "algumas", "alguns", "aparecer",
"aparentemente", "apenas", "apesar", "aproximadamente", "assim", "atrás", "atualmente", "automaticamente",
"bem", "bonito", "certamente", "certo", "claramente", "claro", "completam", "completamente", "completo",
"comumente", "consequentemente", "consistentemente", "continuamente", "contra", "contraste", "contudo",
"cuidado", "curto", "dependendo", "depois", "desigual", "determinado", "deve", "dever", "difícil",
"direito", "dúvida", "embora", "enquanto", "entanto", "ergo", "especial", "estranhamente", "eventualmente",
"evidentemente", "expressar", "extremamente", "fácil", "famoso", "feio", "felizmente", "francamente",
"frequência", "frequentemente", "geralmente", "graças", "impressionante", "impronunciável", "incomum",
"indizível", "infelizmente", "irrelevante", "irrelevantes", "já", "justo", "lento", "longo", "lugares",
"maior", "mais", "mas", "melhor", "mesmo", "muita", "muitas", "muito", "muitos", "múltipla", "nada", "não",
"natural", "naturalmente", "natureza", "nehumas", "nenhum", "nenhuma", "nenhuns", "nomeadamente",
"normalmente", "novo", "número", "nunca", "óbvio", "ocasionalmente", "outra", "outros", "para", "parente",
"particularmente", "pessoa", "pode", "poderia", "pois", "porém", "porque", "portanto", "possível",
"possivelmente", "pouca", "poucas", "pouco", "poucos", "prático", "precisas", "principalmente", "provável",
"provavelmente", "quaisquer", "qualquer", "quase", "rápido", "raramente", "razoavelmente", "realmente",
"recentemente", "relativamente", "repente", "sempre", "senão", "sentida", "sentidas", "sentido", "sentidos",
"siga", "significativo", "sim", "simples", "simplesmente", "sobre", "sozinho", "suave", "suavemente",
"substancialmente", "suficientemente", "tipo", "tornar", "tornaram", "tornou", "total", "totalmente",
"toda", "todas", "todo", "todos", "tudo", "ultrajante", "velho", "verdade", "vez", "vezes", "volta"
));
public PortugueseFillerWordsRule(ResourceBundle messages, UserConfig userConfig) {
super(messages, userConfig);
}
@Override
public String getId() {
return RULE_ID + "_PT";
}
@Override
protected boolean isFillerWord(String token) {
return fillerWords.contains(token);
}
@Override
public boolean isException(AnalyzedTokenReadings[] tokens, int num) {
if ("mas".equals(tokens[num].getToken()) && num >= 2 && ",".equals(tokens[num - 2].getToken())) {
return true;
}
return false;
}
}
|
package org.jgroups.tests;
import org.jgroups.Global;
import org.jgroups.Message;
import org.jgroups.util.RetransmitTable;
import org.jgroups.util.Util;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
/** Tests {@link org.jgroups.util.RetransmitTable}
* @author Bela Ban
*/
@Test(groups=Global.FUNCTIONAL,sequential=false)
public class RetransmitTableTest {
static final Message MSG=new Message(null, null, "test");
public static void testCreation() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
int size=table.size();
assert size == 0;
assert table.get(15) == null;
}
public static void testAddition() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
addAndGet(table, 0, "0");
addAndGet(table, 1, "1");
addAndGet(table, 5, "5");
addAndGet(table, 9, "9");
addAndGet(table, 10, "10");
addAndGet(table, 11, "11");
addAndGet(table, 19, "19");
addAndGet(table, 20, "20");
addAndGet(table, 29, "29");
System.out.println("table: " + table.dump());
assert table.size() == 9;
assert table.size() == table.computeSize();
assert table.capacity() == 30;
}
public static void testAdditionWithOffset() {
RetransmitTable table=new RetransmitTable(3, 10, 100);
addAndGet(table, 100, "100");
addAndGet(table, 101, "101");
addAndGet(table, 105, "105");
addAndGet(table, 109, "109");
addAndGet(table, 110, "110");
addAndGet(table, 111, "111");
addAndGet(table, 119, "119");
addAndGet(table, 120, "120");
addAndGet(table, 129, "129");
System.out.println("table: " + table.dump());
assert table.size() == 9;
assert table.capacity() == 30;
}
public static void testDuplicateAddition() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
addAndGet(table, 0, "0");
addAndGet(table, 1, "1");
addAndGet(table, 5, "5");
addAndGet(table, 9, "9");
addAndGet(table, 10, "10");
assert !table.put(5, new Message());
assert table.get(5).getObject().equals("5");
assert table.size() == 5;
}
public static void testDumpMatrix() {
RetransmitTable table=new RetransmitTable(3, 10, 1);
long[] seqnos={1,3,5,7,9,12,14,16,18,20,21,22,23,24};
for(long seqno: seqnos)
table.put(seqno, MSG);
System.out.println("matrix:\n" + table.dumpMatrix());
}
public static void testMassAddition() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
final int NUM_MSGS=10005;
final Message MSG=new Message(null, null, "hello world");
for(int i=0; i < NUM_MSGS; i++)
table.put(i, MSG);
System.out.println("table = " + table);
assert table.size() == NUM_MSGS;
assert table.capacity() == 10010;
}
public static void testResize() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
assert table.capacity() == 30;
addAndGet(table, 30, "30");
addAndGet(table, 35, "35");
assert table.capacity() == 40;
addAndGet(table, 500, "500");
assert table.capacity() == 510;
addAndGet(table, 515, "515");
assert table.capacity() == 520;
}
public void testResizeWithPurge() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
for(long i=1; i <= 100; i++)
addAndGet(table, i, "hello-" + i);
System.out.println("table: " + table);
// now remove 60 messages
for(long i=1; i <= 60; i++) {
Message msg=table.remove(i);
assert msg.getObject().equals("hello-" + i);
}
System.out.println("table after removal of seqno 60: " + table);
table.purge(50);
System.out.println("now triggering a resize() by addition of seqno=120");
addAndGet(table, 120, "120");
}
public void testResizeWithPurgeAndGetOfNonExistingElement() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
for(long i=0; i < 50; i++)
addAndGet(table, i, "hello-" + i);
System.out.println("table: " + table);
// now remove 15 messages
for(long i=0; i <= 15; i++) {
Message msg=table.remove(i);
assert msg.getObject().equals("hello-" + i);
}
System.out.println("table after removal of seqno 15: " + table);
table.purge(15);
System.out.println("now triggering a resize() by addition of seqno=55");
addAndGet(table, 55, "hello-55");
// now we have elements 40-49 in row 1 and 55 in row 2:
List<String> list=new ArrayList<String>(20);
for(int i=16; i < 50; i++)
list.add("hello-" + i);
list.add("hello-55");
for(long i=table.getOffset(); i < table.capacity() + table.getOffset(); i++) {
Message msg=table.get(i);
if(msg != null) {
String message=(String)msg.getObject();
System.out.println(i + ": " + message);
list.remove(message);
}
}
System.out.println("table:\n" + table.dumpMatrix());
assert list.isEmpty() : " list: " + Util.print(list);
}
public void testResizeWithPurge2() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
for(long i=0; i < 50; i++)
addAndGet(table, i, "hello-" + i);
System.out.println("table = " + table);
assert table.size() == 50;
assert table.capacity() == 50;
assert table.getHighestPurged() == 0;
assert table.getHighest() == 49;
table.purge(43);
addAndGet(table, 52, "hello-52");
assert table.get(43) == null;
for(long i=44; i < 50; i++) {
Message msg=table.get(i);
assert msg != null && msg.getObject().equals("hello-" + i);
}
assert table.get(50) == null;
assert table.get(51) == null;
Message msg=table.get(52);
assert msg != null && msg.getObject().equals("hello-52");
assert table.get(53) == null;
}
public static void testMove() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
for(long i=0; i < 50; i++)
addAndGet(table, i, "hello-" + i);
table.purge(49);
assert table.isEmpty();
addAndGet(table, 50, "50");
assert table.size() == 1;
assert table.capacity() == 50;
}
public static void testPurge() {
RetransmitTable table=new RetransmitTable(5, 10, 0);
for(long seqno=0; seqno < 25; seqno++)
table.put(seqno, MSG);
long[] seqnos={30,31,32,37,38,39, 40,41,42,47,48,49};
for(long seqno: seqnos)
table.put(seqno, MSG);
System.out.println("table (before remove):\n" + table.dump());
for(long seqno=0; seqno <= 22; seqno++)
table.remove(seqno);
System.out.println("\ntable (after remove 22, before purge):\n" + table.dump());
table.purge(22);
System.out.println("\ntable: (after purge 22):\n" + table.dump());
assert table.size() == 2 + seqnos.length;
}
public void testCompact() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
for(long i=0; i < 80; i++)
addAndGet(table, i, "hello-" + i);
assert table.size() == 80;
table.purge(59);
assert table.size() == 20;
table.compact();
assert table.size() == 20;
assert table.capacity() == 40;
}
public void testCompactWithAutomaticPurging() {
RetransmitTable table=new RetransmitTable(3, 10, 0);
table.setAutomaticPurging(true);
for(long i=0; i < 80; i++)
addAndGet(table, i, "hello-" + i);
assert table.size() == 80;
for(long i=0; i <= 59; i++)
table.remove(i);
assert table.size() == 20;
table.compact();
assert table.size() == 20;
assert table.capacity() == 40;
}
protected static void addAndGet(RetransmitTable table, long seqno, String message) {
boolean added=table.put(seqno, new Message(null, null, message));
assert added;
Message msg=table.get(seqno);
assert msg != null && msg.getObject().equals(message);
}
}
|
package imj3.tools;
import static imj3.core.IMJCoreTools.quantize;
import static java.lang.Math.*;
import static multij.tools.Tools.*;
import imj3.core.Image2D;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import multij.events.EventManager;
import multij.events.EventManager.AbstractEvent;
import multij.events.EventManager.Event.Listener;
import multij.swing.MouseHandler;
import multij.swing.SwingTools;
import multij.tools.Canvas;
import multij.tools.CommandLineArgumentsParser;
import multij.tools.Tools;
/**
* @author codistmonk (creation 2015-03-20)
*/
public final class Image2DComponent extends JComponent {
private final Canvas canvas;
private TileOverlay tileOverlay;
private Overlay overlay;
private Image2D image;
private final AffineTransform view;
private final Collection<TileKey> activeTiles;
private int statusHashCode;
private boolean imageEnabled;
private boolean dragEnabled;
private boolean wheelZoomEnabled;
public Image2DComponent(final Image2D image) {
this.canvas = new Canvas();
this.image = image;
this.view = new AffineTransform();
this.activeTiles = Collections.synchronizedSet(new HashSet<>());
this.imageEnabled = true;
this.dragEnabled = true;
this.wheelZoomEnabled = true;
this.setOpaque(true);
final int w = min(image.getWidth(), 800);
final int h = min(image.getHeight(), 600);
this.setPreferredSize(new Dimension(w, h));
final double scale = image.getScale();
this.view.scale(scale, scale);
this.view.translate((-image.getWidth() / 2.0 + w / 2) / scale, (-image.getHeight() / 2.0 + h / 2) / scale);
new MouseHandler() {
private final Point mouse = new Point(-1, 0);
@Override
public final void mousePressed(final MouseEvent event) {
this.mouse.setLocation(event.getX(), event.getY());
}
@Override
public final void mouseDragged(final MouseEvent event) {
if (!isDragEnabled()) {
return;
}
final AffineTransform view = Image2DComponent.this.getView();
final Point2D translation = new Point2D.Double((event.getX() - this.mouse.x) / view.getScaleX(), (event.getY() - this.mouse.y) / view.getScaleY());
view.translate(translation.getX(), translation.getY());
this.mousePressed(event);
Image2DComponent.this.repaint();
}
@Override
public final void mouseWheelMoved(final MouseWheelEvent event) {
if (!isWheelZoomEnabled()) {
return;
}
final int direction = event.getWheelRotation();
final double n = 8.0;
final double scale = Image2DComponent.this.getView().getScaleX();
final double logScale = round(n * log(scale) / log(2.0)) / n;
final double newScale = pow(2.0, logScale + signum(direction) / n);
Image2DComponent.this.setViewScale(newScale);
}
private static final long serialVersionUID = -8787564920294626502L;
}.addTo(this);
}
public final void setImage(final Image2D image) {
final Image2D oldImage = this.getImage();
if (oldImage != image) {
final AffineTransform view = this.getView();
this.image = image.getScaledImage(view.getScaleX());
final double newScale = image.getScale();
this.view.setToScale(newScale, newScale);
this.view.translate((-image.getWidth() / 2.0 + this.getWidth() / 2) / newScale,
(-image.getHeight() / 2.0 + this.getHeight() / 2) / newScale);
this.repaint();
this.new ImageChangedEvent(oldImage).fire();
}
}
public final Image2DComponent setDropImageEnabled(final boolean dropImageEnabled) {
if (this.isDropImageEnabled() != dropImageEnabled) {
this.setDropTarget(dropImageEnabled ? new DropImage(this) : null);
}
return this;
}
public final boolean isDropImageEnabled() {
return this.getDropTarget() instanceof DropImage;
}
public final boolean isImageEnabled() {
return this.imageEnabled;
}
public final Image2DComponent setImageEnabled(final boolean imageEnabled) {
this.imageEnabled = imageEnabled;
return this;
}
public final boolean isDragEnabled() {
return this.dragEnabled;
}
public final Image2DComponent setDragEnabled(final boolean dragEnabled) {
this.dragEnabled = dragEnabled;
return this;
}
public final boolean isWheelZoomEnabled() {
return this.wheelZoomEnabled;
}
public final Image2DComponent setWheelZoomEnabled(final boolean wheelZoomEnabled) {
this.wheelZoomEnabled = wheelZoomEnabled;
return this;
}
public final TileOverlay getTileOverlay() {
return this.tileOverlay;
}
public final void setTileOverlay(final TileOverlay tileOverlay) {
this.tileOverlay = tileOverlay;
}
public final Overlay getOverlay() {
return this.overlay;
}
public final void setOverlay(final Overlay overlay) {
this.overlay = overlay;
}
public final Image2D getImage() {
return this.image;
}
public final AffineTransform getView() {
return this.view;
}
@Override
protected final void paintComponent(final Graphics g) {
super.paintComponent(g);
final Graphics2D canvasGraphics = this.canvas.setFormat(this.getWidth(), this.getHeight()).getGraphics();
{
final double scale = max(this.getView().getScaleX(), this.getView().getScaleY());
final Image2D image = this.getImage();
this.image = image.getScaledImage(scale);
if (image != this.getImage()) {
synchronized (canvasGraphics) {
canvasGraphics.setTransform(new AffineTransform());
}
}
}
final int statusHashCode;
synchronized (canvasGraphics) {
// XXX not perfect but works for now
statusHashCode = this.getView().hashCode() + canvasGraphics.hashCode() + this.getImage().hashCode() + this.getSize().hashCode()
+ Tools.hashCode(this.getOverlay()) + Tools.hashCode(this.getTileOverlay());
canvasGraphics.setTransform(this.getView());
}
if (!this.isImageEnabled()) {
synchronized (canvasGraphics) {
canvasGraphics.setTransform(IDENTITY);
canvasGraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
canvasGraphics.setTransform(this.getView());
}
} else if (this.statusHashCode != statusHashCode) {
this.statusHashCode = statusHashCode;
final Collection<TileKey> newActiveTiles = new HashSet<>();
final Image2D image = this.getImage();
final double imageScale = image.getScale();
final Point2D topLeft = new Point2D.Double();
final Point2D topRight = new Point2D.Double(this.getWidth() - 1.0, 0.0);
final Point2D bottomRight = new Point2D.Double(this.getWidth() - 1.0, this.getHeight() - 1.0);
final Point2D bottomLeft = new Point2D.Double(0, this.getHeight() - 1.0);
try {
this.getView().inverseTransform(topLeft, topLeft);
this.getView().inverseTransform(topRight, topRight);
this.getView().inverseTransform(bottomRight, bottomRight);
this.getView().inverseTransform(bottomLeft, bottomLeft);
} catch (final NoninvertibleTransformException exception) {
exception.printStackTrace();
}
final double top = min(min(topLeft.getY(), topRight.getY()), min(bottomLeft.getY(), bottomRight.getY())) * imageScale;
final double bottom = max(max(topLeft.getY(), topRight.getY()), max(bottomLeft.getY(), bottomRight.getY())) * imageScale;
final double left = min(min(topLeft.getX(), topRight.getX()), min(bottomLeft.getX(), bottomRight.getX())) * imageScale;
final double right = max(max(topLeft.getX(), topRight.getX()), max(bottomLeft.getX(), bottomRight.getX())) * imageScale;
final int optimalTileWidth = image.getOptimalTileWidth();
final int optimalTileHeight = image.getOptimalTileHeight();
final int firstTileX = max(0, quantize((int) left, optimalTileWidth));
final int lastTileX = min(quantize((int) right, optimalTileWidth), quantize(image.getWidth() - 1, optimalTileWidth));
final int firstTileY = max(0, quantize((int) top, optimalTileHeight));
final int lastTileY = min(quantize((int) bottom, optimalTileHeight), quantize(image.getHeight() - 1, optimalTileHeight));
for (int tileY = firstTileY; tileY <= lastTileY; tileY += optimalTileHeight) {
for (int tileX = firstTileX; tileX <= lastTileX; tileX += optimalTileWidth) {
final TileKey tileKey = new TileKey(imageScale, new Point(tileX, tileY));
newActiveTiles.add(tileKey);
if (this.getActiveTiles().add(tileKey)) {
MultiThreadTools.getExecutor().submit(new Runnable() {
@Override
public final void run() {
drawTile(image, tileKey, imageScale, canvasGraphics);
}
});
}
}
}
this.getActiveTiles().retainAll(newActiveTiles);
}
synchronized (canvasGraphics) {
g.drawImage(this.canvas.getImage(), 0, 0, null);
final Overlay overlay = this.getOverlay();
if (overlay != null) {
overlay.update((Graphics2D) g, this.getVisibleRect());
}
}
}
public final void setViewScale(final double newScale) {
final AffineTransform view = this.getView();
final Point2D center = new Point2D.Double(getWidth() / 2.0, getHeight() / 2.0);
final Point2D newCenter = new Point2D.Double(getWidth() / 2.0, getHeight() / 2.0);
try {
view.inverseTransform(center, center);
} catch (final NoninvertibleTransformException exception) {
exception.printStackTrace();
}
view.setTransform(newScale, view.getShearY(), view.getShearX(), newScale, view.getTranslateX(), view.getTranslateY());
// center_view:
{
try {
view.inverseTransform(newCenter, newCenter);
} catch (final NoninvertibleTransformException exception) {
exception.printStackTrace();
}
view.translate(-(center.getX() - newCenter.getX()), -(center.getY() - newCenter.getY()));
newCenter.setLocation(getWidth() / 2.0, getHeight() / 2.0);
try {
view.inverseTransform(newCenter, newCenter);
} catch (final NoninvertibleTransformException exception) {
exception.printStackTrace();
}
}
this.repaint();
}
final Collection<TileKey> getActiveTiles() {
return this.activeTiles;
}
final void drawTile(final Image2D image, final TileKey tileKey,
final double imageScale, final Graphics2D canvasGraphics) {
if (!getActiveTiles().contains(tileKey)) {
return;
}
final Point tileXY = tileKey.getTileXY();
final BufferedImage tile = getTile(image, tileXY.x, tileXY.y);
final boolean clearLeft = tileXY.x == 0;
final boolean clearTop = tileXY.y == 0;
final boolean clearRight = image.getWidth() <= tileXY.x + image.getOptimalTileWidth();
final boolean clearBottom = image.getHeight() <= tileXY.y + image.getOptimalTileHeight();
final boolean clearSomething = clearLeft || clearTop || clearRight || clearBottom;
final Rectangle region = new Rectangle((int) (tileXY.x / imageScale), (int) (tileXY.y / imageScale),
(int) (tile.getWidth() / imageScale), (int) (tile.getHeight() / imageScale));
synchronized (canvasGraphics) {
if (clearSomething) {
final AffineTransform transform = canvasGraphics.getTransform();
final Point topLeft = new Point();
final Point bottomRight = new Point(this.getWidth(), this.getHeight());
try {
transform.inverseTransform(topLeft, topLeft);
transform.inverseTransform(bottomRight, bottomRight);
final Rectangle canvasRegion = new Rectangle(
topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
canvasGraphics.setColor(Color.WHITE);
if (clearLeft) {
canvasGraphics.fillRect(canvasRegion.x, canvasRegion.y,
region.x - canvasRegion.x, canvasRegion.height);
}
if (clearTop) {
canvasGraphics.fillRect(canvasRegion.x, canvasRegion.y,
canvasRegion.width, region.y - canvasRegion.y);
}
if (clearRight) {
canvasGraphics.fillRect(region.x + region.width, canvasRegion.y,
canvasRegion.width, canvasRegion.height);
}
if (clearBottom) {
canvasGraphics.fillRect(canvasRegion.x, region.y + region.height,
canvasRegion.width, canvasRegion.height);
}
} catch (final NoninvertibleTransformException exception) {
exception.printStackTrace();
}
}
canvasGraphics.drawImage(tile, region.x, region.y, region.width, region.height, null);
final TileOverlay tileOverlay = this.getTileOverlay();
if (tileOverlay != null) {
tileOverlay.update(canvasGraphics, tileXY, region);
}
}
if (getActiveTiles().remove(tileKey)) {
repaint();
}
}
/**
* @author codistmonk (creation 2015-05-01)
*/
public final class ImageChangedEvent extends AbstractEvent<Image2DComponent> {
private final Image2D oldImage;
protected ImageChangedEvent(final Image2D oldImage) {
super(Image2DComponent.this);
this.oldImage = oldImage;
}
public final Image2D getOldImage() {
return this.oldImage;
}
private static final long serialVersionUID = -5641162710525216776L;
}
private static final long serialVersionUID = -1359039061498719576L;
public static final Color CLEAR = new Color(0, true);
static final AffineTransform IDENTITY = new AffineTransform();
/**
* @param commandLineArguments
* <br>Must not be null
*/
public static final void main(final String[] commandLineArguments) {
final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments);
final String path = arguments.get("file", "");
final Image2DComponent component = new Image2DComponent(IMJTools.read(path)).setDropImageEnabled(true);
EventManager.getInstance().addWeakListener(component, ImageChangedEvent.class, new Object() {
@Listener
public final void imageChanged(final ImageChangedEvent event) {
((Frame) SwingUtilities.getWindowAncestor(component)).setTitle(component.getImage().getId());
}
});
SwingTools.show(component, path, false).addWindowListener(new WindowAdapter() {
// XXX sftp handler prevents application from closing normally
@Override
public final void windowClosed(final WindowEvent event) {
imj3.protocol.sftp.Handler.closeAll();
System.exit(0);
}
});
}
public static final BufferedImage getTile(final Image2D image, final int tileX, final int tileY) {
try {
// XXX potential synchronization issue here
return (BufferedImage) image.getTileContaining(tileX, tileY).toAwt();
} catch (final Exception exception) {
exception.printStackTrace();
return new BufferedImage(image.getTileWidth(tileX), image.getTileWidth(tileY), BufferedImage.TYPE_BYTE_BINARY);
}
}
/**
* @author codistmonk (creation 2015-03-22)
*/
public static abstract interface TileOverlay extends Serializable {
public abstract void update(Graphics2D graphics, Point tileXY, Rectangle region);
}
/**
* @author codistmonk (creation 2015-03-22)
*/
public static abstract interface Overlay extends Serializable {
public abstract void update(Graphics2D graphics, Rectangle region);
}
/**
* @author codistmonk (creation 2015-03-25)
*/
static final class TileKey implements Serializable {
private final double imageScale;
private final Point tileXY;
public TileKey(final double imageScale, final Point tileXY) {
this.imageScale = imageScale;
this.tileXY = tileXY;
}
public final double getImageScale() {
return this.imageScale;
}
public final Point getTileXY() {
return this.tileXY;
}
@Override
public final int hashCode() {
return Double.hashCode(this.getImageScale()) + this.getTileXY().hashCode();
}
@Override
public final boolean equals(final Object object) {
final TileKey that = cast(this.getClass(), object);
return that != null && this.getImageScale() == that.getImageScale() && this.getTileXY().equals(that.getTileXY());
}
private static final long serialVersionUID = 2790290680678157622L;
}
/**
* @author codistmonk (creation 2015-05-01)
*/
public static final class DropImage extends DropTarget {
private final Image2DComponent component;
public DropImage(final Image2DComponent component) {
this.component = component;
}
@Override
public final synchronized void drop(final DropTargetDropEvent event) {
final Image2D newImage = IMJTools.read(SwingTools.getFiles(event).get(0).getPath());
SwingUtilities.invokeLater(() -> {
this.component.setImage(newImage);
this.component.setViewScale(min((double) this.component.getWidth() / newImage.getWidth(), (double) this.component.getHeight() / newImage.getHeight()));
});
}
private static final long serialVersionUID = 4728142083998773248L;
}
}
|
package com.hhl.tubatu;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class ClipViewPager extends ViewPager {
private final static float DISTANCE = 10;
private float downX;
private float downY;
public ClipViewPager(Context context) {
super(context);
}
public ClipViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if(ev.getAction() == MotionEvent.ACTION_DOWN){
downX = ev.getX();
downY = ev.getY();
}else if (ev.getAction() == MotionEvent.ACTION_UP) {
float upX = ev.getX();
float upY = ev.getY();
// updown > ,,
if(Math.abs(upX - downX) > DISTANCE || Math.abs(upY - downY) > DISTANCE){
return super.dispatchTouchEvent(ev);
}
View view = viewOfClickOnScreen(ev);
if (view != null) {
int index = indexOfChild(view);
if (getCurrentItem() != index) {
setCurrentItem(indexOfChild(view));
}
}
}
return super.dispatchTouchEvent(ev);
}
/**
* @param ev
* @return
*/
private View viewOfClickOnScreen(MotionEvent ev) {
int childCount = getChildCount();
int[] location = new int[2];
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
v.getLocationOnScreen(location);
int minX = location[0];
int minY = getTop();
int maxX = location[0] + v.getWidth();
int maxY = getBottom();
float x = ev.getX();
float y = ev.getY();
if ((x > minX && x < maxX) && (y > minY && y < maxY)) {
return v;
}
}
return null;
}
}
|
package fr.sciencespo.medialab.hci.memorystructure.index;
import fr.sciencespo.medialab.hci.memorystructure.thrift.WebEntity;
import fr.sciencespo.medialab.hci.memorystructure.util.DynamicLogger;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.WildcardQuery;
import java.util.List;
import java.util.Set;
/**
* Lucene queries used in the LRUIndex.
*
* @author heikki doeleman
*/
public class LuceneQueryFactory {
private static DynamicLogger logger = new DynamicLogger(LuceneQueryFactory.class);
private static Term typeEqualNodeLink = new Term(IndexConfiguration.FieldName.TYPE.name(), IndexConfiguration.DocType.NODE_LINK.name());
private static Term typeEqualPageItem = new Term(IndexConfiguration.FieldName.TYPE.name(), IndexConfiguration.DocType.PAGE_ITEM.name());
public static Term typeEqualPrecisionException = new Term(IndexConfiguration.FieldName.TYPE.name(), IndexConfiguration.DocType.PRECISION_EXCEPTION.name());
private static Term typeEqualWebEntity = new Term(IndexConfiguration.FieldName.TYPE.name(), IndexConfiguration.DocType.WEBENTITY.name());
private static Term typeEqualWebEntityLink = new Term(IndexConfiguration.FieldName.TYPE.name(), IndexConfiguration.DocType.WEBENTITY_LINK.name());
private static Term typeEqualWebEntityCreationRule = new Term(IndexConfiguration.FieldName.TYPE.name(), IndexConfiguration.DocType.WEBENTITY_CREATION_RULE.name());
private static Term lruEqualDefaultWebEntityCreationRule = new Term(IndexConfiguration.FieldName.LRU.name(), IndexConfiguration.DEFAULT_WEBENTITY_CREATION_RULE);
// NodeLink
protected static Query getNodeLinksQuery() {
return new TermQuery(typeEqualNodeLink);
}
protected static Query getNodeLinksBySourceLRUQuery(String source) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualNodeLink);
Query q2 = getLRUWildcardManagedQuery(IndexConfiguration.FieldName.SOURCE.name(), source);
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
protected static Query getNodeLinksByTargetLRUQuery(String target) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualNodeLink);
Query q2 = getLRUWildcardManagedQuery(IndexConfiguration.FieldName.TARGET.name(), target);
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
/**
*
* @param nodeLink
* @return
* @throws IndexException hmm
*/
protected static Query getNodeLinkBySourceAndTargetQuery(String source, String target) throws IndexException {
BooleanQuery q = new BooleanQuery();
TermQuery q1 = new TermQuery(typeEqualNodeLink);
TermQuery q2 = new TermQuery(new Term(IndexConfiguration.FieldName.SOURCE.name(), source));
TermQuery q3 = new TermQuery(new Term(IndexConfiguration.FieldName.TARGET.name(), target));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
q.add(q3, BooleanClause.Occur.MUST);
if (logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
// PageItem
protected static Query getPageItemsQuery() {
return new TermQuery(typeEqualPageItem);
}
protected static Query getPageItemByLRUQuery(String lru) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualPageItem);
Query q2 = getLRUWildcardManagedQuery(IndexConfiguration.FieldName.LRU.name(), lru);
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
protected static Query getPageItemMatchingWebEntityButNotMatchingSubWebEntities(WebEntity webEntity, List<WebEntity> subWebEntities) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualPageItem);
q.add(q1, BooleanClause.Occur.MUST);
for(String webEntityPrefix : webEntity.getLRUSet()) {
webEntityPrefix = webEntityPrefix + "*";
Term prefixTerm = new Term(IndexConfiguration.FieldName.LRU.name(), webEntityPrefix);
Query prefixQuery = new WildcardQuery(prefixTerm);
q.add(prefixQuery, BooleanClause.Occur.MUST);
}
for(WebEntity sub : subWebEntities) {
for(String subPrefix : sub.getLRUSet()) {
subPrefix = subPrefix + "*";
Term prefixTerm = new Term(IndexConfiguration.FieldName.LRU.name(), subPrefix);
Query prefixQuery = new WildcardQuery(prefixTerm);
q.add(prefixQuery, BooleanClause.Occur.MUST_NOT);
}
}
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
// PrecisionException
protected static Query getPrecisionExceptionsQuery() {
return new TermQuery(typeEqualPrecisionException);
}
// WebEntity
protected static Query getWebEntitiesQuery() {
return new TermQuery(typeEqualWebEntity);
}
/**
* Query to search for WebEntity by ID.
*
* @param id
* @return
*/
protected static Query getWebEntityByIdQuery(String id) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntity);
Query q2 = new TermQuery(new Term(IndexConfiguration.FieldName.ID.name(), id));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
protected static Query getWebEntitiesByLRUQuery(String lru) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntity);
Query q2 = getLRUWildcardManagedQuery(IndexConfiguration.FieldName.LRU.name(), lru);
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
// WebEntityCreationRule
protected static Query getWebEntityCreationRulesQuery() {
return new TermQuery(typeEqualWebEntityCreationRule);
}
/**
*
* @param lru
* @return
*/
protected static Query getWebEntityCreationRuleByLRUQuery(String lru) {
if(lru == null) {
lru = IndexConfiguration.DEFAULT_WEBENTITY_CREATION_RULE;
}
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntityCreationRule);
Query q2 = new TermQuery(new Term(IndexConfiguration.FieldName.LRU.name(), lru));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
/**
*
* @return
* @throws IndexException hmm
*/
protected static Query getDefaultWebEntityCreationRuleQuery() throws IndexException {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntityCreationRule);
Query q2 = new TermQuery(lruEqualDefaultWebEntityCreationRule);
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
// WebEntityLinks
/**
*
* @return
*/
protected static Query getWebEntityLinksQuery() {
Query q = new TermQuery(typeEqualWebEntityLink);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
/**
*
* @param id
* @return
*/
protected static Query getWebEntityLinkByIdQuery(String id) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntityLink);
Query q2 = new TermQuery(new Term(IndexConfiguration.FieldName.ID.name(), id));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
/**
*
* @param id
* @return
*/
protected static Query getWebEntityLinksByTargetQuery(String target) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntityLink);
Query q2 = new TermQuery(new Term(IndexConfiguration.FieldName.TARGET.name(), target));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
protected static Query getWebEntityLinksBySourceQuery(String source) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntityLink);
Query q2 = new TermQuery(new Term(IndexConfiguration.FieldName.SOURCE.name(), source));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
/**
*
* @param source
* @param target
* @return
*/
protected static Query getWebEntityLinkBySourceAndTargetQuery(String source, String target) {
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntityLink);
Query q2 = new TermQuery(new Term(IndexConfiguration.FieldName.SOURCE.name(), source));
Query q3 = new TermQuery(new Term(IndexConfiguration.FieldName.TARGET.name(), target));
q.add(q1, BooleanClause.Occur.MUST);
q.add(q2, BooleanClause.Occur.MUST);
q.add(q3, BooleanClause.Occur.MUST);
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
/**
*
* @param webEntity
* @return
*/
protected static Query getSubWebEntitiesQuery(WebEntity webEntity) {
if(logger.isDebugEnabled()) {
logger.debug("getSubWebEntitiesQuery for webEntity " + webEntity.getName() );
}
BooleanQuery q = new BooleanQuery();
Query q1 = new TermQuery(typeEqualWebEntity);
q.add(q1, BooleanClause.Occur.MUST);
Set<String> prefixes = webEntity.getLRUSet();
for(String prefix : prefixes) {
Query qNotPrefix = new TermQuery(new Term(IndexConfiguration.FieldName.LRU.name(), prefix));
q.add(qNotPrefix, BooleanClause.Occur.MUST_NOT);
prefix = prefix + "?*";
Query qPrefixWildcard = new WildcardQuery(new Term(IndexConfiguration.FieldName.LRU.name(), prefix));
q.add(qPrefixWildcard, BooleanClause.Occur.MUST);
}
if(logger.isDebugEnabled()) {
logger.debug("Lucene query: " + q.toString());
}
return q;
}
protected static Query getLRUWildcardManagedQuery(String field, String value) {
Term prefixTerm = new Term(field, value);
// prefix query
if(value.endsWith("*")) {
return new PrefixQuery(new Term(field, value.substring(0, value.length() - 1)));
}
// wildcard query
if(value.contains("*") || value.contains("?")) {
return new WildcardQuery(prefixTerm);
}
// no-wildcard query (faster)
else {
return new TermQuery(prefixTerm);
}
}
}
|
package com.smidur.aventon.sync;
import android.content.Context;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import com.amazonaws.mobile.AWSMobileClient;
import com.amazonaws.mobile.user.IdentityManager;
import com.google.android.gms.maps.model.LatLng;
import com.smidur.aventon.exceptions.TokenInvalidException;
import com.smidur.aventon.http.HttpController;
import com.smidur.aventon.http.HttpWrapper;
import com.smidur.aventon.managers.RideManager;
import com.smidur.aventon.model.SyncDestination;
import com.smidur.aventon.model.SyncDriver;
import com.smidur.aventon.model.SyncLocation;
import com.smidur.aventon.model.SyncPassenger;
import com.smidur.aventon.utilities.GpsUtil;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.PriorityQueue;
import java.util.Stack;
public class Sync {
String TAG = getClass().getSimpleName();
private static final int RETRY_SYNC_AVAILABLE_RIDES = 500;//half sec
//todo update faster when driver is picking up somebody
private static final int SYNC_DRIVER_LOCATION_RATE = 3 * 1000;//3 sec
Thread syncAvailableRidesThread;
Thread syncDriverLocationThread;
Thread syncSchedulePickupThread;
HttpController syncAvailableDriversController;
HttpController syncSchedulePickupController;
SyncPassenger syncPassenger;
SyncDriver syncDriver;
Stack<SyncLocation> driverLocations;
private static Sync instance;
private final Context context;
private Handler handler;
public Sync(Context context) {
this.context = context;
}
public static Sync i(Context context){
if(instance==null) {
instance = new Sync(context);
instance.driverLocations = new Stack<>();
instance.handler = new Handler(context.getMainLooper());
}
return instance;
}
/**
* This lets the web service know that driver is available for doing rides.
* @param syncDriver
*/
public void startSyncRideInfo(SyncDriver syncDriver) {
this.syncDriver = syncDriver;
//sync rides info
handler.removeCallbacks(syncAvailableRides);
handler.post(syncAvailableRides);
}
public void stopSyncRideInfo() {
//stop sync ride infos
closeConnectionIfOpen();
if(syncAvailableRidesThread!=null)
syncAvailableRidesThread.interrupt();
if(syncAvailableRides!=null)
handler.removeCallbacks(syncAvailableRides);
}
public void startSyncDriverLocation() {
//sync location
Location lastKnownLocation = GpsUtil.getLastKnownLocation(context);
if(lastKnownLocation!=null) {
pushDriverLocationToSync(lastKnownLocation);
}
handler.post(syncDriverLocation);
}
public void stopSyncDriverLocation() {
//stop sync location
handler.removeCallbacks(syncDriverLocation);
if(syncDriverLocationThread!=null)
syncDriverLocationThread.interrupt();
}
public void startSyncSchedulePickup(SyncPassenger syncPassenger) {
this.syncPassenger = syncPassenger;
handler.post(syncSchedulePickup);
}
public void stopSyncSchedulePickup() {
this.syncPassenger = null;
closeConnectionIfOpen();
if(syncSchedulePickup!=null)
handler.removeCallbacks(syncSchedulePickup);
}
public void pushDriverLocationToSync(Location driverLocation) {
SyncLocation newSyncLocation = new SyncLocation(driverLocation.getLatitude(),driverLocation.getLongitude());
driverLocations.push(newSyncLocation);
}
private void closeConnectionIfOpen() {
if(syncSchedulePickupController!=null)
syncSchedulePickupController.closeStream();
if(syncAvailableDriversController!=null)
syncAvailableDriversController.closeStream();
}
/**
* This assumes that the user is logged in.
*/
private Runnable syncAvailableRides = new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
syncAvailableRidesThread = Thread.currentThread();
Thread.currentThread().setName("SyncAvailableRides");
//this label is to make sure we always schedule this task in a cycle
scheduleNextIteration:
do {
try {
syncAvailableDriversController = new HttpController(context);
syncAvailableDriversController.availableRidesCall(syncDriver,new HttpController.RidesAvailableCallback() {
@Override
public void onNewRideAvailable(String message) {
RideManager.i(context).processMessage(message);
}
});
} catch(TokenInvalidException tie) {
IdentityManager identityManager = AWSMobileClient.defaultMobileClient()
.getIdentityManager();
identityManager.refresh();
} catch(ConnectException ce) {
//catch exceptions related to server down
RideManager.i(context).postLookForRideConnectionErrorCallback();
handler.removeCallbacks(syncAvailableRides);
ce.printStackTrace();
closeConnectionIfOpen();
//post callback of server down
//don't schedule next attempt
return;
} catch(SocketException se) {
//when disconnect to the connection gets called from other place like a button
handler.removeCallbacks(syncAvailableRides);
closeConnectionIfOpen();
Log.e(TAG,"SocketException Sync Available Rides",se);
return;
} catch (InterruptedIOException iioe) {
handler.removeCallbacks(syncAvailableRides);
iioe.printStackTrace();
closeConnectionIfOpen();
//post callback of server down
//don't schedule next attempt
return;
} catch (IOException ioe) {
ioe.printStackTrace();
closeConnectionIfOpen();
}
} while(false);
handler.removeCallbacks(syncAvailableRides);
handler.postDelayed(syncAvailableRides,RETRY_SYNC_AVAILABLE_RIDES);
}
}).start();
}
};
private Runnable syncDriverLocation = new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("SyncAvailableRides");
//this label is to make sure we always schedule this task in a cycle
scheduleNextIteration:
do {
try {
if(driverLocations.size()>0) {
SyncLocation driverLocation = driverLocations.pop();
//this controller doesn't keep a connection open so keep it as local variable
HttpController syncDriverLocationController = new HttpController(context);
syncDriverLocationController.updateDriverLocation(driverLocation);
driverLocations.empty();
}
} catch(TokenInvalidException tie) {
IdentityManager identityManager = AWSMobileClient.defaultMobileClient()
.getIdentityManager();
identityManager.refresh();
} catch(IOException ioe) {
closeConnectionIfOpen();
ioe.printStackTrace();
}
} while(false);
handler.removeCallbacks(syncDriverLocation);
handler.postDelayed(syncDriverLocation,SYNC_DRIVER_LOCATION_RATE);
}
}).start();
}
};
/**
* This assumes that the user is logged in.
*/
private Runnable syncSchedulePickup = new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
syncSchedulePickupThread = Thread.currentThread();
Thread.currentThread().setName("SyncSchedulePickup");
if(syncPassenger==null)return;
//this label is to make sure we always schedule this task in a cycle
scheduleNextIteration:
do {
try {
syncSchedulePickupController = new HttpController(context);
syncSchedulePickupController.schedulePickupCall(syncPassenger,new HttpController.SchedulePickupCallback() {
@Override
public void onConfirmedPickupScheduled(String message) {
RideManager.i(context).processMessage(message);
}
});
} catch(TokenInvalidException tie) {
IdentityManager identityManager = AWSMobileClient.defaultMobileClient()
.getIdentityManager();
identityManager.refresh();
} catch(ConnectException ce) {
//catch exceptions related to server down
RideManager.i(context).postScheduleConnectionErrorCallback();
handler.removeCallbacks(syncSchedulePickup);
ce.printStackTrace();
closeConnectionIfOpen();
//post callback of server down
//don't schedule next attempt
return;
} catch(SocketTimeoutException ste) {
ste.printStackTrace();
//if the driver is not pickup confirmed.
if(!RideManager.i(context).isPassengerPickupConfirmed()){
handler.removeCallbacks(syncSchedulePickup);
closeConnectionIfOpen();
RideManager.i(context).postNoDriverFoundCallback();
return;
}
} catch(SocketException se) {
se.printStackTrace();
handler.removeCallbacks(syncSchedulePickup);
closeConnectionIfOpen();
Log.e(TAG,"SocketException Sync Schedule Pickup",se);
} catch (InterruptedIOException iioe) {
handler.removeCallbacks(syncSchedulePickup);
iioe.printStackTrace();
closeConnectionIfOpen();
//don't schedule next attempt
return;
} catch(IOException ioe) {
ioe.printStackTrace();
closeConnectionIfOpen();
}
} while(false);
handler.removeCallbacks(syncSchedulePickup);
handler.postDelayed(syncSchedulePickup,RETRY_SYNC_AVAILABLE_RIDES);
}
}).start();
}
};
}
|
package org.eclipse.birt.report.model.parser;
import org.eclipse.birt.report.model.api.ErrorCodes;
import org.eclipse.birt.report.model.api.ModelException;
import org.eclipse.birt.report.model.i18n.MessageConstants;
import org.eclipse.birt.report.model.i18n.ModelMessages;
/**
* This class describes a parse error. Many errors are reported using the same
* exceptions used for API operations.
*
*/
public class DesignParserException extends ModelException implements ErrorCodes
{
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 586491893198640178L;
/**
* The design/library file was not found.
*/
public static final String DESIGN_EXCEPTION_FILE_NOT_FOUND = MessageConstants.DESIGN_PARSER_EXCEPTION_FILE_NOT_FOUND;
/**
* The design/library file was not found.
*/
public static final String DESIGN_EXCEPTION_FILE_FORMAT_NOT_SUPPORT = MessageConstants.DESIGN_PARSER_EXCEPTION_FILE_FORMAT_NOT_SUPPORT;
/**
* A custom color did not have a correct RGB value.
*/
public static final String DESIGN_EXCEPTION_RGB_REQUIRED = MessageConstants.DESIGN_PARSER_EXCEPTION_RGB_REQUIRED;
/**
* A custom color is missing the color name.
*/
public static final String DESIGN_EXCEPTION_COLOR_NAME_REQUIRED = MessageConstants.DESIGN_PARSER_EXCEPTION_COLOR_NAME_REQUIRED;
/**
* Use of "extends" to reference a style when "name" should be used.
*/
public static final String DESIGN_EXCEPTION_ILLEGAL_EXTENDS = MessageConstants.DESIGN_PARSER_EXCEPTION_ILLEGAL_EXTENDS;
/**
* Image item has more then one kind of reference type.
*/
public static final String DESIGN_EXCEPTION_IMAGE_REF_CONFLICT = MessageConstants.DESIGN_PARSER_EXCEPTION_IMAGE_REF_CONFLICT;
/**
* Image reference type is expression, but not both type expression and
* value expression are present in the design file.
*/
public static final String DESIGN_EXCEPTION_INVALID_IMAGEREF_EXPR_VALUE = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_IMAGEREF_EXPR_VALUE;
/**
* Image URL value is empty.
*/
public static final String DESIGN_EXCEPTION_INVALID_IMAGE_URL_VALUE = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_IMAGE_URL_VALUE;
/**
* One property is not encryptable.
*/
public static final String DESIGN_EXCEPTION_PROPERTY_IS_NOT_ENCRYPTABLE = MessageConstants.DESIGN_PARSER_EXCEPTION_PROPERTY_IS_NOT_ENCRYPTABLE;
/**
* Image Name is empty.
*/
public static final String DESIGN_EXCEPTION_INVALID_IMAGE_NAME_VALUE = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_IMAGE_NAME_VALUE;
/**
* An action Drillthrough is missing the "reportName" value.
*/
public static final String DESIGN_EXCEPTION_ACTION_REPORTNAME_REQUIRED = MessageConstants.DESIGN_PARSER_EXCEPTION_ACTION_REPORTNAME_REQUIRED;
/**
* An parameter in an Action is missing the "name" value.
*/
public static final String DESIGN_EXCEPTION_ACTION_PARAMETER_NAME_REQUIRED = MessageConstants.DESIGN_PARSER_EXCEPTION_ACTION_PARAMETER_NAME_REQUIRED;
/**
* Break the restriction that "occurrence == 1" for a choice type.
*/
public static final String DESIGN_EXCEPTION_CHOICE_RESTRICTION_VIOLATION = MessageConstants.DESIGN_PARSER_EXCEPTION_CHOICE_RESTRICTION_VIOLATION;
/**
* User-defined message is missing the "resouece-Key" value.
*/
public static final String DESIGN_EXCEPTION_MESSAGE_KEY_REQUIRED = MessageConstants.DESIGN_PARSER_EXCEPTION_MESSAGE_KEY_REQUIRED;
/**
* Two translations with the same locale appeared in a User-defined message.
*/
public static final String DESIGN_EXCEPTION_DUPLICATE_TRANSLATION_LOCALE = MessageConstants.DESIGN_PARSER_EXCEPTION_DUPLICATE_TRANSLATION_LOCALE;
/**
* The property name or member name is required.
*/
public static final String DESIGN_EXCEPTION_NAME_REQUIRED = MessageConstants.DESIGN_PARSER_EXCEPTION_NAME_REQUIRED;
/**
* The property is not a structure list.
*/
public static final String DESIGN_EXCEPTION_WRONG_STRUCTURE_LIST_TYPE = MessageConstants.DESIGN_PARSER_EXCEPTION_WRONG_STRUCTURE_LIST_TYPE;
/**
* The property is not an extended property.
*/
public static final String DESIGN_EXCEPTION_WRONG_EXTENDED_PROPERTY_TYPE = MessageConstants.DESIGN_PARSER_EXCEPTION_WRONG_EXTENDED_PROPERTY_TYPE;
/**
* The structure name is invalid.
*/
public static final String DESIGN_EXCEPTION_INVALID_STRUCTURE_NAME = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_STRUCTURE_NAME;
/**
* The property syntax is invalid.
*/
public static final String DESIGN_EXCEPTION_INVALID_PROPERTY_SYNTAX = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_PROPERTY_SYNTAX;
/**
* The property is not defined.
*/
public static final String DESIGN_EXCEPTION_UNDEFINED_PROPERTY = MessageConstants.DESIGN_PARSER_EXCEPTION_UNDEFINED_PROPERTY;
/**
* A unsupported exception occurred. This happens that the unicode signature
* in the design file is not UTF-8.
*/
public static final String DESIGN_EXCEPTION_UNSUPPORTED_ENCODING = MessageConstants.DESIGN_PARSER_EXCEPTION_UNSUPPORTED_ENCODING;
/**
* The report version is invalid.
*/
public static final String DESIGN_EXCEPTION_INVALID_VERSION = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_VERSION;
/**
* The element id is invalid.
*/
public static final String DESIGN_EXCEPTION_INVALID_ELEMENT_ID = MessageConstants.DESIGN_PARSER_EXCEPTION_INVALID_ELEMENT_ID;
/**
* The virtual parent element reference by baseId is not found in the parent.
*/
public static final String DESIGN_EXCEPTION_VIRTUAL_PARENT_NOT_FOUND = MessageConstants.DESIGN_PARSER_EXCEPTION_VIRTUAL_PARENT_NOT_FOUND;
/**
* The element id is duplicate.
*/
public static final String DESIGN_EXCEPTION_DUPLICATE_ELEMENT_ID = MessageConstants.DESIGN_PARSER_EXCEPTION_DUPLICATE_ELEMENT_ID;
/**
* The default element is not the same type of template element.
*/
public static final String DESIGN_EXCEPTION_INCONSISTENT_TEMPLATE_ELEMENT_TYPE = MessageConstants.DESIGN_PARSER_EXCEPTION_INCONSISTENT_TEMPLATE_ELEMENT_TYPE;
/**
* Error code indicating template parameter definition have no default
* element.
*/
public static final String DESIGN_EXCEPTION_MISSING_TEMPLATE_PARAMETER_DEFAULT = MessageConstants.DESIGN_PARSER_EXCEPTION_MISSING_TEMPLATE_PARAMETER_DEFAULT;
/**
* The simple list property has no definition in the element.
*/
public static final String DESIGN_EXCEPTION_WRONG_SIMPLE_LIST_TYPE = MessageConstants.DESIGN_PARSER_EXCEPTION_WRONG_SIMPLE_LIST_TYPE;
/**
* Constructs the design parser exception with the error code.
*
* @param errCode
* the error condition
*/
public DesignParserException( String errCode )
{
super( errCode );
}
/**
* Constructs the design parser exception with the file name, the property
* name and the error code.
*
* @param values
* the values for message
* @param errCode
* the error condition
*/
public DesignParserException( String[] values, String errCode )
{
super( errCode, values, null );
}
/*
* (non-Javadoc)
*
* @see java.lang.Throwable#getLocalizedMessage()
*/
public String getLocalizedMessage( )
{
if ( sResourceKey == DESIGN_EXCEPTION_FILE_NOT_FOUND
|| sResourceKey == DESIGN_EXCEPTION_FILE_FORMAT_NOT_SUPPORT
|| sResourceKey == DESIGN_EXCEPTION_UNDEFINED_PROPERTY
|| sResourceKey == DESIGN_EXCEPTION_PROPERTY_IS_NOT_ENCRYPTABLE
|| sResourceKey == DESIGN_EXCEPTION_UNSUPPORTED_VERSION
|| sResourceKey == DESIGN_EXCEPTION_VIRTUAL_PARENT_NOT_FOUND )
{
assert oaMessageArguments.length == 1;
return ModelMessages.getMessage( sResourceKey, oaMessageArguments );
}
else if ( sResourceKey == DESIGN_EXCEPTION_INVALID_ELEMENT_ID
|| sResourceKey == DESIGN_EXCEPTION_DUPLICATE_ELEMENT_ID
)
{
assert oaMessageArguments.length == 2;
return ModelMessages.getMessage( sResourceKey, oaMessageArguments );
}
else if ( sResourceKey == DESIGN_EXCEPTION_INCONSISTENT_TEMPLATE_ELEMENT_TYPE )
{
assert oaMessageArguments.length == 2;
return ModelMessages.getMessage( sResourceKey, oaMessageArguments );
}
else if ( sResourceKey == DESIGN_EXCEPTION_MISSING_TEMPLATE_PARAMETER_DEFAULT )
{
assert oaMessageArguments.length == 1;
return ModelMessages.getMessage( sResourceKey, oaMessageArguments );
}
return ModelMessages.getMessage( sResourceKey );
}
/*
* (non-Javadoc)
*
* @see java.lang.Throwable#getMessage()
*/
public String getMessage( )
{
return getLocalizedMessage( );
}
}
|
package net.time4j.clock;
import net.time4j.Moment;
import net.time4j.ZonalClock;
import net.time4j.base.TimeSource;
import net.time4j.tz.TZID;
import net.time4j.tz.Timezone;
/**
* <p>Abstract base clock implementation which allows local views within
* any timezone. </p>
*
* @author Meno Hochschild
* @since 2.1
*/
/*[deutsch]
* <p>Abstrakte Basisimplementierung, die eine lokale Sicht innerhalb einer
* Zeitzone bietet. </p>
*
* @author Meno Hochschild
* @since 2.1
*/
public abstract class AbstractClock
implements TimeSource<Moment> {
/**
* <p>Creates a local clock in platform timezone. </p>
*
* @return local clock in system timezone (using the platform timezone data)
* @since 3.3/4.2
* @see java.util.TimeZone
* @see Timezone#ofPlatform()
*/
/*[deutsch]
* <p>Erzeugt eine lokale Uhr in der Plattform-Zeitzone. </p>
*
* @return local clock in system timezone (using the platform timezone data)
* @since 3.3/4.2
* @see java.util.TimeZone
* @see Timezone#ofPlatform()
*/
public ZonalClock inPlatformView() {
return new ZonalClock(this, Timezone.ofPlatform());
}
/**
* <p>Creates a local clock in system timezone. </p>
*
* @return local clock in system timezone (using the best available timezone data)
* @since 2.1
* @see Timezone#ofSystem()
*/
/*[deutsch]
* <p>Erzeugt eine lokale Uhr in der System-Zeitzone. </p>
*
* @return local clock in system timezone (using the best available timezone data)
* @since 2.1
* @see Timezone#ofSystem()
*/
public ZonalClock inLocalView() {
return new ZonalClock(this, Timezone.ofSystem());
}
public ZonalClock inZonalView(TZID tzid) {
return new ZonalClock(this, tzid);
}
public ZonalClock inZonalView(String tzid) {
return new ZonalClock(this, tzid);
}
}
|
// Contributors: Kitching Simon <Simon.Kitching@orange.ch>
// Nicholas Wolff
package org.apache.log4j;
/**
Defines the minimum set of levels recognized by the system, that is
<code>OFF</code>, <code>FATAL</code>, <code>ERROR</code>,
<code>WARN</code>, <code>INFO</code, <code>DEBUG</code> and
<code>ALL</code>.
<p>The <code>Level</code> class may be subclassed to define a larger
level set.
@author Ceki Gülcü
*/
public class Level extends Priority {
/**
The <code>OFF</code> has the highest possible rank and is
intended to turn off logging. */
final static public Level OFF = new Level(OFF_INT, "OFF", 0);
/**
The <code>FATAL</code> level designates very severe error
events that will presumably lead the application to abort.
*/
final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0);
/**
The <code>ERROR</code> level designates error events that
might still allow the application to continue running. */
final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3);
/**
The <code>WARN</code> level designates potentially harmful situations.
*/
final static public Level WARN = new Level(WARN_INT, "WARN", 4);
/**
The <code>INFO</code> level designates informational messages
that highlight the progress of the application at coarse-grained
level. */
final static public Level INFO = new Level(INFO_INT, "INFO", 6);
/**
The <code>DEBUG</code> Level designates fine-grained
informational events that are most useful to debug an
application. */
final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
/**
The <code>ALL</code> has the lowest possible rank and is intended to
turn on all logging. */
final static public Level ALL = new Level(ALL_INT, "ALL", 7);
/**
Instantiate a Level object.
*/
protected
Level(int level, String levelStr, int syslogEquivalent) {
super(level, levelStr, syslogEquivalent);
}
/**
Convert the string passed as argument to a level. If the
conversion fails, then this method returns {@link #DEBUG}.
*/
public
static
Level toLevel(String sArg) {
return (Level) toLevel(sArg, Level.DEBUG);
}
/**
Convert an integer passed as argument to a level. If the
conversion fails, then this method returns {@link #DEBUG}.
*/
public
static
Level toLevel(int val) {
return (Level) toLevel(val, Level.DEBUG);
}
/**
Convert an integer passed as argument to a level. If the
conversion fails, then this method returns the specified default.
*/
public
static
Level toLevel(int val, Level defaultLevel) {
switch(val) {
case ALL_INT: return ALL;
case DEBUG_INT: return Level.DEBUG;
case INFO_INT: return Level.INFO;
case WARN_INT: return Level.WARN;
case ERROR_INT: return Level.ERROR;
case FATAL_INT: return Level.FATAL;
case OFF_INT: return OFF;
default: return defaultLevel;
}
}
/**
Convert the string passed as argument to a level. If the
conversion fails, then this method returns the value of
<code>defaultLevel</code>.
*/
public
static
Level toLevel(String sArg, Level defaultLevel) {
if(sArg == null)
return defaultLevel;
String s = sArg.toUpperCase();
if(s.equals("ALL")) return Level.ALL;
if(s.equals("DEBUG")) return Level.DEBUG;
//if(s.equals("FINE")) return Level.FINE;
if(s.equals("INFO")) return Level.INFO;
if(s.equals("WARN")) return Level.WARN;
if(s.equals("ERROR")) return Level.ERROR;
if(s.equals("FATAL")) return Level.FATAL;
if(s.equals("OFF")) return Level.OFF;
return defaultLevel;
}
}
|
package jlibs.xml.xsd;
import jlibs.core.lang.ArrayUtil;
import jlibs.core.lang.StringUtil;
import jlibs.xml.Namespaces;
import jlibs.xml.sax.XMLDocument;
import org.xml.sax.SAXException;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.stream.StreamResult;
/**
* This class is used to write xmlschema documents
*
* @author Santhosh Kumar T
*/
public class XSDocument extends Namespaces{
private XMLDocument xml;
public XSDocument(XMLDocument xml){
this.xml = xml;
}
public XSDocument(Result result, boolean omitXMLDeclaration, int indentAmount, String encoding) throws TransformerConfigurationException{
xml = new XMLDocument(result, omitXMLDeclaration, indentAmount, encoding);
}
public XMLDocument xml(){
return xml;
}
public XSDocument startDocument() throws SAXException{
xml.startDocument();
return this;
}
public XSDocument endDocument() throws SAXException{
xml.endDocument();
return this;
}
/**
* <xsd:schema [targetNamespace="$targetNamespace"]>
*/
public XSDocument startSchema(String targetNamespace) throws SAXException{
xml.startElement(URI_XSD, "schema");
if(targetNamespace!=null && !targetNamespace.isEmpty()){
xml.declarePrefix(targetNamespace);
xml.addAttribute("targetNamespace", targetNamespace);
}
return this;
}
/**
* </xsd:schema>
*/
public XSDocument endSchema() throws SAXException{
xml.endElement(URI_XSD, "schema");
return this;
}
/**
* <xsd:import [namespace="$namespace"] [schemaLocation="$schemaLocation"]/>
*/
public XSDocument addImport(String namespace, String schemaLocation) throws SAXException{
xml.startElement(URI_XSD, "import");
xml.addAttribute("namespace", namespace);
xml.addAttribute("schemaLocation", schemaLocation);
xml.endElement();
return this;
}
/**
* <xsd:include schemaLocation="$schemaLocation"/>
*/
public XSDocument addInclude(String schemaLocation) throws SAXException{
xml.startElement(URI_XSD, "include");
xml.addAttribute("schemaLocation", schemaLocation);
xml.endElement();
return this;
}
/**
* name="$name"
*/
public XSDocument name(String name) throws SAXException{
xml.addAttribute("name", name);
return this;
}
/**
* type="qname($typeNS, $typeLocalpart)"
*/
public XSDocument type(String typeNS, String typeLocalpart) throws SAXException{
xml.addAttribute("type", xml.toQName(typeNS, typeLocalpart));
return this;
}
/**
* ref="qname($typeNS, $typeLocalpart)"
*/
public XSDocument ref(String typeNS, String typeLocalpart) throws SAXException{
xml.addAttribute("ref", xml.toQName(typeNS, typeLocalpart));
return this;
}
/**
* if minOccurs!=1
* minOccurs="$minOccurs"
*
* if maxOccurs!=1
* maxOccurs="$maxOccurs"
*/
public void occurs(int minOccurs, int maxOccurs) throws SAXException{
if(minOccurs!= 1)
xml.addAttribute("minOccurs", String.valueOf(minOccurs));
if(maxOccurs!=1)
xml.addAttribute("maxOccurs", maxOccurs==-1 ? "unbounded" : String.valueOf(maxOccurs));
}
/**
* <xsd:element>
*/
public XSDocument startElement() throws SAXException{
xml.startElement(URI_XSD, "element");
return this;
}
/**
* </xsd:element>
*/
public XSDocument endElement() throws SAXException{
xml.endElement(URI_XSD, "element");
return this;
}
enum Constraint{ DEFAULT, FIXED, NONE }
/**
* $constraint="$defaultValue"
*/
public XSDocument constraint(Constraint constraint, String constraintValue) throws SAXException{
if(constraint!=Constraint.NONE)
xml.addAttribute(constraint.name().toLowerCase(), constraintValue);
return this;
}
/**
* use="$reqd ? required : optional"
*/
public XSDocument required(boolean reqd) throws SAXException{
xml.addAttribute("use", reqd ? "required" : "optional");
return this;
}
/**
* <xsd:attribute>
*/
public XSDocument startAttribute() throws SAXException{
xml.startElement(URI_XSD, "attribute");
return this;
}
/**
* </xsd:attribute>
*/
public XSDocument endAttribute() throws SAXException{
xml.endElement(URI_XSD, "attribute");
return this;
}
public XSDocument startSimpleType() throws SAXException{
xml.startElement(URI_XSD, "simpleType");
return this;
}
public XSDocument endSimpleType() throws SAXException{
xml.endElement(URI_XSD, "simpleType");
return this;
}
enum Compositor{ SEQUENCE, ALL, CHOICE }
public XSDocument startCompositor(Compositor compositor) throws SAXException{
xml.startElement(URI_XSD, compositor.name().toLowerCase());
return this;
}
public XSDocument endCompositor() throws SAXException{
xml.endElement();
return this;
}
enum Derivation{ EXTENSION, RESTRICTION, SUBSTITUTION }
public XSDocument startDerivation(Derivation derivation, String baseNS, String baseLocalpart) throws SAXException{
xml.startElement(URI_XSD, derivation.name().toLowerCase());
xml.addAttribute("base", xml.toQName(baseNS, baseLocalpart));
return this;
}
public XSDocument endDerivation() throws SAXException{
xml.endElement();
return this;
}
public XSDocument startComplexType() throws SAXException{
xml.startElement(URI_XSD, "complexType");
return this;
}
public XSDocument prohibit(Derivation... derivations) throws SAXException{
if(derivations.length>0){
boolean prohibitExtension = ArrayUtil.contains(derivations, Derivation.EXTENSION);
boolean prohibitRestriction = ArrayUtil.contains(derivations, Derivation.RESTRICTION);
if(prohibitExtension && prohibitRestriction)
xml.addAttribute("final", "#all");
else if(prohibitExtension)
xml.addAttribute("final", "extension");
else if(prohibitRestriction)
xml.addAttribute("final", "restriction");
}
return this;
}
public XSDocument endComplexType() throws SAXException{
xml.endElement(URI_XSD, "complexType");
return this;
}
enum Content{ SIMPLE, ELEMENT, EMPTY, MIXED }
public XSDocument startContent(Content content) throws SAXException{
xml.startElement(URI_XSD, (content==Content.SIMPLE) ? "simpleContent" : "complexContent");
if(content==Content.MIXED)
xml.addAttribute("mixed", "true");
return this;
}
public XSDocument endContent() throws SAXException{
xml.endElement();
return this;
}
enum Facet{
NONE, WHITE_SPACE,
LENGTH, MIN_LENGTH, MAX_LENGTH,
PATTERN, ENUMERATION, // multivalue facets
MAX_INCLUSIVE, MAX_EXCLUSIVE, MIN_EXCLUSIVE, MIN_INCLUSIVE,
TOTAL_DIGITS, FRACTION_DIGITS;
@Override
public String toString(){
String str = name().toLowerCase();
int underscore = str.indexOf('_');
if(underscore==-1)
return str;
else
return str.substring(0, underscore)+ StringUtil.capitalize(str.substring(underscore+1));
}
}
public XSDocument addFacet(Facet facet, String value, boolean fixed) throws SAXException{
xml.startElement(URI_XSD, facet.toString());
xml.addAttribute("value", value);
if(fixed)
xml.addAttribute("fixed", "true");
xml.endElement();
return this;
}
public XSDocument addMultiValueFacet(Facet facet, String... values) throws SAXException{
String facetName = facet.toString();
for(String value: values){
xml.startElement(URI_XSD, facetName);
xml.addAttribute("value", value);
xml.endElement();
}
return this;
}
public XSDocument addList(String itemTypeNS, String itemTypeLocalpart) throws SAXException{
xml.startElement(URI_XSD, "list");
xml.addAttribute("itemType", xml.toQName(itemTypeNS, itemTypeLocalpart));
xml.endElement();
return this;
}
public XSDocument startUnion(String... memberParts) throws SAXException{
xml.startElement(URI_XSD, "union");
StringBuilder buff = new StringBuilder();
for(int i=0; i<memberParts.length; i+=2){
if(buff.length()>0)
buff.append(' ');
buff.append(xml.toQName(memberParts[i], memberParts[i+1]));
}
if(buff.length()>0)
xml.addAttribute("memberTypes", buff.toString());
xml.endElement();
return this;
}
public XSDocument endUnion() throws SAXException{
xml.endElement();
return this;
}
public XSDocument startAnnotation() throws SAXException{
xml.startElement(URI_XSD, "annotation");
return this;
}
public XSDocument addDocumentation(String doc) throws SAXException{
xml.addElement(URI_XSD, "documentation", doc);
return this;
}
public XSDocument endAnnotation() throws SAXException{
xml.endElement(URI_XSD, "annotation");
return this;
}
public static void main(String[] args) throws TransformerConfigurationException, SAXException{
XSDocument xsd = new XSDocument(new StreamResult(System.out), false, 4, null);
xsd.startDocument();
{
String n1 = "http:
String n2 = "http:
xsd.xml().declarePrefix("n1", n1);
xsd.xml().declarePrefix("n2", n2);
xsd.startSchema(n1);
{
xsd.addImport(n2, "imports/b.xsd");
xsd.startComplexType().name("MyType");
{
xsd.startCompositor(Compositor.SEQUENCE);
xsd.startElement().ref(n1, "e1").endElement();
xsd.endCompositor();
}
xsd.endComplexType();
xsd.startElement().name("root").type(n1, "MyType").endElement();
}
xsd.endSchema();
}
xsd.endDocument();
}
}
|
package picard.vcf;
import htsjdk.samtools.Defaults;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.ValidationStringency;
import htsjdk.samtools.liftover.LiftOver;
import htsjdk.samtools.reference.ReferenceSequenceFileWalker;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.CollectionUtil;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.ProgressLogger;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.samtools.util.SortingCollection;
import htsjdk.samtools.util.StringUtil;
import htsjdk.variant.variantcontext.*;
import htsjdk.variant.variantcontext.writer.Options;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder;
import htsjdk.variant.vcf.VCFFileReader;
import htsjdk.variant.vcf.VCFFilterHeaderLine;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLineType;
import htsjdk.variant.vcf.VCFInfoHeaderLine;
import htsjdk.variant.vcf.VCFRecordCodec;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.CommandLineProgramProperties;
import picard.cmdline.Option;
import picard.cmdline.StandardOptionDefinitions;
import picard.cmdline.programgroups.VcfOrBcf;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Tool for lifting over a VCF to another genome build and producing a properly header'd,
* sorted and indexed VCF in one go.
*
* @author Tim Fennell
*/
@CommandLineProgramProperties(
usage = LiftoverVcf.USAGE_SUMMARY + LiftoverVcf.USAGE_DETAILS,
usageShort = LiftoverVcf.USAGE_SUMMARY,
programGroup = VcfOrBcf.class
)
public class LiftoverVcf extends CommandLineProgram {
static final String USAGE_SUMMARY = "Lifts over a VCF file from one reference build to another. ";
static final String USAGE_DETAILS = "This tool adjusts the coordinates of variants within a VCF file to match a new reference. The " +
"output file will be sorted and indexed using the target reference build. To be clear, REFERENCE_SEQUENCE should be the " +
"<em>target</em> reference build. The tool is based on the UCSC liftOver tool (see: http://genome.ucsc.edu/cgi-bin/hgLiftOver) " +
"and uses a UCSC chain file to guide its operation. <br /><br />" +
"Note that records may be rejected because they cannot be lifted over or because of sequence incompatibilities between the " +
"source and target reference genomes. Rejected records will be emitted with filters to the REJECT file, using the source " +
"genome coordinates.<br />" +
"<h4>Usage example:</h4>" +
"<pre>" +
"java -jar picard.jar LiftoverVcf \\<br />" +
" I=input.vcf \\<br />" +
" O=lifted_over.vcf \\<br />" +
" CHAIN=b37tohg19.chain \\<br />" +
" REJECT=rejected_variants.vcf \\<br />" +
" R=reference_sequence.fasta" +
"</pre>" +
"For additional information, please see: http://genome.ucsc.edu/cgi-bin/hgLiftOver" +
"<hr />";
@Option(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="The input VCF/BCF file to be lifted over.")
public File INPUT;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="The output location to write the lifted over VCF/BCF to.")
public File OUTPUT;
@Option(shortName="C", doc="The liftover chain file. See https://genome.ucsc.edu/goldenPath/help/chain.html for a description" +
" of chain files. See http://hgdownload.soe.ucsc.edu/downloads.html#terms for where to download chain files.")
public File CHAIN;
@Option(doc="File to which to write rejected records.")
public File REJECT;
@Option(shortName = StandardOptionDefinitions.REFERENCE_SHORT_NAME, common=false,
doc = "The reference sequence (fasta) for the TARGET genome build. The fasta file must have an " +
"accompanying sequence dictionary (.dict file).")
public File REFERENCE_SEQUENCE = Defaults.REFERENCE_FASTA;
// Option on whether or not to provide a warning, or error message and exit if a missing contig is encountered
@Option(shortName = "WMC", doc = "Warn on missing contig.", optional = true)
public boolean WARN_ON_MISSING_CONTIG = false;
// Option on whether or not to write the original contig/position of the variant to the INFO field
@Option(doc = "Write the original contig/position for lifted variants to the INFO field.", optional = true)
public boolean WRITE_ORIGINAL_POSITION = false;
@Option(doc = "The minimum percent match required for a variant to be lifted.", optional = true)
public double LIFTOVER_MIN_MATCH = 1.0;
@Option(doc = "Allow INFO and FORMAT in the records that are not found in the header", optional = true)
public boolean ALLOW_MISSING_FIELDS_IN_HEADER = false;
// When a contig used in the chain is not in the reference, exit with this value instead of 0.
protected static int EXIT_CODE_WHEN_CONTIG_NOT_IN_REFERENCE = 1;
/** Filter name to use when a target cannot be lifted over. */
public static final String FILTER_CANNOT_LIFTOVER_INDEL = "ReverseComplementedIndel";
/** Filter name to use when a target cannot be lifted over. */
public static final String FILTER_NO_TARGET = "NoTarget";
/** Filter name to use when a target is lifted over, but the reference allele doens't match the new reference. */
public static final String FILTER_MISMATCHING_REF_ALLELE = "MismatchedRefAllele";
/** Filters to be added to the REJECT file. */
private static final List<VCFFilterHeaderLine> FILTERS = CollectionUtil.makeList(
new VCFFilterHeaderLine(FILTER_CANNOT_LIFTOVER_INDEL, "Indel falls into a reverse complemented region in the target genome."),
new VCFFilterHeaderLine(FILTER_NO_TARGET, "Variant could not be lifted between genome builds."),
new VCFFilterHeaderLine(FILTER_MISMATCHING_REF_ALLELE, "Reference allele does not match reference genome sequence after liftover.")
);
/** Attribute used to store the name of the source contig/chromosome prior to liftover. */
public static final String ORIGINAL_CONTIG = "OriginalContig";
/** Attribute used to store the position of the variant on the source contig prior to liftover. */
public static final String ORIGINAL_START = "OriginalStart";
/** Metadata to be added to the Passing file. */
private static final List<VCFInfoHeaderLine> ATTRS = CollectionUtil.makeList(
new VCFInfoHeaderLine(ORIGINAL_CONTIG, 1, VCFHeaderLineType.String, "The name of the source contig/chromosome prior to liftover."),
new VCFInfoHeaderLine(ORIGINAL_START, 1, VCFHeaderLineType.String, "The position of the variant on the source contig prior to liftover.")
);
private final Log log = Log.getInstance(LiftoverVcf.class);
// Stock main method
public static void main(final String[] args) {
new LiftoverVcf().instanceMainWithExit(args);
}
@Override protected int doWork() {
IOUtil.assertFileIsReadable(INPUT);
IOUtil.assertFileIsReadable(REFERENCE_SEQUENCE);
IOUtil.assertFileIsReadable(CHAIN);
IOUtil.assertFileIsWritable(OUTPUT);
IOUtil.assertFileIsWritable(REJECT);
// Setup the inputs
final LiftOver liftOver = new LiftOver(CHAIN);
final VCFFileReader in = new VCFFileReader(INPUT, false);
log.info("Loading up the target reference genome.");
final ReferenceSequenceFileWalker walker = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE);
final Map<String,byte[]> refSeqs = new HashMap<String,byte[]>();
for (final SAMSequenceRecord rec: walker.getSequenceDictionary().getSequences()) {
refSeqs.put(rec.getSequenceName(), walker.get(rec.getSequenceIndex()).getBases());
}
CloserUtil.close(walker);
// Setup the outputs
final VCFHeader inHeader = in.getFileHeader();
final VCFHeader outHeader = new VCFHeader(inHeader);
outHeader.setSequenceDictionary(walker.getSequenceDictionary());
if (WRITE_ORIGINAL_POSITION) {
for (final VCFInfoHeaderLine line : ATTRS) outHeader.addMetaDataLine(line);
}
final VariantContextWriter out = new VariantContextWriterBuilder().setOption(Options.INDEX_ON_THE_FLY)
.modifyOption(Options.ALLOW_MISSING_FIELDS_IN_HEADER, ALLOW_MISSING_FIELDS_IN_HEADER)
.setOutputFile(OUTPUT).setReferenceDictionary(walker.getSequenceDictionary()).build();
out.writeHeader(outHeader);
final VariantContextWriter rejects = new VariantContextWriterBuilder().setOutputFile(REJECT).unsetOption(Options.INDEX_ON_THE_FLY)
.modifyOption(Options.ALLOW_MISSING_FIELDS_IN_HEADER, ALLOW_MISSING_FIELDS_IN_HEADER)
.build();
final VCFHeader rejectHeader = new VCFHeader(in.getFileHeader());
for (final VCFFilterHeaderLine line : FILTERS) rejectHeader.addMetaDataLine(line);
if (WRITE_ORIGINAL_POSITION) {
for (final VCFInfoHeaderLine line : ATTRS) rejectHeader.addMetaDataLine(line);
}
rejects.writeHeader(rejectHeader);
// Read the input VCF, lift the records over and write to the sorting
// collection.
long failedLiftover = 0, failedAlleleCheck = 0, total = 0;
log.info("Lifting variants over and sorting.");
final SortingCollection<VariantContext> sorter = SortingCollection.newInstance(VariantContext.class,
new VCFRecordCodec(outHeader, ALLOW_MISSING_FIELDS_IN_HEADER || VALIDATION_STRINGENCY != ValidationStringency.STRICT),
outHeader.getVCFRecordComparator(),
MAX_RECORDS_IN_RAM,
TMP_DIR);
ProgressLogger progress = new ProgressLogger(log, 1000000, "read");
// a mapping from original allele to reverse complemented allele
final Map<Allele, Allele> reverseComplementAlleleMap = new HashMap<Allele, Allele>(10);
for (final VariantContext ctx : in) {
++total;
final Interval source = new Interval(ctx.getContig(), ctx.getStart(), ctx.getEnd(), false, ctx.getContig() + ":" + ctx.getStart() + "-" + ctx.getEnd());
final Interval target = liftOver.liftOver(source, LIFTOVER_MIN_MATCH);
// if the target is null OR (the target is reverse complemented AND the variant is an indel or mixed), then we cannot lift it over
if (target == null || (target.isNegativeStrand() && (ctx.isMixed() || ctx.isIndel()))) {
final String reason = (target == null) ? FILTER_NO_TARGET : FILTER_CANNOT_LIFTOVER_INDEL;
rejects.add(new VariantContextBuilder(ctx).filter(reason).make());
failedLiftover++;
} else if (!refSeqs.containsKey(target.getContig())) {
rejects.add(new VariantContextBuilder(ctx).filter(FILTER_NO_TARGET).make());
failedLiftover++;
String missingContigMessage = "Encountered a contig, " + target.getContig() + " that is not part of the target reference.";
if(WARN_ON_MISSING_CONTIG) {
log.warn(missingContigMessage);
} else {
log.error(missingContigMessage);
return EXIT_CODE_WHEN_CONTIG_NOT_IN_REFERENCE;
}
} else {
// Fix the alleles if we went from positive to negative strand
reverseComplementAlleleMap.clear();
final List<Allele> alleles = new ArrayList<Allele>();
for (final Allele oldAllele : ctx.getAlleles()) {
if (target.isPositiveStrand() || oldAllele.isSymbolic()) {
alleles.add(oldAllele);
}
else {
final Allele fixedAllele = Allele.create(SequenceUtil.reverseComplement(oldAllele.getBaseString()), oldAllele.isReference());
alleles.add(fixedAllele);
reverseComplementAlleleMap.put(oldAllele, fixedAllele);
}
}
// Build the new variant context
final VariantContextBuilder builder = new VariantContextBuilder(
ctx.getSource(),
target.getContig(),
target.getStart(),
target.getEnd(),
alleles);
builder.id(ctx.getID());
builder.attributes(ctx.getAttributes());
if (WRITE_ORIGINAL_POSITION) {
builder.attribute(ORIGINAL_CONTIG, source.getContig());
builder.attribute(ORIGINAL_START, source.getStart());
}
builder.genotypes(fixGenotypes(ctx.getGenotypes(), reverseComplementAlleleMap));
builder.filters(ctx.getFilters());
builder.log10PError(ctx.getLog10PError());
// Check that the reference allele still agrees with the reference sequence
boolean mismatchesReference = false;
for (final Allele allele : builder.getAlleles()) {
if (allele.isReference()) {
final byte[] ref = refSeqs.get(target.getContig());
final String refString = StringUtil.bytesToString(ref, target.getStart()-1, target.length());
if (!refString.equalsIgnoreCase(allele.getBaseString())) {
mismatchesReference = true;
}
break;
}
}
if (mismatchesReference) {
rejects.add(new VariantContextBuilder(ctx).filter(FILTER_MISMATCHING_REF_ALLELE).make());
failedAlleleCheck++;
}
else {
sorter.add(builder.make());
}
}
progress.record(ctx.getContig(), ctx.getStart());
}
final NumberFormat pfmt = new DecimalFormat("0.0000%");
final String pct = pfmt.format((failedLiftover + failedAlleleCheck) / (double) total);
log.info("Processed ", total, " variants.");
log.info(failedLiftover, " variants failed to liftover.");
log.info(failedAlleleCheck, " variants lifted over but had mismatching reference alleles after lift over.");
log.info(pct, " of variants were not successfully lifted over and written to the output.");
rejects.close();
in.close();
// Write the sorted outputs to the final output file
sorter.doneAdding();
progress = new ProgressLogger(log, 1000000, "written");
log.info("Writing out sorted records to final VCF.");
for (final VariantContext ctx : sorter) {
out.add(ctx);
progress.record(ctx.getContig(), ctx.getStart());
}
out.close();
sorter.cleanup();
return 0;
}
protected static GenotypesContext fixGenotypes(final GenotypesContext originals, final Map<Allele, Allele> reverseComplementAlleleMap) {
// optimization: if nothing needs to be fixed then don't bother
if ( reverseComplementAlleleMap.isEmpty() ) {
return originals;
}
final GenotypesContext fixedGenotypes = GenotypesContext.create(originals.size());
for ( final Genotype genotype : originals ) {
final List<Allele> fixedAlleles = new ArrayList<Allele>();
for ( final Allele allele : genotype.getAlleles() ) {
final Allele fixedAllele = reverseComplementAlleleMap.containsKey(allele) ? reverseComplementAlleleMap.get(allele) : allele;
fixedAlleles.add(fixedAllele);
}
fixedGenotypes.add(new GenotypeBuilder(genotype).alleles(fixedAlleles).make());
}
return fixedGenotypes;
}
}
|
package name.abuchen.portfolio.datatransfer.pdf.viac;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.assertThat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import name.abuchen.portfolio.datatransfer.Extractor.BuySellEntryItem;
import name.abuchen.portfolio.datatransfer.Extractor.Item;
import name.abuchen.portfolio.datatransfer.Extractor.SecurityItem;
import name.abuchen.portfolio.datatransfer.Extractor.TransactionItem;
import name.abuchen.portfolio.datatransfer.actions.AssertImportActions;
import name.abuchen.portfolio.datatransfer.pdf.PDFInputFile;
import name.abuchen.portfolio.datatransfer.pdf.ViacPDFExtractor;
import name.abuchen.portfolio.model.AccountTransaction;
import name.abuchen.portfolio.model.BuySellEntry;
import name.abuchen.portfolio.model.Client;
import name.abuchen.portfolio.model.PortfolioTransaction;
import name.abuchen.portfolio.model.Security;
import name.abuchen.portfolio.model.Transaction.Unit;
import name.abuchen.portfolio.money.CurrencyUnit;
import name.abuchen.portfolio.money.Money;
import name.abuchen.portfolio.money.Values;
@SuppressWarnings("nls")
public class ViacPDFExtractorTest
{
@Test
public void testKauf01()
{
Client client = new Client();
ViacPDFExtractor extractor = new ViacPDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "ViacKauf01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
// check security
Optional<Item> item = results.stream().filter(i -> i instanceof SecurityItem).findFirst();
assertThat(item.isPresent(), is(true));
Security security = ((SecurityItem) item.orElseThrow(IllegalArgumentException::new)).getSecurity();
assertThat(security.getIsin(), is("IE00B5BMR087"));
assertThat(security.getCurrencyCode(), is(CurrencyUnit.USD));
assertThat(security.getName(), is("iShares Core S&P500"));
// check transaction
BuySellEntry entry = (BuySellEntry) results.stream().filter(i -> i instanceof BuySellEntryItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(entry.getPortfolioTransaction().getType(), is(PortfolioTransaction.Type.BUY));
assertThat(entry.getAccountTransaction().getType(), is(AccountTransaction.Type.BUY));
assertThat(entry.getPortfolioTransaction().getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(360.43))));
assertThat(entry.getPortfolioTransaction().getDateTime(), is(LocalDateTime.parse("2018-07-05T00:00")));
assertThat(entry.getPortfolioTransaction().getShares(), is(Values.Share.factorize(1.369)));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.TAX),
is(Money.of("CHF", Values.Amount.factorize(0.46))));
Unit gross = entry.getPortfolioTransaction().getUnit(Unit.Type.GROSS_VALUE)
.orElseThrow(IllegalArgumentException::new);
assertThat(gross.getAmount(), is(Money.of("CHF", Values.Amount.factorize(359.98))));
assertThat(gross.getForex(), is(Money.of(CurrencyUnit.USD, Values.Amount.factorize(359.27))));
}
@Test
public void testKauf02()
{
Client client = new Client();
ViacPDFExtractor extractor = new ViacPDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "ViacKauf02.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
// check security
Optional<Item> item = results.stream().filter(i -> i instanceof SecurityItem).findFirst();
assertThat(item.isPresent(), is(true));
Security security = ((SecurityItem) item.orElseThrow(IllegalArgumentException::new)).getSecurity();
assertThat(security.getIsin(), is("CH0110869143"));
assertThat(security.getCurrencyCode(), is("CHF"));
assertThat(security.getName(), is("CSIF SPI Extra"));
// check transaction
BuySellEntry entry = (BuySellEntry) results.stream().filter(i -> i instanceof BuySellEntryItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(entry.getPortfolioTransaction().getType(), is(PortfolioTransaction.Type.BUY));
assertThat(entry.getAccountTransaction().getType(), is(AccountTransaction.Type.BUY));
assertThat(entry.getPortfolioTransaction().getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(104.78))));
assertThat(entry.getPortfolioTransaction().getDateTime(), is(LocalDateTime.parse("2018-07-04T00:00")));
assertThat(entry.getPortfolioTransaction().getShares(), is(Values.Share.factorize(0.051)));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.TAX),
is(Money.of("CHF", 0L)));
}
@Test
public void testInterest01()
{
Client client = new Client();
ViacPDFExtractor extractor = new ViacPDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "ViacZins01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(1));
new AssertImportActions().check(results, "CHF");
AccountTransaction transaction = (AccountTransaction) results.stream().filter(i -> i instanceof TransactionItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(transaction.getType(), is(AccountTransaction.Type.INTEREST));
assertThat(transaction.getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(0.04))));
assertThat(transaction.getDateTime(), is(LocalDateTime.parse("2019-03-31T00:00")));
}
@Test
public void testFees01()
{
Client client = new Client();
ViacPDFExtractor extractor = new ViacPDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "ViacGebuhren01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(1));
new AssertImportActions().check(results, "CHF");
AccountTransaction transaction = (AccountTransaction) results.stream().filter(i -> i instanceof TransactionItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(transaction.getType(), is(AccountTransaction.Type.FEES));
assertThat(transaction.getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(1.11))));
assertThat(transaction.getDateTime(), is(LocalDateTime.parse("2019-01-31T00:00")));
}
}
|
package org.nuxeo.ecm.platform.search.ejb;
import java.io.Serializable;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJBException;
import javax.ejb.MessageDriven;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.security.auth.login.LoginContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.search.NXSearch;
import org.nuxeo.ecm.core.search.api.client.SearchService;
import org.nuxeo.ecm.core.search.api.events.IndexingEventConf;
import org.nuxeo.ecm.core.search.threading.IndexingThreadPool;
import org.nuxeo.ecm.platform.events.api.DocumentMessage;
import org.nuxeo.ecm.platform.events.api.EventMessage;
import org.nuxeo.runtime.api.Framework;
/**
* Search message listener.
*
* <p>
* Listen for messages on the NXP topic to trigger operations against the search
* engine service.
* </p>
*
* <p>
* Note, this mdb should be deployed on the same node as the core search service
* for now.
* </p>
*
* @author <a href="mailto:ja@nuxeo.com">Julien Anguenot</a>
*/
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/NXPMessages"),
@ActivationConfigProperty(propertyName = "providerAdapterJNDI", propertyValue = "java:/NXCoreEventsProvider"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SearchMessageListener implements MessageListener {
private static final Log log = LogFactory.getLog(SearchMessageListener.class);
private transient SearchService service;
private LoginContext loginCtx;
private SearchService getSearchService() {
if (service == null) {
// XXX : use local interface since the MDB is part of the Facade
// package
// service = SearchServiceDelegate.getRemoteSearchService();
service = NXSearch.getSearchService();
}
return service;
}
private void login() throws Exception {
loginCtx = Framework.login();
}
private void logout() throws Exception {
if (loginCtx != null) {
loginCtx.logout();
}
}
public void onMessage(Message message) {
// check first preconditions
SearchService service = getSearchService();
// Check if the search service is active
if (!service.isEnabled()) {
return;
}
Serializable obj = null;
try {
obj = ((ObjectMessage) message).getObject();
} catch (JMSException e) {
return;
}
if (!(obj instanceof DocumentMessage)) {
return;
}
DocumentMessage doc = (DocumentMessage) obj;
String eventId = doc.getEventId();
Boolean duplicatedMessage = (Boolean) doc.getEventInfo().get(
EventMessage.DUPLICATED);
if (duplicatedMessage != null && duplicatedMessage) {
log.debug("Message " + eventId
+ " is marked as duplicated, ignoring");
return;
}
IndexingEventConf eventConf = service.getIndexingEventConfByName(eventId);
if (eventConf == null) {
log.debug("not interested about event with id=" + eventId);
return;
}
if (eventConf.getMode().equals(IndexingEventConf.ONLY_SYNC)) {
log.debug("Event with id=" + eventId
+ " should only be processed in sync");
return;
}
if (eventConf.getMode().equals(IndexingEventConf.NEVER)) {
log.debug("Event with id=" + eventId
+ " is desactivated for indexing");
return;
}
// event accepted -> login
try {
login();
} catch (Exception e) {
throw new EJBException(e);
}
// :XXX: deal with other events such as audit, relations, etc...
try {
boolean recursive = eventConf.isRecursive();
String action = eventConf.getAction();
if (IndexingEventConf.INDEX.equals(action)
|| IndexingEventConf.RE_INDEX.equals(action)) {
// Check if the dm is indexable.
// For now only based on explicit registration of the doc type
// against the search service. (i.e : versus core type facet
// based)
if (service.getIndexableDocTypeFor(doc.getType()) == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("indexing " + doc.getPath());
}
// Compute full text as well.
IndexingThreadPool.index(doc, recursive, true);
} else if (IndexingEventConf.UN_INDEX.equals(action)) {
if (log.isDebugEnabled()) {
log.debug("asynchronous unindexing " + doc.getPath());
}
IndexingThreadPool.unindex(doc, recursive);// Compute
}
} catch (Exception e) {
throw new EJBException(e);
} finally {
try {
logout();
} catch (Exception e) {
log.error("Impossible to logout", e);
}
}
}
}
|
package org.opennms.web.rest.v1.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.MockLogAppender;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase;
import org.opennms.core.xml.JaxbUtils;
import org.opennms.netmgt.config.collectd.jmx.JmxDatacollectionConfig;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath*:/META-INF/opennms/component-service.xml",
"classpath*:/META-INF/opennms/component-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath:/META-INF/opennms/mockEventIpcManager.xml",
"file:src/main/webapp/WEB-INF/applicationContext-svclayer.xml",
"file:src/main/webapp/WEB-INF/applicationContext-cxf-common.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class JmxDataCollectionConfigResourceIT extends AbstractSpringJerseyRestTestCase {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(PollerConfigurationResourceIT.class);
@Override
protected void afterServletStart() throws Exception {
MockLogAppender.setupLogging(true, "DEBUG");
}
@Test
public void testJmxConfig() throws Exception {
sendRequest(GET, "/config/jmx/notfound", 404);
String xml = sendRequest(GET, "/config/jmx", 200);
JmxDatacollectionConfig config = JaxbUtils.unmarshal(JmxDatacollectionConfig.class, xml);
assertNotNull(config);
assertEquals(4, config.getJmxCollectionCount());
assertEquals(config.getJmxCollection(0).getRrd().getStep(), 300);
assertEquals("jboss", config.getJmxCollection(0).getName());
assertEquals(4, config.getJmxCollection("jboss").getMbeanCount());
assertEquals(4, config.getJmxCollection(0).getMbeanCount());
assertEquals(config.getJmxCollection(1).getRrd().getStep(), 300);
assertEquals("jsr160", config.getJmxCollection(1).getName());
assertEquals(31, config.getJmxCollection("jsr160").getMbeanCount());
assertEquals(31, config.getJmxCollection(1).getMbeanCount());
assertEquals(config.getJmxCollection(2).getRrd().getStep(), 300);
assertEquals("cassandra30x", config.getJmxCollection(2).getName());
assertEquals(config.getJmxCollection(3).getRrd().getStep(), 300);
assertEquals("cassandra30x-newts", config.getJmxCollection(3).getName());
}
}
|
package org.eclipse.mylyn.internal.bugzilla.ui.search;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.fieldassist.ComboContentAdapter;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin;
import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylyn.internal.bugzilla.core.RepositoryConfiguration;
import org.eclipse.mylyn.internal.bugzilla.ui.BugzillaUiPlugin;
import org.eclipse.mylyn.internal.bugzilla.ui.editor.KeywordsDialog;
import org.eclipse.mylyn.internal.tasks.ui.util.WebBrowserDialog;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.wizards.AbstractRepositoryQueryPage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter;
import org.eclipse.ui.progress.IProgressService;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
/**
* Bugzilla search page
*
* @author Mik Kersten (hardening of prototype)
* @author Frank Becker
*/
public class BugzillaSearchPage extends AbstractRepositoryQueryPage implements Listener {
private static final int HEIGHT_ATTRIBUTE_COMBO = 70;
// protected Combo repositoryCombo = null;
private static ArrayList<BugzillaSearchData> previousSummaryPatterns = new ArrayList<BugzillaSearchData>(20);
private static ArrayList<BugzillaSearchData> previousEmailPatterns = new ArrayList<BugzillaSearchData>(20);
private static ArrayList<BugzillaSearchData> previousEmailPatterns2 = new ArrayList<BugzillaSearchData>(20);
private static ArrayList<BugzillaSearchData> previousCommentPatterns = new ArrayList<BugzillaSearchData>(20);
private static ArrayList<BugzillaSearchData> previousKeywords = new ArrayList<BugzillaSearchData>(20);
private boolean firstTime = true;
private IDialogSettings fDialogSettings;
private static final String[] patternOperationText = { Messages.BugzillaSearchPage_all_words,
Messages.BugzillaSearchPage_any_word, Messages.BugzillaSearchPage_regexp,
Messages.BugzillaSearchPage_notregexp };
private static final String[] patternOperationValues = { "allwordssubstr", "anywordssubstr", "regexp", "notregexp" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
private static final String[] emailOperationText = { Messages.BugzillaSearchPage_substring,
Messages.BugzillaSearchPage_exact, Messages.BugzillaSearchPage_regexp,
Messages.BugzillaSearchPage_notregexp };
private static final String[] emailOperationValues = { "substring", "exact", "regexp", "notregexp" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
private static final String[] keywordOperationText = { Messages.BugzillaSearchPage_all,
Messages.BugzillaSearchPage_any, Messages.BugzillaSearchPage_none };
private static final String[] keywordOperationValues = { "allwords", "anywords", "nowords" }; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
private static final String[] emailRoleValues = { "emailassigned_to1", "emailreporter1", "emailcc1", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"emaillongdesc1" }; //$NON-NLS-1$
private static final String[] emailRoleValues2 = { "emailassigned_to2", "emailreporter2", "emailcc2", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"emaillongdesc2" }; //$NON-NLS-1$
// dialog store id constants
private final static String DIALOG_BOUNDS_KEY = "ResizableDialogBounds"; //$NON-NLS-1$
private static final String X = "x"; //$NON-NLS-1$
private static final String Y = "y"; //$NON-NLS-1$
private static final String WIDTH = "width"; //$NON-NLS-1$
private static final String HEIGHT = "height"; //$NON-NLS-1$
private IRepositoryQuery originalQuery = null;
protected boolean restoring = false;
private boolean restoreQueryOptions = true;
protected Combo summaryPattern;
protected Combo summaryOperation;
protected List product;
protected List os;
protected List hardware;
protected List priority;
protected List severity;
protected List resolution;
protected List status;
protected Combo commentOperation;
protected Combo commentPattern;
protected List component;
protected List version;
protected List target;
protected Combo emailOperation;
protected Combo emailOperation2;
protected Combo emailPattern;
protected Combo emailPattern2;
protected Button[] emailButtons;
protected Button[] emailButtons2;
private Combo keywords;
private Combo keywordsOperation;
protected Text daysText;
// /** File containing saved queries */
// protected static SavedQueryFile input;
// /** "Remember query" button */
// protected Button saveButton;
// /** "Saved queries..." button */
// protected Button loadButton;
// /** Run a remembered query */
// protected boolean rememberedQuery = false;
/** Index of the saved query to run */
protected int selIndex;
// Dialog store taskId constants
protected final static String PAGE_NAME = "BugzillaSearchPage"; //$NON-NLS-1$
private static final String STORE_PRODUCT_ID = PAGE_NAME + ".PRODUCT"; //$NON-NLS-1$
private static final String STORE_COMPONENT_ID = PAGE_NAME + ".COMPONENT"; //$NON-NLS-1$
private static final String STORE_VERSION_ID = PAGE_NAME + ".VERSION"; //$NON-NLS-1$
private static final String STORE_MSTONE_ID = PAGE_NAME + ".MILESTONE"; //$NON-NLS-1$
private static final String STORE_STATUS_ID = PAGE_NAME + ".STATUS"; //$NON-NLS-1$
private static final String STORE_RESOLUTION_ID = PAGE_NAME + ".RESOLUTION"; //$NON-NLS-1$
private static final String STORE_SEVERITY_ID = PAGE_NAME + ".SEVERITY"; //$NON-NLS-1$
private static final String STORE_PRIORITY_ID = PAGE_NAME + ".PRIORITY"; //$NON-NLS-1$
private static final String STORE_HARDWARE_ID = PAGE_NAME + ".HARDWARE"; //$NON-NLS-1$
private static final String STORE_OS_ID = PAGE_NAME + ".OS"; //$NON-NLS-1$
private static final String STORE_SUMMARYMATCH_ID = PAGE_NAME + ".SUMMARYMATCH"; //$NON-NLS-1$
private static final String STORE_COMMENTMATCH_ID = PAGE_NAME + ".COMMENTMATCH"; //$NON-NLS-1$
private static final String STORE_EMAILMATCH_ID = PAGE_NAME + ".EMAILMATCH"; //$NON-NLS-1$
private static final String STORE_EMAIL2MATCH_ID = PAGE_NAME + ".EMAIL2MATCH"; //$NON-NLS-1$
private static final String STORE_EMAILBUTTON_ID = PAGE_NAME + ".EMAILATTR"; //$NON-NLS-1$
private static final String STORE_EMAIL2BUTTON_ID = PAGE_NAME + ".EMAIL2ATTR"; //$NON-NLS-1$
private static final String STORE_SUMMARYTEXT_ID = PAGE_NAME + ".SUMMARYTEXT"; //$NON-NLS-1$
private static final String STORE_COMMENTTEXT_ID = PAGE_NAME + ".COMMENTTEXT"; //$NON-NLS-1$
private static final String STORE_EMAILADDRESS_ID = PAGE_NAME + ".EMAILADDRESS"; //$NON-NLS-1$
private static final String STORE_EMAIL2ADDRESS_ID = PAGE_NAME + ".EMAIL2ADDRESS"; //$NON-NLS-1$
private static final String STORE_KEYWORDS_ID = PAGE_NAME + ".KEYWORDS"; //$NON-NLS-1$
private static final String STORE_KEYWORDSMATCH_ID = PAGE_NAME + ".KEYWORDSMATCH"; //$NON-NLS-1$
// private static final String STORE_REPO_ID = PAGE_NAME + ".REPO";
private RepositoryConfiguration repositoryConfiguration;
private final SelectionAdapter updateActionSelectionAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (isControlCreated()) {
setPageComplete(isPageComplete());
}
}
};
private Text queryTitle;
private final class ModifyListenerImplementation implements ModifyListener {
public void modifyText(ModifyEvent e) {
if (isControlCreated()) {
setPageComplete(isPageComplete());
}
}
}
@Override
public void setPageComplete(boolean complete) {
super.setPageComplete(complete);
if (getSearchContainer() != null) {
getSearchContainer().setPerformActionEnabled(complete);
}
}
private static class BugzillaSearchData {
/** Pattern to match on */
String pattern;
/** Pattern matching criterion */
int operation;
BugzillaSearchData(String pattern, int operation) {
this.pattern = pattern;
this.operation = operation;
}
}
public BugzillaSearchPage(TaskRepository repository) {
super(Messages.BugzillaSearchPage_Bugzilla_Query, repository);
// setTitle(TITLE);
// setDescription(DESCRIPTION);
// setImageDescriptor(TaskListImages.BANNER_REPOSITORY);
// setPageComplete(false);
// try {
// repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(repository, false);
// } catch (final CoreException e) {
// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
// public void run() {
// MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page",
// "Unable to get configuration. Ensure proper repository configuration in "
// + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n");
}
public BugzillaSearchPage(TaskRepository repository, IRepositoryQuery origQuery) {
super(Messages.BugzillaSearchPage_Bugzilla_Query, repository, origQuery);
originalQuery = origQuery;
setDescription(Messages.BugzillaSearchPage_Select_the_Bugzilla_query_parameters);
// setTitle(TITLE);
// setDescription(DESCRIPTION);
// setPageComplete(false);
// try {
// repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(repository, false);
// } catch (final CoreException e) {
// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
// public void run() {
// MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page",
// "Unable to get configuration. Ensure proper repository configuration in "
// + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n");
}
public void createControl(Composite parent) {
readConfiguration();
Composite control = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 0;
control.setLayout(layout);
control.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL));
// if (scontainer == null) {
// Not presenting in search pane so want query title
// super.createControl(control);
// Label lblName = new Label(control, SWT.NONE);
// final GridData gridData = new GridData();
// lblName.setLayoutData(gridData);
// lblName.setText("Query Title:");
// title = new Text(control, SWT.BORDER);
// title.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
// title.addModifyListener(new ModifyListener() {
// public void modifyText(ModifyEvent e) {
// setPageComplete(isPageComplete());
// else {
// // if (repository == null) {
// // search pane so add repository selection
// createRepositoryGroup(control);
createOptionsGroup(control);
createSearchGroup(control);
// createSaveQuery(control);
// createMaxHits(control);
// input = new SavedQueryFile(BugzillaPlugin.getDefault().getStateLocation().toString(), "/queries");
// createUpdate(control);
// if (originalQuery != null) {
// try {
// updateDefaults(originalQuery.getQueryUrl(), String.valueOf(originalQuery.getMaxHits()));
// } catch (UnsupportedEncodingException e) {
// // ignore
Dialog.applyDialogFont(control);
setControl(control);
PlatformUI.getWorkbench().getHelpSystem().setHelp(control, BugzillaUiPlugin.SEARCH_PAGE_CONTEXT);
restoreBounds();
}
protected void createOptionsGroup(Composite control) {
GridLayout sashFormLayout = new GridLayout();
sashFormLayout.numColumns = 4;
sashFormLayout.marginHeight = 5;
sashFormLayout.marginWidth = 5;
sashFormLayout.horizontalSpacing = 5;
final Composite composite = new Composite(control, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
final GridLayout gridLayout = new GridLayout();
gridLayout.marginBottom = 8;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.numColumns = 4;
composite.setLayout(gridLayout);
if (!inSearchContainer()) {
final Label queryTitleLabel = new Label(composite, SWT.NONE);
queryTitleLabel.setText(Messages.BugzillaSearchPage_Query_Title);
queryTitle = new Text(composite, SWT.BORDER);
queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
if (originalQuery != null) {
queryTitle.setText(originalQuery.getSummary());
}
queryTitle.addModifyListener(new ModifyListenerImplementation());
queryTitle.setFocus();
}
// Info text
Label labelSummary = new Label(composite, SWT.LEFT);
labelSummary.setText(Messages.BugzillaSearchPage_Summary);
// labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT));
//labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
// Pattern combo
summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER);
summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
summaryPattern.addModifyListener(new ModifyListenerImplementation());
summaryPattern.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns);
}
});
summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
summaryOperation.setItems(patternOperationText);
summaryOperation.setText(patternOperationText[0]);
summaryOperation.select(0);
// Info text
Label labelComment = new Label(composite, SWT.LEFT);
labelComment.setText(Messages.BugzillaSearchPage_Comment);
//labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
// Comment pattern combo
commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER);
commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
commentPattern.addModifyListener(new ModifyListenerImplementation());
commentPattern.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns);
}
});
commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
commentOperation.setItems(patternOperationText);
commentOperation.setText(patternOperationText[0]);
commentOperation.select(0);
Label labelEmail = new Label(composite, SWT.LEFT);
labelEmail.setText(Messages.BugzillaSearchPage_Email);
//labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
// pattern combo
emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER);
emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
emailPattern.addModifyListener(new ModifyListenerImplementation());
emailPattern.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns);
}
});
IContentProposalProvider proposalProvider = TasksUi.getUiFactory().createPersonContentProposalProvider(
getTaskRepository());
ILabelProvider proposalLabelProvider = TasksUi.getUiFactory().createPersonContentProposalLabelProvider(
getTaskRepository());
ContentAssistCommandAdapter adapter = new ContentAssistCommandAdapter(emailPattern, new ComboContentAdapter(),
proposalProvider, ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, new char[0], true);
adapter.setLabelProvider(proposalLabelProvider);
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
Composite emailComposite = new Composite(composite, SWT.NONE);
emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
GridLayout emailLayout = new GridLayout();
emailLayout.marginWidth = 0;
emailLayout.marginHeight = 0;
emailLayout.horizontalSpacing = 2;
emailLayout.numColumns = 4;
emailComposite.setLayout(emailLayout);
Button button0 = new Button(emailComposite, SWT.CHECK);
button0.setText(Messages.BugzillaSearchPage_owner);
Button button1 = new Button(emailComposite, SWT.CHECK);
button1.setText(Messages.BugzillaSearchPage_reporter);
Button button2 = new Button(emailComposite, SWT.CHECK);
button2.setText(Messages.BugzillaSearchPage_cc);
Button button3 = new Button(emailComposite, SWT.CHECK);
button3.setText(Messages.BugzillaSearchPage_commenter);
emailButtons = new Button[] { button0, button1, button2, button3 };
// operation combo
emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
emailOperation.setItems(emailOperationText);
emailOperation.setText(emailOperationText[0]);
emailOperation.select(0);
// Email2
Label labelEmail2 = new Label(composite, SWT.LEFT);
labelEmail2.setText(Messages.BugzillaSearchPage_Email_2);
//labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
// pattern combo
emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER);
emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
emailPattern2.addModifyListener(new ModifyListenerImplementation());
emailPattern2.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2);
}
});
ContentAssistCommandAdapter adapter2 = new ContentAssistCommandAdapter(emailPattern2,
new ComboContentAdapter(), proposalProvider, ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS,
new char[0], true);
adapter.setLabelProvider(proposalLabelProvider);
adapter2.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
Composite emailComposite2 = new Composite(composite, SWT.NONE);
emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
GridLayout emailLayout2 = new GridLayout();
emailLayout2.marginWidth = 0;
emailLayout2.marginHeight = 0;
emailLayout2.horizontalSpacing = 2;
emailLayout2.numColumns = 4;
emailComposite2.setLayout(emailLayout2);
Button e2button0 = new Button(emailComposite2, SWT.CHECK);
e2button0.setText(Messages.BugzillaSearchPage_owner);
Button e2button1 = new Button(emailComposite2, SWT.CHECK);
e2button1.setText(Messages.BugzillaSearchPage_reporter);
Button e2button2 = new Button(emailComposite2, SWT.CHECK);
e2button2.setText(Messages.BugzillaSearchPage_cc);
Button e2button3 = new Button(emailComposite2, SWT.CHECK);
e2button3.setText(Messages.BugzillaSearchPage_commenter);
emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 };
// operation combo
emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
emailOperation2.setItems(emailOperationText);
emailOperation2.setText(emailOperationText[0]);
emailOperation2.select(0);
Label labelKeywords = new Label(composite, SWT.NONE);
labelKeywords.setText(Messages.BugzillaSearchPage_Keywords);
// labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT));
//labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
Composite keywordsComposite = new Composite(composite, SWT.NONE);
keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
GridLayout keywordsLayout = new GridLayout();
keywordsLayout.marginWidth = 0;
keywordsLayout.marginHeight = 0;
keywordsLayout.numColumns = 3;
keywordsComposite.setLayout(keywordsLayout);
keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY);
keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
keywordsOperation.setItems(keywordOperationText);
keywordsOperation.setText(keywordOperationText[0]);
keywordsOperation.select(0);
keywords = new Combo(keywordsComposite, SWT.NONE);
keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
keywords.addModifyListener(new ModifyListenerImplementation());
keywords.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleWidgetSelected(keywords, keywordsOperation, previousKeywords);
}
});
Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE);
keywordsSelectButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (repositoryConfiguration != null && getShell() != null) {
KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(),
repositoryConfiguration.getKeywords());
if (dialog.open() == Window.OK) {
keywords.setText(dialog.getSelectedKeywordsString());
}
}
}
});
keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
keywordsSelectButton.setText(Messages.BugzillaSearchPage_Select_);
SashForm sashForm = new SashForm(control, SWT.VERTICAL);
sashForm.setLayout(sashFormLayout);
final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_sashForm.widthHint = 500;
sashForm.setLayoutData(gd_sashForm);
GridLayout topLayout = new GridLayout();
topLayout.numColumns = 4;
SashForm topForm = new SashForm(sashForm, SWT.NONE);
GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
topLayoutData.widthHint = 500;
topForm.setLayoutData(topLayoutData);
topForm.setLayout(topLayout);
GridLayout productLayout = new GridLayout();
productLayout.marginWidth = 0;
productLayout.marginHeight = 0;
productLayout.horizontalSpacing = 0;
Composite productComposite = new Composite(topForm, SWT.NONE);
productComposite.setLayout(productLayout);
Label productLabel = new Label(productComposite, SWT.LEFT);
productLabel.setText(Messages.BugzillaSearchPage_Product);
productLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO;
product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
product.setLayoutData(productLayoutData);
product.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (product.getSelectionIndex() != -1) {
String[] selectedProducts = product.getSelection();
updateAttributesFromConfiguration(selectedProducts);
} else {
updateAttributesFromConfiguration(null);
}
if (restoring) {
restoring = false;
restoreWidgetValues();
}
setPageComplete(isPageComplete());
}
});
GridLayout componentLayout = new GridLayout();
componentLayout.marginWidth = 0;
componentLayout.marginHeight = 0;
componentLayout.horizontalSpacing = 0;
Composite componentComposite = new Composite(topForm, SWT.NONE);
componentComposite.setLayout(componentLayout);
Label componentLabel = new Label(componentComposite, SWT.LEFT);
componentLabel.setText(Messages.BugzillaSearchPage_Component);
componentLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO;
component.setLayoutData(componentLayoutData);
component.addSelectionListener(updateActionSelectionAdapter);
Composite versionComposite = new Composite(topForm, SWT.NONE);
GridLayout versionLayout = new GridLayout();
versionLayout.marginWidth = 0;
versionLayout.marginHeight = 0;
versionLayout.horizontalSpacing = 0;
versionComposite.setLayout(versionLayout);
Label versionLabel = new Label(versionComposite, SWT.LEFT);
versionLabel.setText(Messages.BugzillaSearchPage_Version);
versionLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO;
version.setLayoutData(versionLayoutData);
version.addSelectionListener(updateActionSelectionAdapter);
Composite milestoneComposite = new Composite(topForm, SWT.NONE);
GridLayout milestoneLayout = new GridLayout();
milestoneLayout.marginWidth = 0;
milestoneLayout.marginHeight = 0;
milestoneLayout.horizontalSpacing = 0;
milestoneComposite.setLayout(milestoneLayout);
Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT);
milestoneLabel.setText(Messages.BugzillaSearchPage_Milestone);
milestoneLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO;
target.setLayoutData(targetLayoutData);
target.addSelectionListener(updateActionSelectionAdapter);
SashForm bottomForm = new SashForm(sashForm, SWT.NONE);
GridLayout bottomLayout = new GridLayout();
bottomLayout.numColumns = 6;
bottomForm.setLayout(bottomLayout);
GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1);
bottomLayoutData.heightHint = 119;
bottomLayoutData.widthHint = 400;
bottomForm.setLayoutData(bottomLayoutData);
Composite statusComposite = new Composite(bottomForm, SWT.NONE);
GridLayout statusLayout = new GridLayout();
statusLayout.marginTop = 7;
statusLayout.marginWidth = 0;
statusLayout.horizontalSpacing = 0;
statusLayout.marginHeight = 0;
statusComposite.setLayout(statusLayout);
Label statusLabel = new Label(statusComposite, SWT.LEFT);
statusLabel.setText(Messages.BugzillaSearchPage_Status);
statusLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_status.heightHint = 60;
status.setLayoutData(gd_status);
status.addSelectionListener(updateActionSelectionAdapter);
Composite resolutionComposite = new Composite(bottomForm, SWT.NONE);
GridLayout resolutionLayout = new GridLayout();
resolutionLayout.marginTop = 7;
resolutionLayout.marginWidth = 0;
resolutionLayout.marginHeight = 0;
resolutionLayout.horizontalSpacing = 0;
resolutionComposite.setLayout(resolutionLayout);
Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT);
resolutionLabel.setText(Messages.BugzillaSearchPage_Resolution);
resolutionLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_resolution.heightHint = 60;
resolution.setLayoutData(gd_resolution);
resolution.addSelectionListener(updateActionSelectionAdapter);
Composite priorityComposite = new Composite(bottomForm, SWT.NONE);
GridLayout priorityLayout = new GridLayout();
priorityLayout.marginTop = 7;
priorityLayout.marginWidth = 0;
priorityLayout.marginHeight = 0;
priorityLayout.horizontalSpacing = 0;
priorityComposite.setLayout(priorityLayout);
Label priorityLabel = new Label(priorityComposite, SWT.LEFT);
priorityLabel.setText(Messages.BugzillaSearchPage_PROORITY);
priorityLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_priority.heightHint = 60;
priority.setLayoutData(gd_priority);
priority.addSelectionListener(updateActionSelectionAdapter);
Composite severityComposite = new Composite(bottomForm, SWT.NONE);
GridLayout severityLayout = new GridLayout();
severityLayout.marginTop = 7;
severityLayout.marginWidth = 0;
severityLayout.marginHeight = 0;
severityLayout.horizontalSpacing = 0;
severityComposite.setLayout(severityLayout);
Label severityLabel = new Label(severityComposite, SWT.LEFT);
severityLabel.setText(Messages.BugzillaSearchPage_Severity);
severityLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_severity.heightHint = 60;
severity.setLayoutData(gd_severity);
severity.addSelectionListener(updateActionSelectionAdapter);
Composite hardwareComposite = new Composite(bottomForm, SWT.NONE);
GridLayout hardwareLayout = new GridLayout();
hardwareLayout.marginTop = 7;
hardwareLayout.marginWidth = 0;
hardwareLayout.marginHeight = 0;
hardwareLayout.horizontalSpacing = 0;
hardwareComposite.setLayout(hardwareLayout);
Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT);
hardwareLabel.setText(Messages.BugzillaSearchPage_Hardware);
hardwareLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_hardware.heightHint = 60;
hardware.setLayoutData(gd_hardware);
hardware.addSelectionListener(updateActionSelectionAdapter);
Composite osComposite = new Composite(bottomForm, SWT.NONE);
GridLayout osLayout = new GridLayout();
osLayout.marginTop = 7;
osLayout.marginWidth = 0;
osLayout.marginHeight = 0;
osLayout.horizontalSpacing = 0;
osComposite.setLayout(osLayout);
Label osLabel = new Label(osComposite, SWT.LEFT);
osLabel.setText(Messages.BugzillaSearchPage_Operating_System);
osLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_os.heightHint = 60;
os.setLayoutData(gd_os);
os.addSelectionListener(updateActionSelectionAdapter);
bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 });
}
private void createSearchGroup(Composite control) {
Composite composite = new Composite(control, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
GridLayout gridLayout = new GridLayout();
gridLayout.marginTop = 7;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
Label changedInTheLabel = new Label(composite, SWT.LEFT);
changedInTheLabel.setLayoutData(new GridData());
changedInTheLabel.setText(Messages.BugzillaSearchPage_Changed_in);
Composite updateComposite = new Composite(composite, SWT.NONE);
updateComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
GridLayout updateLayout = new GridLayout(3, false);
updateLayout.marginWidth = 0;
updateLayout.horizontalSpacing = 0;
updateLayout.marginHeight = 0;
updateComposite.setLayout(updateLayout);
daysText = new Text(updateComposite, SWT.BORDER);
daysText.setLayoutData(new GridData(40, SWT.DEFAULT));
daysText.setTextLimit(5);
daysText.addListener(SWT.Modify, this);
Label label = new Label(updateComposite, SWT.LEFT);
label.setText(Messages.BugzillaSearchPage_days);
Button updateButton = new Button(updateComposite, SWT.PUSH);
updateButton.setText(Messages.BugzillaSearchPage_Update_Attributes_from_Repository);
updateButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
updateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (getTaskRepository() != null) {
// try {
updateConfiguration(true);
// } catch (final CoreException e1) {
// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
// public void run() {
// MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page",
// "Unable to get configuration. Ensure proper repository configuration in "
// + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n");
} else {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
IBugzillaConstants.TITLE_MESSAGE_DIALOG,
Messages.BugzillaSearchPage_No_repository_available);
}
}
});
}
/**
* Creates the buttons for remembering a query and accessing previously saved queries.
*/
protected Control createSaveQuery(Composite control) {
GridLayout layout;
GridData gd;
Group group = new Group(control, SWT.NONE);
layout = new GridLayout(3, false);
group.setLayout(layout);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
gd = new GridData(GridData.BEGINNING | GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan = 2;
group.setLayoutData(gd);
// loadButton = new Button(group, SWT.PUSH | SWT.LEFT);
// loadButton.setText("Saved Queries...");
// final BugzillaSearchPage bsp = this;
// loadButton.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent event) {
// GetQueryDialog qd = new GetQueryDialog(getShell(), "Saved Queries",
// input);
// if (qd.open() == InputDialog.OK) {
// selIndex = qd.getSelected();
// if (selIndex != -1) {
// rememberedQuery = true;
// performAction();
// bsp.getShell().close();
// loadButton.setEnabled(true);
// loadButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
// saveButton = new Button(group, SWT.PUSH | SWT.LEFT);
// saveButton.setText("Remember...");
// saveButton.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent event) {
// SaveQueryDialog qd = new SaveQueryDialog(getShell(), "Remember Query");
// if (qd.open() == InputDialog.OK) {
// String qName = qd.getText();
// if (qName != null && qName.compareTo("") != 0) {
// try {
// input.add(getQueryParameters().toString(), qName, summaryPattern.getText());
// } catch (UnsupportedEncodingException e) {
// /*
// * Do nothing. Every implementation of the Java
// * platform is required to support the standard
// * charset "UTF-8"
// */
// saveButton.setEnabled(true);
// saveButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
return group;
}
// public static SavedQueryFile getInput() {
// return input;
private void handleWidgetSelected(Combo widget, Combo operation, ArrayList<BugzillaSearchData> history) {
if (widget.getSelectionIndex() < 0) {
return;
}
int index = history.size() - 1 - widget.getSelectionIndex();
BugzillaSearchData patternData = history.get(index);
if (patternData == null || !widget.getText().equals(patternData.pattern)) {
return;
}
widget.setText(patternData.pattern);
operation.setText(operation.getItem(patternData.operation));
}
// TODO: avoid overriding?
@Override
public boolean performSearch() {
if (restoreQueryOptions) {
saveState();
}
getPatternData(summaryPattern, summaryOperation, previousSummaryPatterns);
getPatternData(commentPattern, commentOperation, previousCommentPatterns);
getPatternData(emailPattern, emailOperation, previousEmailPatterns);
getPatternData(emailPattern2, emailOperation2, previousEmailPatterns2);
getPatternData(keywords, keywordsOperation, previousKeywords);
String summaryText = summaryPattern.getText();
BugzillaUiPlugin.getDefault().getPreferenceStore().setValue(IBugzillaConstants.MOST_RECENT_QUERY, summaryText);
return super.performSearch();
}
@Override
public void setVisible(boolean visible) {
if (visible && summaryPattern != null) {
if (firstTime) {
// Set<TaskRepository> repositories = TasksUiPlugin.getRepositoryManager().getRepositories(BugzillaCorePlugin.REPOSITORY_KIND);
// String[] repositoryUrls = new String[repositories.size()];
// int i = 0;
// int indexToSelect = 0;
// for (Iterator<TaskRepository> iter = repositories.iterator(); iter.hasNext();) {
// TaskRepository currRepsitory = iter.next();
// // if (i == 0 && repository == null) {
// // repository = currRepsitory;
// // indexToSelect = 0;
// if (repository != null && repository.equals(currRepsitory)) {
// indexToSelect = i;
// repositoryUrls[i] = currRepsitory.getUrl();
// IDialogSettings settings = getDialogSettings();
// if (repositoryCombo != null) {
// repositoryCombo.setItems(repositoryUrls);
// if (repositoryUrls.length == 0) {
// MessageDialog.openInformation(Display.getCurrent().getActiveShell(), IBugzillaConstants.TITLE_MESSAGE_DIALOG,
// TaskRepositoryManager.MESSAGE_NO_REPOSITORY);
// } else {
// String selectRepo = settings.get(STORE_REPO_ID);
// if (selectRepo != null && repositoryCombo.indexOf(selectRepo) > -1) {
// repositoryCombo.setText(selectRepo);
// repository = TasksUiPlugin.getRepositoryManager().getRepository(
// BugzillaCorePlugin.REPOSITORY_KIND, repositoryCombo.getText());
// if (repository == null) {
// repository = TasksUiPlugin.getRepositoryManager().getDefaultRepository( BugzillaCorePlugin.REPOSITORY_KIND);
// } else {
// repositoryCombo.select(indexToSelect);
// updateAttributesFromRepository(repositoryCombo.getText(), null, false);
firstTime = false;
// Set item and text here to prevent page from resizing
for (String searchPattern : getPreviousPatterns(previousSummaryPatterns)) {
summaryPattern.add(searchPattern);
}
// summaryPattern.setItems(getPreviousPatterns(previousSummaryPatterns));
for (String comment : getPreviousPatterns(previousCommentPatterns)) {
commentPattern.add(comment);
}
// commentPattern.setItems(getPreviousPatterns(previousCommentPatterns));
for (String email : getPreviousPatterns(previousEmailPatterns)) {
emailPattern.add(email);
}
for (String email : getPreviousPatterns(previousEmailPatterns2)) {
emailPattern2.add(email);
}
// emailPattern.setItems(getPreviousPatterns(previousEmailPatterns));
for (String keyword : getPreviousPatterns(previousKeywords)) {
keywords.add(keyword);
}
// TODO: update status, resolution, severity etc if possible...
if (getTaskRepository() != null) {
repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(getTaskRepository().getUrl());
updateAttributesFromConfiguration(null);
if (product.getItemCount() == 0) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (getControl() != null && !getControl().isDisposed()) {
updateConfiguration(true);
updateAttributesFromConfiguration(null);
}
}
});
}
}
if (originalQuery != null) {
try {
updateDefaults(originalQuery.getUrl());
} catch (UnsupportedEncodingException e) {
// ignore
}
}
}
/*
* hack: we have to select the correct product, then update the
* attributes so the component/version/milestone lists have the
* proper values, then we can restore all the widget selections.
*/
if (getTaskRepository() != null) {
IDialogSettings settings = getDialogSettings();
String repoId = "." + getTaskRepository().getRepositoryUrl(); //$NON-NLS-1$
if (getWizard() == null && restoreQueryOptions && settings.getArray(STORE_PRODUCT_ID + repoId) != null
&& product != null) {
product.setSelection(nonNullArray(settings, STORE_PRODUCT_ID + repoId));
if (product.getSelection().length > 0) {
updateAttributesFromConfiguration(product.getSelection());
}
restoreWidgetValues();
}
}
setPageComplete(isPageComplete());
if (getWizard() == null) {
// TODO: wierd check
summaryPattern.setFocus();
}
}
super.setVisible(visible);
}
/**
* Returns <code>true</code> if at least some parameter is given to query on.
*/
private boolean canQuery() {
if (isControlCreated()) {
return product.getSelectionCount() > 0 || component.getSelectionCount() > 0
|| version.getSelectionCount() > 0 || target.getSelectionCount() > 0
|| status.getSelectionCount() > 0 || resolution.getSelectionCount() > 0
|| severity.getSelectionCount() > 0 || priority.getSelectionCount() > 0
|| hardware.getSelectionCount() > 0 || os.getSelectionCount() > 0
|| summaryPattern.getText().length() > 0 || commentPattern.getText().length() > 0
|| emailPattern.getText().length() > 0 || emailPattern2.getText().length() > 0
|| keywords.getText().length() > 0;
} else {
return false;
}
}
@Override
public boolean isPageComplete() {
if (daysText != null) {
String days = daysText.getText();
if (days.length() > 0) {
try {
if (Integer.parseInt(days) < 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException ex) {
setErrorMessage(NLS.bind(Messages.BugzillaSearchPage_Number_of_days_must_be_a_positive_integer,
days));
return false;
}
}
}
return getWizard() == null ? canQuery() : canQuery() && super.isPageComplete();
}
/**
* Return search pattern data and update search history list. An existing entry will be updated or a new one
* created.
*/
private BugzillaSearchData getPatternData(Combo widget, Combo operation,
ArrayList<BugzillaSearchData> previousSearchQueryData) {
String pattern = widget.getText();
if (pattern == null || pattern.trim().equals("")) { //$NON-NLS-1$
return null;
}
BugzillaSearchData match = null;
int i = previousSearchQueryData.size() - 1;
while (i >= 0) {
match = previousSearchQueryData.get(i);
if (pattern.equals(match.pattern)) {
break;
}
i
}
if (i >= 0 && match != null) {
match.operation = operation.getSelectionIndex();
// remove - will be added last (see below)
previousSearchQueryData.remove(match);
} else {
match = new BugzillaSearchData(widget.getText(), operation.getSelectionIndex());
}
previousSearchQueryData.add(match);
return match;
}
/**
* Returns an array of previous summary patterns
*/
private String[] getPreviousPatterns(ArrayList<BugzillaSearchData> patternHistory) {
int size = patternHistory.size();
String[] patterns = new String[size];
for (int i = 0; i < size; i++) {
patterns[i] = (patternHistory.get(size - 1 - i)).pattern;
}
return patterns;
}
public String getSearchURL(TaskRepository repository) {
return getQueryURL(repository, getQueryParameters());
}
protected String getQueryURL(TaskRepository repository, StringBuilder params) {
StringBuilder url = new StringBuilder(getQueryURLStart(repository).toString());
url.append(params);
// HACK make sure that the searches come back sorted by priority. This
// should be a search option though
url.append("&order=Importance"); //$NON-NLS-1$
// url.append(BugzillaRepositoryUtil.contentTypeRDF);
return url.toString();
}
private StringBuilder getQueryURLStart(TaskRepository repository) {
StringBuilder sb = new StringBuilder(repository.getRepositoryUrl());
if (sb.charAt(sb.length() - 1) != '/') {
sb.append('/');
}
sb.append("buglist.cgi?"); //$NON-NLS-1$
return sb;
}
/**
* Goes through the query form and builds up the query parameters. Example:
* short_desc_type=substring&short_desc=bla& ... TODO: The encoding here should match
* TaskRepository.getCharacterEncoding()
*
* @throws UnsupportedEncodingException
*/
protected StringBuilder getQueryParameters() {
StringBuilder sb = new StringBuilder();
sb.append("short_desc_type="); //$NON-NLS-1$
sb.append(patternOperationValues[summaryOperation.getSelectionIndex()]);
appendToBuffer(sb, "&short_desc=", summaryPattern.getText()); //$NON-NLS-1$
int[] selected = product.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&product=", product.getItem(element)); //$NON-NLS-1$
}
selected = component.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&component=", component.getItem(element)); //$NON-NLS-1$
}
selected = version.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&version=", version.getItem(element)); //$NON-NLS-1$
}
selected = target.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&target_milestone=", target.getItem(element)); //$NON-NLS-1$
}
sb.append("&long_desc_type="); //$NON-NLS-1$
sb.append(patternOperationValues[commentOperation.getSelectionIndex()]);
appendToBuffer(sb, "&long_desc=", commentPattern.getText()); //$NON-NLS-1$
selected = status.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&bug_status=", status.getItem(element)); //$NON-NLS-1$
}
selected = resolution.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&resolution=", resolution.getItem(element)); //$NON-NLS-1$
}
selected = severity.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&bug_severity=", severity.getItem(element)); //$NON-NLS-1$
}
selected = priority.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&priority=", priority.getItem(element)); //$NON-NLS-1$
}
selected = hardware.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&ref_platform=", hardware.getItem(element)); //$NON-NLS-1$
}
selected = os.getSelectionIndices();
for (int element : selected) {
appendToBuffer(sb, "&op_sys=", os.getItem(element)); //$NON-NLS-1$
}
if (emailPattern.getText() != null && !emailPattern.getText().trim().equals("")) { //$NON-NLS-1$
boolean selectionMade = false;
for (Button button : emailButtons) {
if (button.getSelection()) {
selectionMade = true;
break;
}
}
if (selectionMade) {
for (int i = 0; i < emailButtons.length; i++) {
if (emailButtons[i].getSelection()) {
sb.append("&"); //$NON-NLS-1$
sb.append(emailRoleValues[i]);
sb.append("=1"); //$NON-NLS-1$
}
}
sb.append("&emailtype1="); //$NON-NLS-1$
sb.append(emailOperationValues[emailOperation.getSelectionIndex()]);
appendToBuffer(sb, "&email1=", emailPattern.getText()); //$NON-NLS-1$
}
}
if (emailPattern2.getText() != null && !emailPattern2.getText().trim().equals("")) { //$NON-NLS-1$
boolean selectionMade = false;
for (Button button : emailButtons2) {
if (button.getSelection()) {
selectionMade = true;
break;
}
}
if (selectionMade) {
for (int i = 0; i < emailButtons2.length; i++) {
if (emailButtons2[i].getSelection()) {
sb.append("&"); //$NON-NLS-1$
sb.append(emailRoleValues2[i]);
sb.append("=1"); //$NON-NLS-1$
}
}
sb.append("&emailtype2="); //$NON-NLS-1$
sb.append(emailOperationValues[emailOperation2.getSelectionIndex()]);
appendToBuffer(sb, "&email2=", emailPattern2.getText()); //$NON-NLS-1$
}
}
if (daysText.getText() != null && !daysText.getText().equals("")) { //$NON-NLS-1$
try {
Integer.parseInt(daysText.getText());
appendToBuffer(sb, "&changedin=", daysText.getText()); //$NON-NLS-1$
} catch (NumberFormatException ignored) {
// this means that the days is not a number, so don't worry
}
}
if (keywords.getText() != null && !keywords.getText().trim().equals("")) { //$NON-NLS-1$
sb.append("&keywords_type="); //$NON-NLS-1$
sb.append(keywordOperationValues[keywordsOperation.getSelectionIndex()]);
appendToBuffer(sb, "&keywords=", keywords.getText().replace(',', ' ')); //$NON-NLS-1$
}
return sb;
}
private void appendToBuffer(StringBuilder sb, String key, String value) {
sb.append(key);
try {
sb.append(URLEncoder.encode(value, getTaskRepository().getCharacterEncoding()));
} catch (UnsupportedEncodingException e) {
sb.append(value);
}
}
@Override
public IDialogSettings getDialogSettings() {
IDialogSettings settings = BugzillaUiPlugin.getDefault().getDialogSettings();
fDialogSettings = settings.getSection(PAGE_NAME);
if (fDialogSettings == null) {
fDialogSettings = settings.addNewSection(PAGE_NAME);
}
return fDialogSettings;
}
/**
* Initializes itself from the stored page settings.
*/
private void readConfiguration() {
getDialogSettings();
}
private void updateAttributesFromConfiguration(String[] selectedProducts) {
if (repositoryConfiguration != null) {
String[] saved_product = product.getSelection();
String[] saved_component = component.getSelection();
String[] saved_version = version.getSelection();
String[] saved_target = target.getSelection();
String[] saved_status = status.getSelection();
String[] saved_resolution = resolution.getSelection();
String[] saved_severity = severity.getSelection();
String[] saved_priority = priority.getSelection();
String[] saved_hardware = hardware.getSelection();
String[] saved_os = os.getSelection();
if (selectedProducts == null) {
java.util.List<String> products = repositoryConfiguration.getProducts();
String[] productsList = products.toArray(new String[products.size()]);
Arrays.sort(productsList, String.CASE_INSENSITIVE_ORDER);
product.setItems(productsList);
}
String[] componentsList = BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_COMPONENT,
selectedProducts, repositoryConfiguration);
Arrays.sort(componentsList, String.CASE_INSENSITIVE_ORDER);
component.setItems(componentsList);
version.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_VERSION, selectedProducts,
repositoryConfiguration));
target.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_TARGET, selectedProducts,
repositoryConfiguration));
status.setItems(convertStringListToArray(repositoryConfiguration.getStatusValues()));
resolution.setItems(convertStringListToArray(repositoryConfiguration.getResolutions()));
severity.setItems(convertStringListToArray(repositoryConfiguration.getSeverities()));
priority.setItems(convertStringListToArray(repositoryConfiguration.getPriorities()));
hardware.setItems(convertStringListToArray(repositoryConfiguration.getPlatforms()));
os.setItems(convertStringListToArray(repositoryConfiguration.getOSs()));
setSelection(product, saved_product);
setSelection(component, saved_component);
setSelection(version, saved_version);
setSelection(target, saved_target);
setSelection(status, saved_status);
setSelection(resolution, saved_resolution);
setSelection(severity, saved_severity);
setSelection(priority, saved_priority);
setSelection(hardware, saved_hardware);
setSelection(os, saved_os);
}
}
@Override
public boolean canFlipToNextPage() {
// if (getErrorMessage() != null)
// return false;
// return true;
return false;
}
public void handleEvent(Event event) {
if (getWizard() != null) {
getWizard().getContainer().updateButtons();
}
}
/**
* TODO: get rid of this?
*/
public void updateDefaults(String startingUrl) throws UnsupportedEncodingException {
// String serverName = startingUrl.substring(0,
// startingUrl.indexOf("?"));
startingUrl = startingUrl.substring(startingUrl.indexOf("?") + 1); //$NON-NLS-1$
String[] options = startingUrl.split("&"); //$NON-NLS-1$
for (String option : options) {
String key = option.substring(0, option.indexOf("=")); //$NON-NLS-1$
String value = URLDecoder.decode(option.substring(option.indexOf("=") + 1), //$NON-NLS-1$
getTaskRepository().getCharacterEncoding());
if (key == null) {
continue;
}
if (key.equals("short_desc")) { //$NON-NLS-1$
summaryPattern.setText(value);
} else if (key.equals("short_desc_type")) { //$NON-NLS-1$
if (value.equals("allwordssubstr")) { //$NON-NLS-1$
value = "all words"; //$NON-NLS-1$
} else if (value.equals("anywordssubstr")) { //$NON-NLS-1$
value = "any word"; //$NON-NLS-1$
}
int index = 0;
for (String item : summaryOperation.getItems()) {
if (item.compareTo(value) == 0) {
break;
}
index++;
}
if (index < summaryOperation.getItemCount()) {
summaryOperation.select(index);
}
} else if (key.equals("product")) { //$NON-NLS-1$
String[] sel = product.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
product.setSelection(selList.toArray(sel));
updateAttributesFromConfiguration(selList.toArray(sel));
} else if (key.equals("component")) { //$NON-NLS-1$
String[] sel = component.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
component.setSelection(selList.toArray(sel));
} else if (key.equals("version")) { //$NON-NLS-1$
String[] sel = version.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
version.setSelection(selList.toArray(sel));
} else if (key.equals("target_milestone")) { // XXX //$NON-NLS-1$
String[] sel = target.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
target.setSelection(selList.toArray(sel));
} else if (key.equals("version")) { //$NON-NLS-1$
String[] sel = version.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
version.setSelection(selList.toArray(sel));
} else if (key.equals("long_desc_type")) { //$NON-NLS-1$
if (value.equals("allwordssubstr")) { //$NON-NLS-1$
value = "all words"; //$NON-NLS-1$
} else if (value.equals("anywordssubstr")) { //$NON-NLS-1$
value = "any word"; //$NON-NLS-1$
}
int index = 0;
for (String item : commentOperation.getItems()) {
if (item.compareTo(value) == 0) {
break;
}
index++;
}
if (index < commentOperation.getItemCount()) {
commentOperation.select(index);
}
} else if (key.equals("long_desc")) { //$NON-NLS-1$
commentPattern.setText(value);
} else if (key.equals("bug_status")) { //$NON-NLS-1$
String[] sel = status.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
status.setSelection(selList.toArray(sel));
} else if (key.equals("resolution")) { //$NON-NLS-1$
String[] sel = resolution.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
resolution.setSelection(selList.toArray(sel));
} else if (key.equals("bug_severity")) { //$NON-NLS-1$
String[] sel = severity.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
severity.setSelection(selList.toArray(sel));
} else if (key.equals("priority")) { //$NON-NLS-1$
String[] sel = priority.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
priority.setSelection(selList.toArray(sel));
} else if (key.equals("ref_platform")) { //$NON-NLS-1$
String[] sel = hardware.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
hardware.setSelection(selList.toArray(sel));
} else if (key.equals("op_sys")) { //$NON-NLS-1$
String[] sel = os.getSelection();
java.util.List<String> selList = Arrays.asList(sel);
selList = new ArrayList<String>(selList);
selList.add(value);
sel = new String[selList.size()];
os.setSelection(selList.toArray(sel));
} else if (key.equals("emailassigned_to1")) { // HACK: email //$NON-NLS-1$
// buttons
// assumed to be
// in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons[0].setSelection(true);
} else {
emailButtons[0].setSelection(false);
}
} else if (key.equals("emailreporter1")) { // HACK: email //$NON-NLS-1$
// buttons assumed
// to be in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons[1].setSelection(true);
} else {
emailButtons[1].setSelection(false);
}
} else if (key.equals("emailcc1")) { // HACK: email buttons //$NON-NLS-1$
// assumed to be in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons[2].setSelection(true);
} else {
emailButtons[2].setSelection(false);
}
} else if (key.equals("emaillongdesc1")) { // HACK: email //$NON-NLS-1$
// buttons assumed
// to be in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons[3].setSelection(true);
} else {
emailButtons[3].setSelection(false);
}
} else if (key.equals("emailtype1")) { //$NON-NLS-1$
int index = 0;
for (String item : emailOperation.getItems()) {
if (item.compareTo(value) == 0) {
break;
}
index++;
}
if (index < emailOperation.getItemCount()) {
emailOperation.select(index);
}
} else if (key.equals("email1")) { //$NON-NLS-1$
emailPattern.setText(value);
} else if (key.equals("emailassigned_to2")) { // HACK: email //$NON-NLS-1$
// buttons
// assumed to be
// in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons2[0].setSelection(true);
} else {
emailButtons2[0].setSelection(false);
}
} else if (key.equals("emailreporter2")) { // HACK: email //$NON-NLS-1$
// buttons assumed
// to be in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons2[1].setSelection(true);
} else {
emailButtons2[1].setSelection(false);
}
} else if (key.equals("emailcc2")) { // HACK: email buttons //$NON-NLS-1$
// assumed to be in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons2[2].setSelection(true);
} else {
emailButtons2[2].setSelection(false);
}
} else if (key.equals("emaillongdesc2")) { // HACK: email //$NON-NLS-1$
// buttons assumed
// to be in same
// position
if (value.equals("1")) { //$NON-NLS-1$
emailButtons2[3].setSelection(true);
} else {
emailButtons2[3].setSelection(false);
}
} else if (key.equals("emailtype2")) { //$NON-NLS-1$
int index = 0;
for (String item : emailOperation2.getItems()) {
if (item.compareTo(value) == 0) {
break;
}
index++;
}
if (index < emailOperation2.getItemCount()) {
emailOperation2.select(index);
}
} else if (key.equals("email2")) { //$NON-NLS-1$
emailPattern2.setText(value);
} else if (key.equals("changedin")) { //$NON-NLS-1$
daysText.setText(value);
} else if (key.equals("keywords")) { //$NON-NLS-1$
keywords.setText(value.replace(' ', ','));
} else if (key.equals("keywords_type")) { //$NON-NLS-1$
int index = 0;
for (String item : keywordOperationValues) {
if (item.equals(value)) {
keywordsOperation.select(index);
break;
}
index++;
}
}
}
}
private String[] nonNullArray(IDialogSettings settings, String id) {
String[] value = settings.getArray(id);
if (value == null) {
return new String[] {};
}
return value;
}
private void restoreWidgetValues() {
try {
IDialogSettings settings = getDialogSettings();
String repoId = "." + getTaskRepository().getRepositoryUrl(); //$NON-NLS-1$
if (!restoreQueryOptions || settings.getArray(STORE_PRODUCT_ID + repoId) == null || product == null) {
return;
}
// set widgets to stored values
product.setSelection(nonNullArray(settings, STORE_PRODUCT_ID + repoId));
component.setSelection(nonNullArray(settings, STORE_COMPONENT_ID + repoId));
version.setSelection(nonNullArray(settings, STORE_VERSION_ID + repoId));
target.setSelection(nonNullArray(settings, STORE_MSTONE_ID + repoId));
status.setSelection(nonNullArray(settings, STORE_STATUS_ID + repoId));
resolution.setSelection(nonNullArray(settings, STORE_RESOLUTION_ID + repoId));
severity.setSelection(nonNullArray(settings, STORE_SEVERITY_ID + repoId));
priority.setSelection(nonNullArray(settings, STORE_PRIORITY_ID + repoId));
hardware.setSelection(nonNullArray(settings, STORE_HARDWARE_ID + repoId));
os.setSelection(nonNullArray(settings, STORE_OS_ID + repoId));
summaryOperation.select(settings.getInt(STORE_SUMMARYMATCH_ID + repoId));
commentOperation.select(settings.getInt(STORE_COMMENTMATCH_ID + repoId));
emailOperation.select(settings.getInt(STORE_EMAILMATCH_ID + repoId));
for (int i = 0; i < emailButtons.length; i++) {
emailButtons[i].setSelection(settings.getBoolean(STORE_EMAILBUTTON_ID + i + repoId));
}
summaryPattern.setText(settings.get(STORE_SUMMARYTEXT_ID + repoId));
commentPattern.setText(settings.get(STORE_COMMENTTEXT_ID + repoId));
emailPattern.setText(settings.get(STORE_EMAILADDRESS_ID + repoId));
try {
emailOperation2.select(settings.getInt(STORE_EMAIL2MATCH_ID + repoId));
} catch (Exception e) {
//ignore
}
for (int i = 0; i < emailButtons2.length; i++) {
emailButtons2[i].setSelection(settings.getBoolean(STORE_EMAIL2BUTTON_ID + i + repoId));
}
emailPattern2.setText(settings.get(STORE_EMAIL2ADDRESS_ID + repoId));
if (settings.get(STORE_KEYWORDS_ID + repoId) != null) {
keywords.setText(settings.get(STORE_KEYWORDS_ID + repoId));
keywordsOperation.select(settings.getInt(STORE_KEYWORDSMATCH_ID + repoId));
}
} catch (IllegalArgumentException e) {
//ignore
}
}
@Override
public void saveState() {
String repoId = "." + getTaskRepository().getRepositoryUrl(); //$NON-NLS-1$
IDialogSettings settings = getDialogSettings();
settings.put(STORE_PRODUCT_ID + repoId, product.getSelection());
settings.put(STORE_COMPONENT_ID + repoId, component.getSelection());
settings.put(STORE_VERSION_ID + repoId, version.getSelection());
settings.put(STORE_MSTONE_ID + repoId, target.getSelection());
settings.put(STORE_STATUS_ID + repoId, status.getSelection());
settings.put(STORE_RESOLUTION_ID + repoId, resolution.getSelection());
settings.put(STORE_SEVERITY_ID + repoId, severity.getSelection());
settings.put(STORE_PRIORITY_ID + repoId, priority.getSelection());
settings.put(STORE_HARDWARE_ID + repoId, hardware.getSelection());
settings.put(STORE_OS_ID + repoId, os.getSelection());
settings.put(STORE_SUMMARYMATCH_ID + repoId, summaryOperation.getSelectionIndex());
settings.put(STORE_COMMENTMATCH_ID + repoId, commentOperation.getSelectionIndex());
settings.put(STORE_EMAILMATCH_ID + repoId, emailOperation.getSelectionIndex());
for (int i = 0; i < emailButtons.length; i++) {
settings.put(STORE_EMAILBUTTON_ID + i + repoId, emailButtons[i].getSelection());
}
settings.put(STORE_SUMMARYTEXT_ID + repoId, summaryPattern.getText());
settings.put(STORE_COMMENTTEXT_ID + repoId, commentPattern.getText());
settings.put(STORE_EMAILADDRESS_ID + repoId, emailPattern.getText());
settings.put(STORE_EMAIL2ADDRESS_ID + repoId, emailPattern2.getText());
settings.put(STORE_EMAIL2MATCH_ID + repoId, emailOperation2.getSelectionIndex());
for (int i = 0; i < emailButtons2.length; i++) {
settings.put(STORE_EMAIL2BUTTON_ID + i + repoId, emailButtons2[i].getSelection());
}
settings.put(STORE_KEYWORDS_ID + repoId, keywords.getText());
settings.put(STORE_KEYWORDSMATCH_ID + repoId, keywordsOperation.getSelectionIndex());
// settings.put(STORE_REPO_ID, repositoryCombo.getText());
}
private void saveBounds(Rectangle bounds) {
if (inSearchContainer()) {
return;
}
IDialogSettings settings = getDialogSettings();
IDialogSettings dialogBounds = settings.getSection(DIALOG_BOUNDS_KEY);
if (dialogBounds == null) {
dialogBounds = new DialogSettings(DIALOG_BOUNDS_KEY);
settings.addSection(dialogBounds);
}
dialogBounds.put(X, bounds.x);
dialogBounds.put(Y, bounds.y);
dialogBounds.put(WIDTH, bounds.width);
dialogBounds.put(HEIGHT, bounds.height);
}
private void restoreBounds() {
if (inSearchContainer()) {
return;
}
IDialogSettings settings = getDialogSettings();
IDialogSettings dialogBounds = settings.getSection(DIALOG_BOUNDS_KEY);
Shell shell = getShell();
if (shell != null) {
Rectangle bounds = shell.getBounds();
if (bounds != null && dialogBounds != null) {
try {
bounds.x = dialogBounds.getInt(X);
bounds.y = dialogBounds.getInt(Y);
bounds.height = dialogBounds.getInt(HEIGHT);
bounds.width = dialogBounds.getInt(WIDTH);
shell.setBounds(bounds);
} catch (NumberFormatException e) {
// silently ignored
}
}
}
}
/* Testing hook to see if any products are present */
public int getProductCount() throws Exception {
return product.getItemCount();
}
public boolean isRestoreQueryOptions() {
return restoreQueryOptions;
}
public void setRestoreQueryOptions(boolean restoreQueryOptions) {
this.restoreQueryOptions = restoreQueryOptions;
}
private String[] convertStringListToArray(java.util.List<String> stringList) {
return stringList.toArray(new String[stringList.size()]);
}
private void updateConfiguration(final boolean force) {
String[] selectedProducts = product.getSelection();
if (selectedProducts != null && selectedProducts.length == 0) {
selectedProducts = null;
}
if (getTaskRepository() != null) {
IRunnableWithProgress updateRunnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
monitor.beginTask(Messages.BugzillaSearchPage_Updating_search_options_,
IProgressMonitor.UNKNOWN);
repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(getTaskRepository(),
force, monitor);
} catch (final Exception e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
try {
if (getContainer() != null) {
getContainer().run(true, true, updateRunnable);
} else if (getSearchContainer() != null) {
getSearchContainer().getRunnableContext().run(true, true, updateRunnable);
} else {
IProgressService service = PlatformUI.getWorkbench().getProgressService();
service.busyCursorWhile(updateRunnable);
}
} catch (InvocationTargetException ex) {
Shell shell = null;
shell = getShell();
if (ex.getCause() instanceof CoreException) {
CoreException cause = ((CoreException) ex.getCause());
if (cause.getStatus() instanceof RepositoryStatus
&& ((RepositoryStatus) cause.getStatus()).isHtmlMessage()) {
if (shell != null) {
shell.setEnabled(false);
}
// TODO: eliminate use of internal api
WebBrowserDialog dialog = new WebBrowserDialog(shell,
Messages.BugzillaSearchPage_Error_updating_search_options, null, cause.getStatus()
.getMessage(), NONE, new String[] { IDialogConstants.OK_LABEL }, 0,
((RepositoryStatus) cause.getStatus()).getHtmlMessage());
dialog.setBlockOnOpen(true);
dialog.open();
if (shell != null) {
shell.setEnabled(true);
}
return;
// this.setPageComplete(this.isPageComplete());
// this.setControlsEnabled(true);
} else {
StatusHandler.log(new Status(IStatus.ERROR, BugzillaUiPlugin.ID_PLUGIN, cause.getMessage(),
cause));
}
}
if (ex.getCause() instanceof OperationCanceledException) {
return;
}
MessageDialog.openError(shell, Messages.BugzillaSearchPage_Error_updating_search_options,
MessageFormat.format(Messages.BugzillaSearchPage_Error_was_X, ex.getCause().getMessage()));
return;
} catch (InterruptedException ex) {
return;
}
updateAttributesFromConfiguration(selectedProducts);
}
}
@Override
public Shell getShell() {
Shell shell = null;
if (getWizard() != null && getWizard().getContainer() != null) {
shell = getWizard().getContainer().getShell();
}
if (shell == null && getControl() != null) {
shell = getControl().getShell();
}
return shell;
}
@Override
public String getQueryTitle() {
return (queryTitle != null) ? queryTitle.getText() : ""; //$NON-NLS-1$
}
private void setSelection(List listControl, String[] selection) {
for (String item : selection) {
int index = listControl.indexOf(item);
if (index > -1) {
listControl.select(index);
}
}
if (listControl.getSelectionCount() > 0) {
listControl.showSelection();
} else {
listControl.select(0);
listControl.showSelection();
listControl.deselectAll();
}
}
@Override
public void applyTo(IRepositoryQuery query) {
query.setUrl(getQueryURL(getTaskRepository(), getQueryParameters()));
query.setSummary(getQueryTitle());
Shell shell = getShell();
if (shell != null) {
saveBounds(shell.getBounds());
}
}
}
|
package org.eclipse.mylyn.internal.discovery.ui.wizards;
import java.net.URL;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.mylyn.internal.discovery.core.model.AbstractDiscoverySource;
import org.eclipse.mylyn.internal.discovery.core.model.Overview;
import org.eclipse.mylyn.internal.provisional.commons.ui.GradientToolTip;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
/**
* @author David Green
*/
class OverviewToolTip extends GradientToolTip {
private static final String COLOR_BLACK = "black"; //$NON-NLS-1$
private final Overview overview;
private final AbstractDiscoverySource source;
private Color colorBlack;
public OverviewToolTip(Control control, AbstractDiscoverySource source, Overview overview) {
super(control, ToolTip.RECREATE, true);
if (source == null) {
throw new IllegalArgumentException();
}
if (overview == null) {
throw new IllegalArgumentException();
}
this.source = source;
this.overview = overview;
setHideOnMouseDown(false); // required for links to work
}
@Override
protected Composite createToolTipArea(Event event, final Composite parent) {
if (colorBlack == null) {
ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
if (!colorRegistry.hasValueFor(COLOR_BLACK)) {
colorRegistry.put(COLOR_BLACK, new RGB(0, 0, 0));
}
colorBlack = colorRegistry.get(COLOR_BLACK);
}
GridLayoutFactory.fillDefaults().applyTo(parent);
Composite container = new Composite(parent, SWT.NULL);
container.setBackground(null);
Image image = null;
if (overview.getScreenshot() != null) {
image = computeImage(source, overview.getScreenshot());
if (image != null) {
final Image fimage = image;
container.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
fimage.dispose();
}
});
}
}
final boolean hasLearnMoreLink = overview.getUrl() != null && overview.getUrl().length() > 0;
final int borderWidth = 1;
final int fixedImageHeight = 240;
final int fixedImageWidth = 320;
final int heightHint = fixedImageHeight + (borderWidth * 2);
final int widthHint = fixedImageWidth;
final int containerWidthHintWithImage = 650;
final int containerWidthHintWithoutImage = 500;
GridDataFactory.fillDefaults().grab(true, true).hint(
image == null ? containerWidthHintWithoutImage : containerWidthHintWithImage, SWT.DEFAULT).applyTo(
container);
GridLayoutFactory.fillDefaults().numColumns(2).margins(5, 5).spacing(3, 0).applyTo(container);
String summary = overview.getSummary();
Composite summaryContainer = new Composite(container, SWT.NULL);
summaryContainer.setBackground(null);
GridLayoutFactory.fillDefaults().applyTo(summaryContainer);
GridDataFactory gridDataFactory = GridDataFactory.fillDefaults()
.grab(true, true)
.span(image == null ? 2 : 1, 1);
if (image != null) {
gridDataFactory.hint(widthHint, heightHint);
}
gridDataFactory.applyTo(summaryContainer);
Label summaryLabel = new Label(summaryContainer, SWT.WRAP);
summaryLabel.setText(summary);
summaryLabel.setBackground(null);
GridDataFactory.fillDefaults().grab(true, true).align(SWT.BEGINNING, SWT.BEGINNING).applyTo(summaryLabel);
if (image != null) {
final Composite imageContainer = new Composite(container, SWT.BORDER);
GridLayoutFactory.fillDefaults().applyTo(imageContainer);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.CENTER, SWT.BEGINNING).hint(
widthHint + (borderWidth * 2), heightHint).applyTo(imageContainer);
Label imageLabel = new Label(imageContainer, SWT.NULL);
GridDataFactory.fillDefaults().hint(widthHint, fixedImageHeight).indent(borderWidth, borderWidth).applyTo(
imageLabel);
imageLabel.setImage(image);
imageLabel.setBackground(null);
imageLabel.setSize(widthHint, fixedImageHeight);
// creates a border
imageContainer.setBackground(colorBlack);
}
if (hasLearnMoreLink) {
Link link = new Link(summaryContainer, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false).align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(null);
link.setToolTipText(NLS.bind(Messages.ConnectorDescriptorToolTip_detailsLink_tooltip, overview.getUrl()));
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil.openUrl(overview.getUrl(), IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
if (image == null) {
// prevent overviews with no image from providing unlimited text.
Point optimalSize = summaryContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
if (optimalSize.y > (heightHint + 10)) {
((GridData) summaryContainer.getLayoutData()).heightHint = heightHint;
container.layout(true);
}
}
// hack: cause the tooltip to gain focus so that we can capture the escape key
// this must be done async since the tooltip is not yet visible.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (!parent.isDisposed()) {
parent.setFocus();
}
}
});
return container;
}
private Image computeImage(AbstractDiscoverySource discoverySource, String imagePath) {
URL resource = discoverySource.getResource(imagePath);
if (resource != null) {
ImageDescriptor descriptor = ImageDescriptor.createFromURL(resource);
Image image = descriptor.createImage();
return image;
}
return null;
}
}
|
package io.jooby;
import javax.annotation.Nonnull;
/**
* Force SSL handler. Check for non-HTTPs request and force client to use HTTPs by redirecting the
* call to the HTTPs version.
*
* @author edgar
*/
public class SSLHandler implements Route.Before {
private static final int SECURE_PORT = 443;
private final String host;
private final int port;
private boolean useProxy;
/**
* Creates a SSLHandler and redirect non-HTTPS request to the given host and port.
*
* @param host Host to redirect.
* @param port HTTP port.
*/
public SSLHandler(@Nonnull String host, int port) {
this.host = host;
this.port = port;
}
/**
* Creates a SSLHandler and redirect non-HTTPS request to the given host.
*
* @param host Host to redirect.
*/
public SSLHandler(@Nonnull String host) {
this(host, SECURE_PORT);
}
/**
* Creates a SSLHandler and redirect non-HTTPs requests to the HTTPS version of this call. Host
* is recreated from <code>Host</code> header or <code>X-Forwarded-Host</code>.
*
* @param useProxy True for trust/use the <code>X-Forwarded-Host</code>. Otherwise, only the
* <code>Host</code> header is used it.
* @param port HTTPS port.
*/
public SSLHandler(boolean useProxy, int port) {
this.host = null;
this.port = port;
this.useProxy = useProxy;
}
/**
* Creates a SSLHandler and redirect non-HTTPs requests to the HTTPS version of this call. Host
* is recreated from <code>Host</code> header or <code>X-Forwarded-Host</code>.
*
* @param useProxy True for trust/use the <code>X-Forwarded-Host</code>. Otherwise, only the
* <code>Host</code> header is used it.
*/
public SSLHandler(boolean useProxy) {
this(useProxy, SECURE_PORT);
}
@Override public void apply(@Nonnull Context ctx) {
if (!ctx.isSecure()) {
String host;
if (this.host == null) {
String hostAndPort = ctx.getHostAndPort(useProxy);
int i = hostAndPort.lastIndexOf(':');
host = i > 0 ? hostAndPort.substring(0, i) : hostAndPort;
} else {
host = this.host;
}
StringBuilder buff = new StringBuilder("https:
buff.append(host);
if (host.equals("localhost")) {
int securePort = ctx.getRouter().getServerOptions().getSecurePort();
buff.append(":").append(securePort);
} else {
if (port > 0 && port != SECURE_PORT) {
buff.append(":").append(port);
}
}
buff.append(ctx.pathString());
buff.append(ctx.queryString());
ctx.sendRedirect(buff.toString());
}
}
}
|
package org.eclipse.mylar.internal.java.ui.editor;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer;
import org.eclipse.mylar.context.core.IMylarElement;
import org.eclipse.mylar.context.core.ContextCorePlugin;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.internal.context.core.MylarContextManager;
import org.eclipse.mylar.internal.context.ui.ContextUiImages;
/**
* TODO: parametrize relevance levels (requires JDT changes, bug 119063)
*
* @author Mik Kersten
*/
public class MylarJavaProposalProcessor {
static final int THRESHOLD_INTEREST = 10000;
private static final int THRESHOLD_IMPLICIT_INTEREST = THRESHOLD_INTEREST * 2;
private static final int RELEVANCE_IMPLICIT_INTEREST = 300;
private static final String IDENTIFIER_THIS = "this";
public static final String LABEL_SEPARATOR = "
public static final MylarProposalSeparator PROPOSAL_SEPARATOR = new MylarProposalSeparator();
private List<IJavaCompletionProposalComputer> monitoredProposalComputers = new ArrayList<IJavaCompletionProposalComputer>();
private List<IJavaCompletionProposalComputer> alreadyComputedProposals = new ArrayList<IJavaCompletionProposalComputer>();
private List<IJavaCompletionProposalComputer> alreadyContainSeparator = new ArrayList<IJavaCompletionProposalComputer>();
private List<IJavaCompletionProposalComputer> containsSingleInterestingProposal = new ArrayList<IJavaCompletionProposalComputer>();
private static MylarJavaProposalProcessor INSTANCE = new MylarJavaProposalProcessor();
private MylarJavaProposalProcessor() {
}
public static MylarJavaProposalProcessor getDefault() {
return INSTANCE;
}
public void addMonitoredComputer(IJavaCompletionProposalComputer proposalComputer) {
monitoredProposalComputers.add(proposalComputer);
}
@SuppressWarnings("unchecked")
public List projectInterestModel(IJavaCompletionProposalComputer proposalComputer, List proposals) {
try {
if (!ContextCorePlugin.getContextManager().isContextActive()) {
return proposals;
} else {
boolean hasInterestingProposals = false;
for (Object object : proposals) {
if (object instanceof AbstractJavaCompletionProposal) {
boolean foundInteresting = boostRelevanceWithInterest((AbstractJavaCompletionProposal) object);
if (!hasInterestingProposals && foundInteresting) {
hasInterestingProposals = true;
}
}
}
// NOTE: this annoying state needs to be maintainted to ensure
// the
// separator is added only once, and not added for single
// proposals
if (containsSingleInterestingProposal.size() > 0 && proposals.size() > 0) {
proposals.add(MylarJavaProposalProcessor.PROPOSAL_SEPARATOR);
} else if (hasInterestingProposals && alreadyContainSeparator.isEmpty()) {
if (proposals.size() == 1) {
containsSingleInterestingProposal.add(proposalComputer);
} else {
proposals.add(MylarJavaProposalProcessor.PROPOSAL_SEPARATOR);
alreadyContainSeparator.add(proposalComputer);
}
}
alreadyComputedProposals.add(proposalComputer);
if (alreadyComputedProposals.size() == monitoredProposalComputers.size()) {
alreadyComputedProposals.clear();
alreadyContainSeparator.clear();
containsSingleInterestingProposal.clear();
}
return proposals;
}
} catch (Throwable t) {
MylarStatusHandler.fail(t, "Failed to project interest onto propsals", false);
return proposals;
}
}
private boolean boostRelevanceWithInterest(AbstractJavaCompletionProposal proposal) {
boolean hasInteresting = false;
IJavaElement javaElement = proposal.getJavaElement();
if (javaElement != null) {
IMylarElement mylarElement = ContextCorePlugin.getContextManager().getElement(
javaElement.getHandleIdentifier());
float interest = mylarElement.getInterest().getValue();
if (interest > MylarContextManager.getScalingFactors().getInteresting()) {
// TODO: losing precision here, only going to one decimal place
proposal.setRelevance(THRESHOLD_INTEREST + (int) (interest * 10));
hasInteresting = true;
}
} else if (isImplicitlyInteresting(proposal)) {
proposal.setRelevance(THRESHOLD_IMPLICIT_INTEREST + proposal.getRelevance());
hasInteresting = true;
}
return hasInteresting;
}
public boolean isImplicitlyInteresting(AbstractJavaCompletionProposal proposal) {
return proposal.getRelevance() > RELEVANCE_IMPLICIT_INTEREST
&& !IDENTIFIER_THIS.equals(proposal.getDisplayString());
}
static class MylarProposalSeparator extends JavaCompletionProposal {
public MylarProposalSeparator() {
super("", 0, 0, ContextUiImages.getImage(ContextUiImages.CONTENT_ASSIST_SEPARATOR), LABEL_SEPARATOR,
MylarJavaProposalProcessor.THRESHOLD_INTEREST);
}
}
}
|
package org.lamport.tla.toolbox.tool.tlc.ui.editor.page;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.events.IHyperlinkListener;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import org.lamport.tla.toolbox.tool.tlc.output.ITLCOutputListener;
import org.lamport.tla.toolbox.tool.tlc.output.source.TLCOutputSourceRegistry;
import org.lamport.tla.toolbox.tool.tlc.output.source.TLCRegion;
import org.lamport.tla.toolbox.tool.tlc.output.source.TLCRegionContainer;
import org.lamport.tla.toolbox.tool.tlc.ui.TLCUIActivator;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.data.CoverageInformationItem;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.data.GeneralOutputParsingHwelper;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.data.StateSpaceInformationItem;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.data.TLCError;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.data.TLCState;
import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper;
import org.lamport.tla.toolbox.tool.tlc.ui.view.TLCErrorView;
import org.lamport.tla.toolbox.util.IHelpConstants;
import org.lamport.tla.toolbox.util.UIHelper;
import tlc2.output.EC;
import tlc2.output.MP;
/**
* A page to display results of model checking
* @author Simon Zambrovski
* @version $Id$
*/
public class ResultPage extends BasicFormPage implements ITLCOutputListener
{
public static final String ID = "resultPage";
private static final String NO_OUTPUT_AVAILABLE = "No execution data is available";
private SourceViewer output;
private SourceViewer progress;
private Text startTimeText;
private Text elapsedTimeText;
private Text coverageTimestampText;
private Hyperlink errorStatusHyperLink;
private TableViewer coverage;
private TableViewer stateSpace;
// list of all errors
private Vector errors;
// last detected error
private TLCError lastDetectedError = null;
// hyper link listener activated in case of errors
protected IHyperlinkListener errorHyperLinkListener = new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e)
{
TLCErrorView errorView = (TLCErrorView) UIHelper.openView(TLCErrorView.ID);
errorView.fill(errors);
}
};
// flag indicating that the job / file output is finished
private boolean isDone = false;
/**
* Content provider delivering list content
*/
private IContentProvider listContentProvider = new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
public void dispose()
{
}
public Object[] getElements(Object inputElement)
{
if (inputElement != null && inputElement instanceof List)
{
return ((List) inputElement).toArray(new Object[((List) inputElement).size()]);
}
return null;
}
};
/**
* @param editor
*/
public ResultPage(FormEditor editor)
{
super(editor, ID, "Model Checking Results");
this.helpId = IHelpConstants.RESULT_MODEL_PAGE;
this.imagePath = "icons/full/choice_sc_obj.gif";
}
/* (non-Javadoc)
* @see org.lamport.tla.toolbox.tool.tlc.output.ITLCOutputListener#onOutput(org.eclipse.jface.text.ITypedRegion, org.eclipse.jface.text.IDocument)
*/
public synchronized void onOutput(ITypedRegion region, IDocument document)
{
System.out.println(">");
// restarting
if (isDone)
{
// the only reason for this is the restart of the MC, after the previous run completed.
// clean up the output
isDone = false;
}
String outputMessage;
try
{
outputMessage = document.get(region.getOffset(), region.getLength());
} catch (BadLocationException e)
{
TLCUIActivator.logError("Error retrieving a message for the process", e);
TLCUIActivator.logDebug("R " + region);
return;
}
if (region instanceof TLCRegion)
{
TLCRegion tlcRegion = (TLCRegion) region;
int severity = tlcRegion.getSeverity();
int messageCode = tlcRegion.getMessageCode();
switch (severity) {
case MP.STATE:
Assert.isNotNull(this.lastDetectedError,
"The state encountered without the error describing the reason for it. This is a bug.");
this.lastDetectedError.addState(TLCState.parseState(outputMessage));
break;
case MP.ERROR:
case MP.TLCBUG:
case MP.WARNING:
switch (messageCode) {
// errors to skip
case EC.TLC_BEHAVIOR_UP_TO_THIS_POINT:
case EC.TLC_COUNTER_EXAMPLE:
break;
// usual errors
default:
if (lastDetectedError != null)
{
// something is detected which is not an error
// and the error trace is not empty
// add the trace to the error list
this.errors.add(lastDetectedError);
this.lastDetectedError = null;
}
updateErrorInformation();
this.lastDetectedError = createError(tlcRegion, document);
break;
}
break;
case MP.NONE:
if (lastDetectedError != null)
{
// something is detected which is not an error
// and the error trace is not empty
// add the trace to the error list
this.errors.add(lastDetectedError);
this.lastDetectedError = null;
updateErrorInformation();
}
switch (messageCode) {
// Progress information
case EC.TLC_VERSION:
case EC.TLC_SANY_START:
case EC.TLC_MODE_MC:
case EC.TLC_MODE_SIMU:
case EC.TLC_SANY_END:
case EC.TLC_COMPUTING_INIT:
case EC.TLC_CHECKING_TEMPORAL_PROPS:
case EC.TLC_SUCCESS:
case EC.TLC_PROGRESS_SIMU:
case EC.TLC_PROGRESS_START_STATS_DFID:
case EC.TLC_PROGRESS_STATS_DFID:
case EC.TLC_INITIAL_STATE:
case EC.TLC_INIT_GENERATED1:
case EC.TLC_INIT_GENERATED2:
case EC.TLC_INIT_GENERATED3:
case EC.TLC_INIT_GENERATED4:
case EC.TLC_STATS:
case EC.TLC_STATS_DFID:
case EC.TLC_STATS_SIMU:
case EC.TLC_SEARCH_DEPTH:
case EC.TLC_CHECKPOINT_START:
case EC.TLC_CHECKPOINT_END:
case EC.TLC_CHECKPOINT_RECOVER_START:
case EC.TLC_CHECKPOINT_RECOVER_END:
case EC.TLC_CHECKPOINT_RECOVER_END_DFID:
case EC.TLC_LIVE_IMPLIED:
setDocumentText(this.progress.getDocument(), outputMessage, true);
break;
case EC.TLC_STARTING:
String startingTimestamp = GeneralOutputParsingHwelper.parseTLCTimestamp(outputMessage);
setFieldText(this.startTimeText, startingTimestamp);
break;
case EC.TLC_FINISHED:
String finishedTimestamp = GeneralOutputParsingHwelper.parseTLCTimestamp(outputMessage);
setFieldText(this.elapsedTimeText, finishedTimestamp);
break;
case EC.TLC_PROGRESS_STATS:
final StateSpaceInformationItem stateSpaceInformationItem = StateSpaceInformationItem
.parse(outputMessage);
UIHelper.runUIAsync(new Runnable() {
public void run()
{
// TODO add to the model
ResultPage.this.stateSpace.add(stateSpaceInformationItem);
ResultPage.this.stateSpace.refresh(stateSpaceInformationItem);
}
});
break;
// Coverage information
case EC.TLC_COVERAGE_START:
String coverageTimestamp = CoverageInformationItem.parseCoverageTimestamp(outputMessage);
setFieldText(this.coverageTimestampText, coverageTimestamp);
UIHelper.runUIAsync(new Runnable() {
public void run()
{
ResultPage.this.coverage.setInput(new Vector());
}
});
break;
case EC.TLC_COVERAGE_VALUE:
final CoverageInformationItem coverageInformationItem = CoverageInformationItem
.parse(outputMessage);
UIHelper.runUIAsync(new Runnable() {
public void run()
{
// TODO add to the model
ResultPage.this.coverage.add(coverageInformationItem);
ResultPage.this.coverage.refresh(coverageInformationItem);
}
});
break;
case EC.TLC_COVERAGE_END:
break;
default:
setDocumentText(this.output.getDocument(), outputMessage, true);
break;
}
break;
default:
throw new IllegalArgumentException("This is a bug, the TLCToken with unexpected severity detected: "
+ severity);
}
} else
{
setDocumentText(this.output.getDocument(), outputMessage, true);
// TLCUIActivator.logDebug("Unknown type detected: " + region.getType() + " message " + outputMessage);
}
}
/**
* @param tlcRegion
* @param document
* @return
*/
private TLCError createError(TLCRegion tlcRegion, IDocument document)
{
TLCError topError = new TLCError();
if (tlcRegion instanceof TLCRegionContainer)
{
TLCRegionContainer container = (TLCRegionContainer) tlcRegion;
ITypedRegion[] regions = container.getSubRegions();
Assert.isTrue(regions.length < 3, "Unexpected error region structure, this is a bug.");
for (int i = 0; i < regions.length; i++)
{
if (regions[i] instanceof TLCRegion)
{
TLCError cause = createError((TLCRegion) regions[i], document);
topError.setCause(cause);
} else
{
String output;
try
{
output = document.get(tlcRegion.getOffset(), tlcRegion.getLength());
topError.setMessage(output);
topError.setErrorCode(tlcRegion.getMessageCode());
} catch (BadLocationException e)
{
TLCUIActivator.logError("Error parsing the error message", e);
}
}
}
}
return topError;
}
protected void loadData() throws CoreException
{
// TLCUIActivator.logDebug("Entering loadData()");
TLCOutputSourceRegistry.getStatusRegistry().disconnect(this);
// re-init the fields
reinit();
TLCOutputSourceRegistry.getStatusRegistry().connect(this);
// TLCUIActivator.logDebug("Exiting loadData()");
}
/**
* reload the data on activation
*/
public void setActive(boolean active)
{
if (active)
{
// refresh
try
{
loadData();
} catch (CoreException e)
{
TLCUIActivator.logError("Error refreshing the page", e);
}
}
super.setActive(active);
}
/**
* @see org.lamport.tla.toolbox.tool.tlc.output.ITLCOutputListener#getProcessName()
*/
public String getProcessName()
{
// the model file name is good because it is unique
return getConfig().getFile().getName();
}
/**
* @see org.lamport.tla.toolbox.tool.tlc.output.ITLCOutputListener#onDone()
*/
public synchronized void onDone()
{
this.isDone = true;
if (lastDetectedError != null)
{
// something is detected which is not an error
// and the error trace is not empty
// add the trace to the error list
this.errors.add(lastDetectedError);
this.lastDetectedError = null;
}
updateErrorInformation();
TLCUIActivator.logDebug("Done");
}
/**
* @see org.lamport.tla.toolbox.tool.tlc.output.ITLCOutputListener#newSourceOccured(int)
*/
public synchronized void onNewSource()
{
UIHelper.runUIAsync(new Runnable() {
public void run()
{
reinit();
}
});
}
/**
* Updates the view indicating the number of errors found
*/
public synchronized void updateErrorInformation()
{
UIHelper.runUIAsync(new Runnable() {
public void run()
{
ResultPage.this.errorStatusHyperLink.setText(String.valueOf(errors.size() + " Errors"));
if (ResultPage.this.errors.size() > 0)
{
ResultPage.this.errorStatusHyperLink.addHyperlinkListener(ResultPage.this.errorHyperLinkListener);
ResultPage.this.errorStatusHyperLink.setForeground(TLCUIActivator.getColor(SWT.COLOR_RED));
} else
{
ResultPage.this.errorStatusHyperLink
.removeHyperlinkListener(ResultPage.this.errorHyperLinkListener);
ResultPage.this.errorStatusHyperLink.setForeground(TLCUIActivator.getColor(SWT.COLOR_BLACK));
}
// update the error view
updateErrorView(ResultPage.this.errors);
}
});
// TLCUIActivator.logDebug("Errors changed, now have " + errors.size() + ".");
}
/**
* Display the errors in the view
* @param errors
*/
private static void updateErrorView(List errors)
{
TLCErrorView errorView = (TLCErrorView) UIHelper.openView(TLCErrorView.ID);
if (errorView != null)
{
errorView.fill(errors);
}
}
/**
* Reinitialize the fields
*/
public synchronized void reinit()
{
this.startTimeText.setText("");
this.elapsedTimeText.setText("");
this.errorStatusHyperLink.setText("");
this.coverage.setInput(new Vector());
this.stateSpace.setInput(new Vector());
this.progress.setDocument(new Document(NO_OUTPUT_AVAILABLE));
this.output.setDocument(new Document(NO_OUTPUT_AVAILABLE));
this.errors = new Vector();
// update the error window and the trace explorer
this.updateErrorInformation();
}
/**
* Sets the field text
* @param field
* @param text
*/
public synchronized void setFieldText(final Text field, final String text)
{
UIHelper.runUIAsync(new Runnable() {
public void run()
{
field.setText(text);
}
});
}
/**
* Sets text to a document
* @param document
* @param message
* @param append
* @throws BadLocationException
*/
public synchronized void setDocumentText(final IDocument document, final String message, final boolean append)
{
final String CR = "\n";
final String EMPTY = "";
UIHelper.runUIAsync(new Runnable() {
public void run()
{
try
{
if (append)
{
if (document.getLength() == NO_OUTPUT_AVAILABLE.length())
{
String content = document.get(0, NO_OUTPUT_AVAILABLE.length());
if (content != null && NO_OUTPUT_AVAILABLE.equals(content))
{
document.replace(0, document.getLength(), message
+ ((message.endsWith(CR)) ? EMPTY : CR));
}
} else
{
document.replace(document.getLength(), 0, message + ((message.endsWith(CR)) ? EMPTY : CR));
}
} else
{
document.replace(0, document.getLength(), message + ((message.endsWith(CR)) ? EMPTY : CR));
}
} catch (BadLocationException e)
{
}
}
});
}
/**
* Dispose the page
*/
public void dispose()
{
TLCOutputSourceRegistry.getStatusRegistry().disconnect(this);
super.dispose();
}
public void setEnabled(boolean enabled)
{
// do nothing here, since the result page is read-only per definition
}
/**
* Draw the fields
*/
protected void createBodyContent(IManagedForm managedForm)
{
int sectionFlags = Section.TITLE_BAR | Section.DESCRIPTION | Section.TREE_NODE | Section.EXPANDED | SWT.WRAP;
int textFieldFlags = SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY | SWT.FULL_SELECTION | SWT.WRAP;
FormToolkit toolkit = managedForm.getToolkit();
Composite body = managedForm.getForm().getBody();
TableWrapLayout layout = new TableWrapLayout();
layout.numColumns = 2;
body.setLayout(layout);
TableWrapData twd;
Section section;
GridData gd;
// general section
section = FormHelper.createSectionComposite(body, "General", "The current progress of model-checking", toolkit,
sectionFlags, getExpansionListener());
twd = new TableWrapData();
twd.colspan = 2;
section.setLayoutData(twd);
Composite generalArea = (Composite) section.getClient();
generalArea.setLayout(new GridLayout());
Composite statusComposite = toolkit.createComposite(generalArea);
statusComposite.setLayout(new GridLayout(2, false));
// start
startTimeText = createTextLeft("Start time:", statusComposite, toolkit);
// elapsed time
elapsedTimeText = createTextLeft("Elapsed time:", statusComposite, toolkit);
// errors
// Label createLabel =
toolkit.createLabel(statusComposite, "Errors detected:");
this.errorStatusHyperLink = toolkit.createHyperlink(statusComposite, "", SWT.RIGHT);
// statistics section
section = FormHelper.createSectionComposite(body, "Statistics", "The current progress of model-checking",
toolkit, sectionFlags | Section.COMPACT, getExpansionListener());
twd = new TableWrapData();
twd.colspan = 2;
section.setLayoutData(twd);
Composite statArea = (Composite) section.getClient();
statArea = (Composite) section.getClient();
layout = new TableWrapLayout();
layout.numColumns = 2;
statArea.setLayout(layout);
// progress stats
// Composite stateStats =
createAndSetupStateSpace("State space progress statistics:", statArea, toolkit);
// coverage stats
// Composite coverageStats =
createAndSetupCoverage("Coverage statistics at", statArea, toolkit);
// progress section
section = FormHelper.createSectionComposite(body, "Progress Output", "The current progress of model-checking",
toolkit, sectionFlags, getExpansionListener());
Composite progressArea = (Composite) section.getClient();
progressArea = (Composite) section.getClient();
progressArea.setLayout(new GridLayout());
progress = FormHelper.createFormsOutputViewer(toolkit, progressArea, textFieldFlags);
gd = new GridData(SWT.FILL, SWT.LEFT, true, true);
gd.minimumHeight = 300;
gd.minimumWidth = 300;
progress.getControl().setLayoutData(gd);
// output section
section = FormHelper.createSectionComposite(body, "User Output", "Output created by TLC during the execution",
toolkit, sectionFlags, getExpansionListener());
Composite outputArea = (Composite) section.getClient();
outputArea.setLayout(new GridLayout());
// output viewer
output = FormHelper.createFormsOutputViewer(toolkit, outputArea, textFieldFlags);
gd = new GridData(SWT.FILL, SWT.LEFT, true, true);
gd.minimumHeight = 300;
gd.minimumWidth = 300;
output.getControl().setLayoutData(gd);
}
/**
* Creates the state space table
* @param label
* @param parent
* @param toolkit
* @return
*/
private Composite createAndSetupStateSpace(String label, Composite parent, FormToolkit toolkit)
{
Composite statespaceComposite = toolkit.createComposite(parent, SWT.WRAP);
statespaceComposite.setLayout(new GridLayout(1, false));
toolkit.createLabel(statespaceComposite, label);
Table stateTable = toolkit.createTable(statespaceComposite, SWT.MULTI | SWT.FULL_SELECTION | SWT.V_SCROLL
| SWT.BORDER);
GridData gd = new GridData(StateSpaceLabelProvider.MIN_WIDTH, 100);
stateTable.setLayoutData(gd);
stateTable.setHeaderVisible(true);
stateTable.setLinesVisible(true);
StateSpaceLabelProvider.createTableColumns(stateTable);
// create the viewer
this.stateSpace = new TableViewer(stateTable);
// create list-based content provider
this.stateSpace.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
public void dispose()
{
}
public Object[] getElements(Object inputElement)
{
if (inputElement != null && inputElement instanceof List)
{
return ((List) inputElement).toArray(new Object[((List) inputElement).size()]);
}
return null;
}
});
this.stateSpace.setLabelProvider(new StateSpaceLabelProvider());
return statespaceComposite;
}
/**
* Creates the state space table
* @param label
* @param parent
* @param toolkit
* @return
*/
private Composite createAndSetupCoverage(String label, Composite parent, FormToolkit toolkit)
{
Composite coverageComposite = toolkit.createComposite(parent, SWT.WRAP);
coverageComposite.setLayout(new GridLayout(2, false));
// coverageComposite.setLayoutData(gd);
GridData gd = new GridData();
toolkit.createLabel(coverageComposite, label);
this.coverageTimestampText = toolkit.createText(coverageComposite, "", SWT.FLAT);
this.coverageTimestampText.setEditable(false);
gd = new GridData();
gd.minimumWidth = 200;
gd.grabExcessHorizontalSpace = true;
this.coverageTimestampText.setLayoutData(gd);
Table stateTable = toolkit.createTable(coverageComposite, SWT.MULTI | SWT.FULL_SELECTION | SWT.V_SCROLL
| SWT.BORDER);
gd = new GridData(CoverageLabelProvider.MIN_WIDTH, 100);
gd.horizontalSpan = 2;
stateTable.setLayoutData(gd);
stateTable.setHeaderVisible(true);
stateTable.setLinesVisible(true);
CoverageLabelProvider.createTableColumns(stateTable);
// create the viewer
this.coverage = new TableViewer(stateTable);
// create list-based content provider
this.coverage.setContentProvider(listContentProvider);
this.coverage.setLabelProvider(new CoverageLabelProvider());
return coverageComposite;
}
/**
* Creates a text component with left-aligned text
* @param title
* @param parent
* @param toolkit
* @return
*/
private static Text createTextLeft(String title, Composite parent, FormToolkit toolkit)
{
Label createLabel = toolkit.createLabel(parent, title);
GridData gd = new GridData();
createLabel.setLayoutData(gd);
gd.verticalAlignment = SWT.TOP;
Text text = toolkit.createText(parent, "");
gd = new GridData(SWT.FILL, SWT.LEFT, true, false);
gd.horizontalIndent = 30;
gd.verticalAlignment = SWT.TOP;
gd.horizontalAlignment = SWT.RIGHT;
gd.minimumWidth = 150;
text.setLayoutData(gd);
return text;
}
/**
* Provides labels for the statespace table
*/
static class StateSpaceLabelProvider extends LabelProvider implements ITableLabelProvider
{
public final static String[] columnTitles = new String[] { "Time", "Diameter", "States Found",
"States Distinct", "States Left" };
public final static int[] columnWidths = { 120, 60, 80, 100, 80 };
public static final int MIN_WIDTH = columnWidths[0] + columnWidths[1] + columnWidths[2] + columnWidths[3]
+ columnWidths[4];
public final static int COL_TIME = 0;
public final static int COL_DIAMETER = 1;
public final static int COL_FOUND = 2;
public final static int COL_DISTINCT = 3;
public final static int COL_LEFT = 4;
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // $NON-NLS-1$
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage(Object element, int columnIndex)
{
return null;
}
/**
* @param stateTable
*/
public static void createTableColumns(Table stateTable)
{
// create table headers
for (int i = 0; i < columnTitles.length; i++)
{
TableColumn column = new TableColumn(stateTable, SWT.NULL);
column.setWidth(columnWidths[i]);
column.setText(columnTitles[i]);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex)
{
if (element instanceof StateSpaceInformationItem)
{
StateSpaceInformationItem item = (StateSpaceInformationItem) element;
switch (columnIndex) {
case COL_TIME:
return sdf.format(item.getTime());
case COL_DIAMETER:
return String.valueOf(item.getDiameter());
case COL_FOUND:
return String.valueOf(item.getFoundStates());
case COL_DISTINCT:
return String.valueOf(item.getDistinctStates());
case COL_LEFT:
return String.valueOf(item.getLeftStates());
}
}
return null;
}
}
/**
* Provides labels for the coverage table
*/
static class CoverageLabelProvider extends LabelProvider implements ITableLabelProvider
{
public final static String[] columnTitles = new String[] { "Module", "Location", "Count" };
public final static int[] columnWidths = { 80, 200, 80 };
public static final int MIN_WIDTH = columnWidths[0] + columnWidths[1] + columnWidths[2];
public final static int COL_MODULE = 0;
public final static int COL_LOCATION = 1;
public final static int COL_COUNT = 2;
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage(Object element, int columnIndex)
{
return null;
}
/**
* @param stateTable
*/
public static void createTableColumns(Table stateTable)
{
// create table headers
for (int i = 0; i < columnTitles.length; i++)
{
TableColumn column = new TableColumn(stateTable, SWT.NULL);
column.setWidth(columnWidths[i]);
column.setText(columnTitles[i]);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex)
{
if (element instanceof CoverageInformationItem)
{
CoverageInformationItem item = (CoverageInformationItem) element;
switch (columnIndex) {
case COL_MODULE:
return item.getModule();
case COL_LOCATION:
return item.getLocation();
case COL_COUNT:
return String.valueOf(item.getCount());
}
}
return null;
}
}
}
|
package peergos.shared.user.fs;
public class MimeTypes {
final static int[] ID3 = new int[]{'I', 'D', '3'};
final static int[] MP3 = new int[]{0xff, 0xfb};
final static int[] WAV_1 = new int[]{'R', 'I', 'F', 'F'};
final static int[] WAV_2 = new int[]{'W', 'A', 'V', 'E'};
final static int[] MP4 = new int[]{'f', 't', 'y', 'p'};
final static int[] FLV = new int[]{'F', 'L', 'V'};
final static int[] AVI = new int[]{'A', 'V', 'I', ' '};
final static int[] OGG = new int[]{'O', 'g', 'g', 'S', 0, 2};
final static int[] WEBM = new int[]{'w', 'e', 'b', 'm'};
final static int[] MATROSKA = new int[]{0x6D, 0x61, 0x74, 0x72, 0x6F, 0x73, 0x6B, 0x61};
final static int[] ICO = new int[]{0, 0, 1, 0};
final static int[] CUR = new int[]{0, 0, 2, 0};
final static int[] BMP = new int[]{'B', 'M'};
final static int[] GIF = new int[]{'G', 'I', 'F'};
final static int[] JPEG = new int[]{255, 216};
final static int[] TIFF1 = new int[]{'I', 'I', 0x2A, 0};
final static int[] TIFF2 = new int[]{'M', 'M', 0, 0x2A};
final static int[] PNG = new int[]{137, 'P', 'N', 'G', 13, 10, 26, 10};
final static int HEADER_BYTES_TO_IDENTIFY_MIME_TYPE = 28;
public static final String calculateMimeType(byte[] start) {
if (equalArrays(start, BMP))
return "image/bmp";
if (equalArrays(start, GIF))
return "image/gif";
if (equalArrays(start, PNG))
return "image/png";
if (equalArrays(start, JPEG))
return "image/jpg";
if (equalArrays(start, ICO))
return "image/x-icon";
if (equalArrays(start, CUR))
return "image/x-icon";
// many browsers don't support tiff
if (equalArrays(start, TIFF1))
return "image/tiff";
if (equalArrays(start, TIFF2))
return "image/tiff";
if (equalArrays(start, 4, MP4))
return "video/mp4";
if (equalArrays(start, 24, WEBM))
return "video/webm";
if (equalArrays(start, OGG))
return "video/ogg";
if (equalArrays(start, 8, MATROSKA))
return "video/x-matroska";
if (equalArrays(start, FLV))
return "video/x-flv";
if (equalArrays(start, 8, AVI))
return "video/avi";
if (equalArrays(start, ID3))
return "audio/mpeg";
if (equalArrays(start, MP3))
return "audio/mpeg";
if (equalArrays(start, OGG)) // not sure how to distinguish from ogg video easily
return "audio/ogg";
if (equalArrays(start, WAV_1) && equalArrays(start, 8, WAV_2))
return "audio/wav";
if (allAscii(start))
return "text/plain";
return "";
}
private static boolean allAscii(byte[] data) {
for (byte b : data) {
if ((b & 0xff) > 0x80)
return false;
if ((b & 0xff) < 0x20 && b != (byte)0x10 && b != (byte) 0x13)
return false;
}
return true;
}
private static boolean equalArrays(byte[] a, int[] target) {
return equalArrays(a, 0, target);
}
private static boolean equalArrays(byte[] a, int aOffset, int[] target) {
if (a == null || target == null){
return false;
}
for (int i=0; i < target.length; i++) {
if ((a[i + aOffset] & 0xff) != (target[i] & 0xff)) {
return false;
}
}
return true;
}
}
|
package org.python.pydev.debug.ui.launching;
import java.io.IOException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;
import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
import org.python.pydev.core.log.Log;
import org.python.pydev.debug.core.Constants;
import org.python.pydev.debug.core.PydevDebugPlugin;
/**
*
* Launcher for the python scripts.
*
* <p>The code is pretty much copied from ExternalTools' ProgramLaunchDelegate.
* <p>I would have subclassed, but ProgramLaunchDelegate hides important internals
*
* Based on org.eclipse.ui.externaltools.internal.program.launchConfigurations.ProgramLaunchDelegate
*
* Build order based on org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate
*/
public abstract class AbstractLaunchConfigurationDelegate extends LaunchConfigurationDelegate implements ILaunchConfigurationDelegate {
private IProject[] fOrderedProjects;
/**
* We need to reimplement this method (otherwise, all the projects in the workspace will be rebuilt, and not only
* the ones referenced in the configuration).
*/
@Override
protected IProject[] getBuildOrder(ILaunchConfiguration configuration, String mode) throws CoreException {
return fOrderedProjects;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate2#preLaunchCheck(org.eclipse.debug.core.ILaunchConfiguration,
* java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public boolean preLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException {
// build project list
fOrderedProjects = null;
String projName = configuration.getAttribute(Constants.ATTR_PROJECT, "");
if(projName.length() > 0){
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projName);
if (project != null) {
fOrderedProjects = computeReferencedBuildOrder(new IProject[] { project });
}
}
// do generic launch checks
return super.preLaunchCheck(configuration, mode, monitor);
}
/**
* Launches the python process.
*
* Modelled after Ant & Java runners
* see WorkbenchLaunchConfigurationDelegate::launch
*/
public void launch(ILaunchConfiguration conf, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Preparing configuration", 3);
PythonRunnerConfig runConfig = new PythonRunnerConfig(conf, mode, getRunnerConfigRun());
monitor.worked(1);
try {
PythonRunner.run(runConfig, launch, monitor);
} catch (IOException e) {
Log.log(e);
throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Unexpected IO Exception in Pydev debugger", null));
}
}
/**
* @return the mode we should use to run it...
*
* @see PythonRunnerConfig#RUN_REGULAR
* @see PythonRunnerConfig#RUN_COVERAGE
* @see PythonRunnerConfig#RUN_UNITTEST
* @see PythonRunnerConfig#RUN_JYTHON_UNITTEST
* @see PythonRunnerConfig#RUN_JYTHON
*/
protected abstract String getRunnerConfigRun();
}
|
package org.spoofax.interpreter.library.index;
import static org.spoofax.interpreter.core.Tools.isTermAppl;
import static org.spoofax.interpreter.core.Tools.isTermList;
import java.io.Serializable;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoConstructor;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.IStrategoTuple;
import org.spoofax.interpreter.terms.ITermFactory;
public class IndexURI implements Serializable {
private static final long serialVersionUID = 1619836759792533807L;
private final IStrategoConstructor constructor;
private final IStrategoTerm identifier;
private final IStrategoTerm type;
private transient IStrategoAppl cachedTerm;
/**
* Use {@link IndexEntryFactory#createURI}.
*/
protected IndexURI(IStrategoConstructor constructor, IStrategoTerm identifier, IStrategoTerm type) {
this.constructor = constructor;
this.identifier = identifier;
this.type = type;
assert constructor != null && identifier != null;
}
public IStrategoConstructor getConstructor() {
return constructor;
}
public IStrategoTerm getIdentifier() {
return identifier;
}
public IStrategoTerm getType() {
return type;
}
/**
* Returns a parent URI by taking the tail of the path. If the path has no tail, null is returned.
*/
public IndexURI getParent(ITermFactory factory) {
// TODO: Maybe this should be performed by a user-defined strategy?
if(isTermList(identifier)) {
IStrategoList parentPath = getParentPath((IStrategoList) identifier, factory);
if(parentPath == null)
return null;
return new IndexURI(constructor, parentPath, type);
} else if(isTermAppl(identifier)) {
IStrategoAppl appl = (IStrategoAppl) identifier;
for(int i = 0; i < identifier.getSubtermCount(); ++i) {
if(isTermList(identifier.getSubterm(i))) {
IStrategoList parentPath = getParentPath((IStrategoList) identifier.getSubterm(i), factory);
if(parentPath == null)
return null;
IStrategoTerm[] subterms = identifier.getAllSubterms().clone();
subterms[i] = parentPath;
return new IndexURI(constructor, factory.makeAppl(appl.getConstructor(), subterms), type);
}
}
}
return null;
}
private IStrategoList getParentPath(IStrategoList path, ITermFactory factory) {
if(path.size() > 0) {
IStrategoTerm head = path.head();
if(head.getTermType() == IStrategoTerm.APPL && head.getSubtermCount() == 0)
// Retain the head of the path if it is a namespace (APPL with 0 subterms).
return factory.makeListCons(head, path.tail().tail());
else
return path.tail();
}
return null;
}
/**
* Returns the term representation of this entry.
*/
public IStrategoAppl toTerm(ITermFactory factory, IStrategoTerm value) {
if(cachedTerm != null)
return cachedTerm;
if(IndexEntryFactory.isDefData(constructor)) {
cachedTerm = factory.makeAppl(constructor, identifier, type, value);
} else if(constructor.getArity() == 2) {
cachedTerm = factory.makeAppl(constructor, identifier, value);
} else if(constructor.getArity() == 1) {
cachedTerm = factory.makeAppl(constructor, identifier);
} else {
IStrategoTerm[] terms = new IStrategoTerm[constructor.getArity()];
terms[0] = identifier;
IStrategoTuple values = (IStrategoTuple) value;
System.arraycopy(values.getAllSubterms(), 0, terms, 1, values.getSubtermCount());
cachedTerm = factory.makeAppl(constructor, terms);
}
return cachedTerm;
}
@Override
public String toString() {
String result = constructor.getName() + "(" + identifier + ")";
if(type != null)
result += "," + type;
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((constructor == null) ? 0 : constructor.hashCode());
result = prime * result + ((identifier == null) ? 0 : identifier.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof IndexURI))
return false;
IndexURI other = (IndexURI) obj;
if(constructor == null) {
if(other.constructor != null)
return false;
} else if(!constructor.equals(other.constructor))
return false;
if(identifier == null) {
if(other.identifier != null)
return false;
} else if(!identifier.equals(other.identifier))
return false;
if(type == null) {
if(other.type != null)
return false;
} else if(!type.equals(other.type))
return false;
return true;
}
}
|
package com.redhat.ceylon.eclipse.code.open;
import static com.redhat.ceylon.eclipse.code.complete.CodeCompletions.getQualifiedDescriptionFor;
import static com.redhat.ceylon.eclipse.code.editor.Navigation.gotoDeclaration;
import static com.redhat.ceylon.eclipse.code.hover.DocumentationHover.getDocumentationFor;
import static com.redhat.ceylon.eclipse.code.hover.DocumentationHover.getLinkedModel;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.addPageEpilog;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.insertPageProlog;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getImageForDeclaration;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getModuleLabel;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getPackageLabel;
import static com.redhat.ceylon.eclipse.code.preferences.CeylonPreferenceInitializer.PARAMS_IN_DIALOGS;
import static com.redhat.ceylon.eclipse.code.preferences.CeylonPreferenceInitializer.PARAM_TYPES_IN_DIALOGS;
import static com.redhat.ceylon.eclipse.code.preferences.CeylonPreferenceInitializer.RETURN_TYPES_IN_DIALOGS;
import static com.redhat.ceylon.eclipse.code.preferences.CeylonPreferenceInitializer.TYPE_PARAMS_IN_DIALOGS;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjectTypeChecker;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjects;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getUnits;
import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.getOpenDialogFont;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_MODULE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_PACKAGE;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CONFIG_LABELS;
import static com.redhat.ceylon.eclipse.util.EditorUtil.getCurrentEditor;
import static com.redhat.ceylon.eclipse.util.EditorUtil.getPreferences;
import static com.redhat.ceylon.eclipse.util.Highlights.PACKAGE_STYLER;
import static com.redhat.ceylon.model.cmr.JDKUtils.isJDKModule;
import static com.redhat.ceylon.model.cmr.JDKUtils.isOracleJDKModule;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isNameMatching;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isOverloadedVersion;
import static org.eclipse.jface.viewers.StyledString.COUNTER_STYLER;
import static org.eclipse.ui.dialogs.PreferencesUtil.createPreferenceDialogOn;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.html.HTML;
import com.redhat.ceylon.eclipse.code.preferences.CeylonFiltersPreferencePage;
import com.redhat.ceylon.eclipse.code.preferences.CeylonOpenDialogsPreferencePage;
import com.redhat.ceylon.eclipse.core.model.CrossProjectSourceFile;
import com.redhat.ceylon.eclipse.core.model.EditedSourceFile;
import com.redhat.ceylon.eclipse.core.model.IResourceAware;
import com.redhat.ceylon.eclipse.core.model.JDTModule;
import com.redhat.ceylon.eclipse.core.model.JavaCompilationUnit;
import com.redhat.ceylon.eclipse.core.model.ProjectSourceFile;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
import com.redhat.ceylon.eclipse.ui.CeylonResources;
import com.redhat.ceylon.eclipse.util.DocBrowser;
import com.redhat.ceylon.eclipse.util.Filters;
import com.redhat.ceylon.eclipse.util.ModelProxy;
import com.redhat.ceylon.model.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.Module;
import com.redhat.ceylon.model.typechecker.model.Modules;
import com.redhat.ceylon.model.typechecker.model.Package;
import com.redhat.ceylon.model.typechecker.model.Referenceable;
import com.redhat.ceylon.model.typechecker.model.Unit;
public class OpenDeclarationDialog extends FilteredItemsSelectionDialog {
private static final String SHOW_SELECTION_MODULE =
"showSelectionModule";
private static final String SHOW_SELECTION_PACKAGE =
"showSelectionPackage";
private static final String EXCLUDE_DEPRECATED =
"excludeDeprecated";
private static final String EXCLUDE_JDK =
"excludeJDK";
private static final String EXCLUDE_ORA_JDK =
"excludeOracleJDK";
// private static final Image MEMBERS_IMAGE =
// CeylonPlugin.getInstance().getImageRegistry().get(CeylonResources.SHOW_MEMBERS);
private static final String SETTINGS_ID =
CeylonPlugin.PLUGIN_ID
+ ".openDeclarationDialog";
private boolean includeMembers;
private boolean excludeDeprecated;
private boolean excludeJDK;
private boolean excludeOracleJDK;
private int filterVersion = 0;
private boolean showSelectionPackage;
private boolean showSelectionModule;
private TogglePackageAction togglePackageAction;
private ToggleModuleAction toggleModuleAction;
private ToggleExcludeDeprecatedAction toggleExcludeDeprecatedAction;
private ToggleExcludeJDKAction toggleExcludeJDKAction;
private ToggleExcludeOracleJDKAction toggleExcludeOracleJDKAction;
// private ToolItem toggleMembersToolItem;
// private ToggleMembersAction toggleMembersAction;
protected String emptyDoc;
@Override
protected void applyFilter() {
includeMembers =
getPatternControl().getText()
.contains(".");
// toggleMembersAction.setChecked(includeMembers);
super.applyFilter();
}
// private final class ToggleMembersAction extends Action {
// private ToggleMembersAction() {
// super("Include Member Declarations", IAction.AS_CHECK_BOX);
// setImageDescriptor(CeylonPlugin.getInstance().getImageRegistry().getDescriptor(CeylonResources.SHOW_MEMBERS));
// @Override
// public void run() {
// includeMembers=!includeMembers;
// applyFilter();
//// if (toggleMembersToolItem!=null) {
//// toggleMembersToolItem.setSelection(includeMembers);
private class ToggleExcludeDeprecatedAction
extends Action {
ToggleExcludeDeprecatedAction() {
super("Exclude Deprecated Declarations",
AS_CHECK_BOX);
}
@Override
public void run() {
excludeDeprecated=!excludeDeprecated;
filterVersion++;
applyFilter();
}
}
private class ToggleExcludeJDKAction
extends Action {
ToggleExcludeJDKAction() {
super("Exclude Java SDK",
AS_CHECK_BOX);
}
@Override
public void run() {
excludeJDK=!excludeJDK;
filterVersion++;
applyFilter();
}
}
private class ToggleExcludeOracleJDKAction
extends Action {
ToggleExcludeOracleJDKAction() {
super("Exclude Java SDK Internals",
AS_CHECK_BOX);
}
@Override
public void run() {
excludeOracleJDK=!excludeOracleJDK;
filterVersion++;
applyFilter();
}
}
private class TogglePackageAction
extends Action {
private TogglePackageAction() {
super("Show Selection Package",
AS_CHECK_BOX);
ImageDescriptor desc =
CeylonPlugin.imageRegistry()
.getDescriptor(CEYLON_PACKAGE);
setImageDescriptor(desc);
}
@Override
public void run() {
showSelectionPackage = !showSelectionPackage;
refresh();
}
}
private class ToggleModuleAction extends Action {
private ToggleModuleAction() {
super("Show Selection Module", AS_CHECK_BOX);
ImageDescriptor desc =
CeylonPlugin.imageRegistry()
.getDescriptor(CEYLON_MODULE);
setImageDescriptor(desc);
}
@Override
public void run() {
showSelectionModule = !showSelectionModule;
refresh();
}
}
protected void restoreDialog(IDialogSettings settings) {
super.restoreDialog(settings);
if (settings.get(SHOW_SELECTION_PACKAGE)!=null) {
showSelectionPackage =
settings.getBoolean(
SHOW_SELECTION_PACKAGE);
}
if (settings.get(SHOW_SELECTION_MODULE)!=null) {
showSelectionModule =
settings.getBoolean(
SHOW_SELECTION_MODULE);
}
if (settings.get(EXCLUDE_DEPRECATED)!=null) {
excludeDeprecated =
settings.getBoolean(EXCLUDE_DEPRECATED);
}
if (settings.get(EXCLUDE_JDK)!=null) {
excludeJDK =
settings.getBoolean(EXCLUDE_JDK);
}
if (settings.get(EXCLUDE_ORA_JDK)!=null) {
excludeOracleJDK =
settings.getBoolean(EXCLUDE_ORA_JDK);
}
else {
excludeOracleJDK = true;
}
if (togglePackageAction!=null) {
togglePackageAction.setChecked(
showSelectionPackage);
}
if (toggleModuleAction!=null) {
toggleModuleAction.setChecked(
showSelectionModule);
}
if (toggleExcludeDeprecatedAction!=null) {
toggleExcludeDeprecatedAction.setChecked(
excludeDeprecated);
}
if (toggleExcludeJDKAction!=null) {
toggleExcludeJDKAction.setChecked(
excludeJDK);
}
if (toggleExcludeOracleJDKAction!=null) {
toggleExcludeOracleJDKAction.setChecked(
excludeOracleJDK);
}
}
protected void storeDialog(IDialogSettings settings) {
super.storeDialog(settings);
settings.put(SHOW_SELECTION_MODULE,
showSelectionModule);
settings.put(SHOW_SELECTION_PACKAGE,
showSelectionPackage);
settings.put(EXCLUDE_DEPRECATED,
excludeDeprecated);
settings.put(EXCLUDE_JDK,
excludeJDK);
settings.put(EXCLUDE_ORA_JDK,
excludeOracleJDK);
}
private static Declaration toDeclaration(Object object) {
if (object instanceof DeclarationProxy) {
DeclarationProxy proxy =
(DeclarationProxy) object;
return proxy.get();
}
else {
return null;
}
}
public class Filter extends ItemsFilter {
boolean members = includeMembers;
boolean filterDeprecated = excludeDeprecated;
boolean filterJDK = excludeJDK;
boolean filterOracleJDK = excludeOracleJDK;
int version = filterVersion;
@Override
public boolean matchItem(Object item) {
Declaration declaration = toDeclaration(item);
Unit unit = declaration.getUnit();
Module module = unit.getPackage().getModule();
String moduleName = module.getNameAsString();
if (filterJDK &&
isJDKModule(moduleName) ||
filterOracleJDK &&
isOracleJDKModule(moduleName) ||
filterDeprecated &&
declaration.isDeprecated()) {
return false;
}
String pattern = getPattern();
int loc = pattern.indexOf('.');
if (loc<0) {
String name = declaration.getName();
if (name==null) {
return false;
}
else if (pattern.contains("*")) {
return isMatchingGlob(pattern, name);
}
else {
return isNameMatching(pattern, name);
}
}
else {
if (declaration.isClassOrInterfaceMember()) {
String typePattern =
pattern.substring(0,loc);
String memberPattern =
pattern.substring(loc+1);
Declaration type =
(Declaration)
declaration.getContainer();
return isNameMatching(memberPattern,
declaration) &&
isNameMatching(typePattern, type);
}
else {
return false;
}
}
}
@Override
public boolean isConsistentItem(Object item) {
return true;
}
private boolean isCompatibleFilter(
ItemsFilter itemsFilter) {
if (itemsFilter instanceof Filter) {
Filter filter = (Filter) itemsFilter;
return members==filter.members &&
version==filter.version;
}
else {
return false;
}
}
@Override
public boolean equalsFilter(ItemsFilter filter) {
return isCompatibleFilter(filter) &&
filter.getPattern()
.equals(getPattern());
}
@Override
public boolean isSubFilter(ItemsFilter filter) {
if (!isCompatibleFilter(filter)) {
return false;
}
else {
String pattern = getPattern();
String filterPattern = filter.getPattern();
int loc = pattern.indexOf('.');
int filterLoc = filterPattern.indexOf('.');
if (loc<0) {
return filterLoc<0 &&
filterPattern.startsWith(pattern);
}
else if (filterLoc>=0) {
String memberPattern =
pattern.substring(loc+1);
String typePattern =
pattern.substring(0,loc);
String filterMemberPattern =
filterPattern.substring(filterLoc+1);
String filterTypePattern =
filterPattern.substring(0,filterLoc);
return
filterMemberPattern
.startsWith(memberPattern) &&
filterTypePattern
.startsWith(typePattern);
}
else {
return false;
}
}
}
}
static abstract class BaseLabelProvider
implements IBaseLabelProvider {
@Override
public void removeListener(
ILabelProviderListener listener) {}
@Override
public boolean isLabelProperty(
Object element, String property) {
return false;
}
@Override
public void dispose() {}
@Override
public void addListener(
ILabelProviderListener listener) {}
}
class SelectionLabelDecorator
extends BaseLabelProvider
implements ILabelDecorator {
@Override
public String decorateText(String text, Object element) {
if (showSelectionPackage || showSelectionModule) {
Declaration dec =
toDeclaration(element);
if (dec!=null &&
!nameOccursMultipleTimes(dec)) {
try {
StringBuilder sb =
new StringBuilder(text);
if (showSelectionPackage) {
sb.append(" \u2014 ")
.append(getPackageLabel(dec));
}
if (showSelectionModule) {
sb.append(" \u2014 ")
.append(getModule(dec));
}
return sb.toString();
}
catch (Exception e) {
System.err.println(dec.getName());
e.printStackTrace();
}
}
}
return text;
}
@Override
public Image decorateImage(Image image,
Object element) {
return null;
}
}
static class DetailsLabelProvider
extends BaseLabelProvider
implements ILabelProvider {
@Override
public String getText(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
try {
return getPackageLabel(dec);
/*+ " \u2014 " + getLocation(dwp)*/
}
catch (Exception e) {
System.err.println(dec.getName());
e.printStackTrace();
return "";
}
}
else if (element instanceof String) {
return (String) element;
}
else {
return "";
}
}
@Override
public Image getImage(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
return CeylonResources.PACKAGE;
}
else {
return null;
}
}
}
static class MoreDetailsLabelProvider
extends BaseLabelProvider
implements ILabelProvider {
@Override
public String getText(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
try {
return getModuleLabel(dec);
/* + " \u2014 " + getLocation(dwp)*/
}
catch (Exception e) {
System.err.println(dec.getName());
e.printStackTrace();
return "";
}
}
else if (element instanceof String) {
return (String) element;
}
else {
return "";
}
}
@Override
public Image getImage(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
return CeylonResources.MODULE;
}
else {
return null;
}
}
}
static class EvenMoreDetailsLabelProvider
extends BaseLabelProvider
implements ILabelProvider {
@Override
public String getText(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
try {
return getLocation(dec);
}
catch (Exception e) {
System.err.println(dec.getName());
e.printStackTrace();
return "";
}
}
else if (element instanceof String) {
return (String) element;
}
else {
return "";
}
}
@Override
public Image getImage(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
return getLocationImage(dec);
}
else {
return null;
}
}
}
private StyledString label(Declaration dec) {
IPreferenceStore prefs = getPreferences();
StyledString label =
getQualifiedDescriptionFor(dec,
prefs.getBoolean(TYPE_PARAMS_IN_DIALOGS),
prefs.getBoolean(PARAMS_IN_DIALOGS),
prefs.getBoolean(PARAM_TYPES_IN_DIALOGS),
prefs.getBoolean(RETURN_TYPES_IN_DIALOGS),
getPatternControl().getText(),
getOpenDialogFont());
if (nameOccursMultipleTimes(dec)) {
label.append(" \u2014 ", PACKAGE_STYLER)
.append(getPackageLabel(dec), PACKAGE_STYLER)
.append(" \u2014 ", COUNTER_STYLER)
.append(getModule(dec), COUNTER_STYLER);
}
return label;
}
class LabelProvider
extends StyledCellLabelProvider
implements IStyledLabelProvider,
ILabelProvider {
@Override
public boolean isLabelProperty(Object element,
String property) {
return false;
}
@Override
public Image getImage(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
try {
return getImageForDeclaration(dec);
}
catch (Exception e) {
System.err.println(dec.getName());
e.printStackTrace();
return null;
}
}
else {
return null;
}
}
@Override
public String getText(Object element) {
return getStyledText(element).getString();
}
@Override
public StyledString getStyledText(Object element) {
Declaration dec = toDeclaration(element);
if (dec!=null) {
try {
return label(dec);
}
catch (Exception e) {
System.err.println(dec.getName());
e.printStackTrace();
return new StyledString(dec.getName());
}
}
else {
return new StyledString();
}
}
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
if (element instanceof DeclarationProxy) {
StyledString styledText =
getStyledText(element);
cell.setText(styledText.toString());
cell.setStyleRanges(styledText.getStyleRanges());
cell.setImage(getImage(element));
}
else {
cell.setStyleRanges(new StyleRange[0]);
}
super.update(cell);
}
}
private class TypeSelectionHistory extends SelectionHistory {
protected DeclarationProxy restoreItemFromMemento(
IMemento element) {
String qualifiedName =
element.getString("qualifiedName");
String unitFileName =
element.getString("unitFileName");
String packageName =
element.getString("packageName");
String projectName =
element.getString("projectName");
if (projectName!=null) {
for (IProject project: getProjects()) {
if (project.getName().equals(projectName)) {
//search for a source file in the project
for (PhasedUnit phasedUnit:
getUnits(project)) {
String filename =
phasedUnit.getUnit()
.getFilename();
String pname =
phasedUnit.getPackage()
.getQualifiedNameString();
if (filename.equals(unitFileName) &&
pname.equals(packageName)) {
for (Declaration dec:
phasedUnit.getDeclarations()) {
try {
if (isPresentable(dec)) {
String qname =
dec.getQualifiedNameString();
if (qualifiedName.equals(qname)) {
return isFiltered(dec) ? null :
new DeclarationProxy(dec);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
for (IProject project: getProjects()) {
//for archives, search all dependent modules
//this will find declarations in source archives
Modules modules =
getProjectTypeChecker(project)
.getContext()
.getModules();
for (Module module: modules.getListOfModules()) {
Package pkg =
module.getDirectPackage(packageName);
if (pkg!=null) {
for (Unit unit: pkg.getUnits()) {
if (unit.getFilename().equals(unitFileName)) {
for (Declaration dec: unit.getDeclarations()) {
if (isPresentable(dec)) {
String qname =
dec.getQualifiedNameString();
if (qualifiedName.equals(qname)) {
return isFiltered(dec) ? null :
new DeclarationProxy(dec);
}
else if (qualifiedName.startsWith(qname+ '.')) {
for (Declaration mem: dec.getMembers()) {
if (isPresentable(mem)) {
String mqname =
mem.getQualifiedNameString();
if (qualifiedName.equals(mqname)) {
return isFiltered(dec) ? null :
new DeclarationProxy(mem);
}
}
}
}
}
}
}
}
}
}
}
return null;
}
protected void storeItemToMemento(Object item,
IMemento element) {
Declaration dec = toDeclaration(item);
Unit unit = dec.getUnit();
element.putString("qualifiedName",
dec.getQualifiedNameString());
element.putString("unitFileName",
unit.getFilename());
element.putString("packageName",
unit.getPackage()
.getQualifiedNameString());
if (unit instanceof EditedSourceFile ||
unit instanceof ProjectSourceFile ||
unit instanceof CrossProjectSourceFile ||
//TODO: is this correct:
unit instanceof JavaCompilationUnit) {
IResourceAware projectSourceFile =
(IResourceAware) unit;
element.putString("projectName",
projectSourceFile.getResourceProject()
.getName());
}
}
}
public OpenDeclarationDialog(boolean multi, boolean history,
Shell shell, String title,
String filterLabelText, String listLabelText) {
super(shell, multi, filterLabelText, listLabelText);
setTitle(title);
initLabelProviders(new LabelProvider(),
new SelectionLabelDecorator(),
new DetailsLabelProvider(),
new MoreDetailsLabelProvider(),
new EvenMoreDetailsLabelProvider());
if (history) {
setSelectionHistory(new TypeSelectionHistory());
}
}
@Override
protected IDialogSettings getDialogSettings() {
IDialogSettings settings =
CeylonPlugin.getInstance()
.getDialogSettings();
IDialogSettings section =
settings.getSection(SETTINGS_ID);
if (section == null) {
section = settings.addNewSection(SETTINGS_ID);
}
return section;
}
@Override
protected IStatus validateItem(Object item) {
return Status.OK_STATUS;
}
@Override
protected ItemsFilter createFilter() {
return new Filter();
}
@Override
protected Comparator<Object> getItemsComparator() {
return new Comparator<Object>() {
@Override
public int compare(Object x, Object y) {
return compareDeclarations(toDeclaration(x),
toDeclaration(y));
}
private int compareDeclarations(Declaration p,
Declaration q) {
int result = p.getName().compareTo(q.getName());
if (result!=0) {
return result;
}
else if (p.isClassOrInterfaceMember() &&
!q.isClassOrInterfaceMember()) {
return 1;
}
else if (!p.isClassOrInterfaceMember() &&
q.isClassOrInterfaceMember()) {
return -1;
}
else if (p.isClassOrInterfaceMember() &&
q.isClassOrInterfaceMember()) {
return compareDeclarations(
(Declaration) p.getContainer(),
(Declaration) q.getContainer());
}
else {
return 0;
}
}
};
}
Map<String,Integer> usedNames =
new HashMap<String,Integer>();
@Override
protected void fillContentProvider(
AbstractContentProvider contentProvider,
ItemsFilter itemsFilter,
IProgressMonitor monitor)
throws CoreException {
usedNames.clear();
monitor.beginTask("Filtering", estimateWork(monitor));
Set<String> searchedArchives = new HashSet<String>();
Collection<IProject> projectsToSearch = getProjects();
for (IProject project: projectsToSearch) {
TypeChecker typeChecker =
getProjectTypeChecker(project);
fill(contentProvider, itemsFilter,
typeChecker.getPhasedUnits()
.getPhasedUnits());
monitor.worked(1);
if (monitor.isCanceled()) break;
Modules modules =
typeChecker.getContext().getModules();
for (Module m: modules.getListOfModules()) {
if (m instanceof JDTModule &&
!filters.isFiltered(m)) {
JDTModule module = (JDTModule) m;
IProject originalProject =
module.getOriginalProject();
if (originalProject != null
&& projectsToSearch.contains(
originalProject)) {
continue;
}
String moduleName =
module.getNameAsString();
if (module.isAvailable() &&
(!excludeJDK ||
!isJDKModule(moduleName)) &&
(!excludeOracleJDK ||
!isOracleJDKModule(moduleName)) &&
searchedArchives.add(
uniqueIdentifier(module))) {
fill(contentProvider, itemsFilter,
module, monitor);
monitor.worked(1);
if (monitor.isCanceled()) break;
}
}
}
}
monitor.done();
}
private void fill(AbstractContentProvider contentProvider,
ItemsFilter itemsFilter, JDTModule module,
IProgressMonitor monitor) {
ArrayList<Package> copiedPackages =
new ArrayList<Package>(module.getPackages());
for (Package pack: copiedPackages) {
if (!filters.isFiltered(pack)) {
for (Declaration dec: pack.getMembers()) {
fillDeclarationAndMembers(contentProvider,
itemsFilter, module, dec);
}
}
monitor.worked(1);
if (monitor.isCanceled()) break;
}
}
protected static class DeclarationProxy
extends ModelProxy {
private String location;
public DeclarationProxy(Declaration declaration) {
super(declaration);
location = getLocation(declaration);
}
@Override
public boolean equals(Object obj) {
if (this==obj) {
return true;
}
else if (obj instanceof DeclarationProxy) {
DeclarationProxy that =
(DeclarationProxy) obj;
if (super.equals(that)) {
return location==that.location ||
location!=null &&
that.location!=null &&
location.equals(that.location);
}
else {
return false;
}
}
else {
return false;
}
}
@Override
public int hashCode() {
return super.hashCode() + location.hashCode();
}
}
private void fillDeclarationAndMembers(
AbstractContentProvider contentProvider,
ItemsFilter itemsFilter,
JDTModule module, Declaration dec) {
if (includeDeclaration(module, dec) &&
//watch out for dupes!
(!module.isProjectModule() ||
!dec.getUnit()
.getFilename()
.endsWith(".ceylon"))) {
contentProvider.add(new DeclarationProxy(dec),
itemsFilter);
nameOccurs(dec);
if (includeMembers &&
dec instanceof ClassOrInterface) {
try {
ArrayList<Declaration> copiedMembers =
new ArrayList<Declaration>
(dec.getMembers());
for (Declaration member: copiedMembers) {
fillDeclarationAndMembers(
contentProvider,
itemsFilter,
module, member);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void fill(
AbstractContentProvider contentProvider,
ItemsFilter itemsFilter,
List<? extends PhasedUnit> units) {
for (PhasedUnit unit: units) {
JDTModule jdtModule = (JDTModule)
unit.getPackage().getModule();
for (Declaration dec: unit.getDeclarations()) {
if (includeDeclaration(jdtModule, dec)) {
contentProvider.add(
new DeclarationProxy(dec),
itemsFilter);
nameOccurs(dec);
}
}
}
}
protected String getFilterListAsString(String preference) {
return getPreferences().getString(preference);
}
private Filters filters = new Filters() {
@Override
protected String getFilterListAsString(String preference) {
return OpenDeclarationDialog.this
.getFilterListAsString(preference);
}
};
private boolean isFiltered(Declaration declaration) {
if (excludeDeprecated &&
declaration.isDeprecated()) {
return true;
}
return filters.isFiltered(declaration);
}
private boolean includeDeclaration(JDTModule module,
Declaration dec) {
try {
boolean visibleFromSourceModules;
if (dec.isToplevel()) {
visibleFromSourceModules =
dec.isShared() ||
module.isProjectModule();
}
else {
visibleFromSourceModules =
includeMembers && dec.isShared();
}
return visibleFromSourceModules &&
isPresentable(dec) &&
!isFiltered(dec);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
private int estimateWork(IProgressMonitor monitor) {
int work = 0;
Set<String> searchedArchives =
new HashSet<String>();
for (IProject project: getProjects()) {
work++;
Modules modules =
getProjectTypeChecker(project)
.getContext()
.getModules();
for (Module m: modules.getListOfModules()) {
if (m instanceof JDTModule &&
!filters.isFiltered(m)) {
JDTModule module = (JDTModule) m;
String moduleName =
module.getNameAsString();
if (module.isAvailable() &&
(!excludeJDK ||
!isJDKModule(moduleName)) &&
(!excludeOracleJDK ||
!isOracleJDKModule(moduleName)) &&
searchedArchives.add(
uniqueIdentifier(module))) {
work += 1 + m.getPackages().size();
}
}
}
}
return work;
}
private String uniqueIdentifier(JDTModule module) {
return module.getArtifact()==null ?
module.getNameAsString() +
'#' + module.getVersion() :
new File(module.getSourceArchivePath())
.getAbsolutePath();
}
private static String getModule(Declaration dec) {
Module module = dec.getUnit()
.getPackage().getModule();
StringBuilder sb = new StringBuilder();
sb.append(module.getNameAsString());
if (module.getVersion()!=null) {
sb.append(" \"")
.append(module.getVersion())
.append("\"");
}
return sb.toString();
}
private static Image getLocationImage(Declaration dwp) {
Module module =
dwp.getUnit().getPackage().getModule();
if (module instanceof JDTModule) {
JDTModule m = (JDTModule) module;
if (m.isProjectModule()) {
// IProject project = dwp.getProject();
// if (project.isOpen()) {
return CeylonResources.FILE;
// else {
// return CeylonResources.PROJECT;
}
else {
return CeylonResources.REPO;
}
}
else {
return null;
}
}
private static String repositoryPath =
CeylonPlugin.getInstance()
.getCeylonRepository()
.getPath();
private static String getLocation(Declaration declaration) {
Unit unit = declaration.getUnit();
Module module = unit.getPackage().getModule();
if (module instanceof JDTModule) {
if (unit instanceof EditedSourceFile ||
unit instanceof ProjectSourceFile ||
unit instanceof CrossProjectSourceFile ||
//TODO: is this correct:
unit instanceof JavaCompilationUnit) {
IResourceAware sourceFile =
(IResourceAware) unit;
return sourceFile.getResourceFile()
.getFullPath()
.toPortableString();
}
else {
JDTModule mod = (JDTModule) module;
String displayString =
mod.getRepositoryDisplayString();
if (repositoryPath.equals(displayString)) {
displayString = "IDE System Modules";
}
return displayString;
}
}
else {
return null;
}
}
private String toName(Declaration dec) {
String name = dec.getName();
if (dec.isClassOrInterfaceMember()) {
Declaration type =
(Declaration) dec.getContainer();
name = type.getName() + "." + name;
}
return name;
}
private boolean nameOccursMultipleTimes(Declaration dec) {
Integer n = usedNames.get(toName(dec));
return n!=null && n>1;
}
private void nameOccurs(Declaration dec) {
String name = toName(dec);
Integer i = usedNames.get(name);
if (i==null) i=0;
usedNames.put(name, i+1);
}
static boolean isPresentable(Declaration d) {
String name = d.getName();
return name!=null &&
!d.isAnonymous() &&
!isOverloadedVersion(d);
}
@Override
public String getElementName(Object item) {
return toDeclaration(item).getQualifiedNameString();
}
@Override
protected void fillViewMenu(IMenuManager menuManager) {
// toggleMembersAction = new ToggleMembersAction();
// toggleMembersAction.setChecked(includeMembers);
// menuManager.add(toggleMembersAction);
toggleExcludeDeprecatedAction =
new ToggleExcludeDeprecatedAction();
toggleExcludeDeprecatedAction.setChecked(
excludeDeprecated);
menuManager.add(toggleExcludeDeprecatedAction);
toggleExcludeJDKAction =
new ToggleExcludeJDKAction();
toggleExcludeJDKAction.setChecked(excludeJDK);
menuManager.add(toggleExcludeJDKAction);
toggleExcludeOracleJDKAction =
new ToggleExcludeOracleJDKAction();
toggleExcludeOracleJDKAction.setChecked(
excludeOracleJDK);
menuManager.add(toggleExcludeOracleJDKAction);
menuManager.add(new Separator());
super.fillViewMenu(menuManager);
togglePackageAction = new TogglePackageAction();
toggleModuleAction = new ToggleModuleAction();
menuManager.add(togglePackageAction);
menuManager.add(toggleModuleAction);
menuManager.add(new Separator());
Action configureAction =
new Action("Configure Filters and Labels...",
CeylonPlugin.imageRegistry()
.getDescriptor(CONFIG_LABELS)) {
@Override
public void run() {
createPreferenceDialogOn(getShell(),
CeylonOpenDialogsPreferencePage.ID,
new String[] {
CeylonOpenDialogsPreferencePage.ID,
CeylonPlugin.COLORS_AND_FONTS_PAGE_ID,
CeylonFiltersPreferencePage.ID
},
null).open();
filters.initFilters();
filterVersion++;
applyFilter();
}
};
menuManager.add(configureAction);
}
@Override
protected void refreshBrowserContent(DocBrowser browser,
Object[] selection) {
if (browser.isVisible()) {
try {
if (selection!=null &&
selection.length==1 &&
selection[0] instanceof DeclarationProxy) {
browser.setText(getDocumentationFor(null,
toDeclaration(selection[0])));
}
else {
if (emptyDoc==null) {
StringBuilder buffer =
new StringBuilder();
insertPageProlog(buffer, 0,
HTML.getStyleSheet());
buffer.append("<i>Select a declaration to see its documentation here.</i>");
addPageEpilog(buffer);
emptyDoc = buffer.toString();
}
browser.setText(emptyDoc);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean isMatchingGlob(
String filter, String name) {
if (name==null) {
return false;
}
int loc = 0;
boolean first = true;
for (String subfilter: filter.split("\\*")) {
int match = name.toLowerCase()
.indexOf(subfilter.toLowerCase(), loc);
if (match<0 || first && match>0) {
return false;
}
loc += match + subfilter.length();
first = false;
}
return true;
}
/*@Override
protected void createToolBar(ToolBar toolBar) {
super.createToolBar(toolBar);
toggleMembersToolItem = new ToolItem(toolBar, SWT.CHECK, 0);
toggleMembersToolItem.setImage(MEMBERS_IMAGE);
toggleMembersToolItem.setToolTipText("Show/Hide Members");
toggleMembersToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
includeMembers=!includeMembers;
applyFilter();
if (toggleMembersAction!=null) {
toggleMembersAction.setChecked(includeMembers);
}
}
});
}*/
@Override
void handleLink(String location, DocBrowser browser) {
Referenceable target = null;
CeylonEditor editor = null;
IEditorPart currentEditor = getCurrentEditor();
if (currentEditor instanceof CeylonEditor) {
editor = (CeylonEditor) currentEditor;
target = getLinkedModel(location, editor);
/*if (location.startsWith("ref:")) {
new FindReferencesAction(editor,
(Declaration) target).run();
close();
return;
}
else if (location.startsWith("sub:")) {
new FindSubtypesAction(editor,
(Declaration) target).run();
close();
return;
}
else if (location.startsWith("act:")) {
new FindRefinementsAction(editor,
(Declaration) target).run();
close();
return;
}
else if (location.startsWith("ass:")) {
new FindAssignmentsAction(editor,
(Declaration) target).run();
close();
return;
}*/
}
if (location.startsWith("doc:")) {
if (target==null) {
target = getLinkedModel(location);
}
if (target instanceof Declaration) {
String text =
getDocumentationFor(null,
(Declaration) target);
if (text!=null) browser.setText(text);
}
if (target instanceof Package) {
String text =
getDocumentationFor(null,
(Package) target);
if (text!=null) browser.setText(text);
}
if (target instanceof Module) {
String text =
getDocumentationFor(null,
(Module) target);
if (text!=null) browser.setText(text);
}
}
if (location.startsWith("dec:")) {
if (target==null) {
target = getLinkedModel(location);
}
if (target!=null) {
gotoDeclaration(target);
close();
return;
}
}
}
@Override
public Declaration[] getResult() {
Object[] proxies = super.getResult();
if (proxies==null) {
return null;
}
else {
Declaration[] declarations =
new Declaration[proxies.length];
for (int i=0; i<proxies.length; i++) {
declarations[i] = toDeclaration(proxies[i]);
}
return declarations;
}
}
}
|
package nl.mvdr.tinustris.gui;
import javafx.scene.shape.Box;
import javafx.scene.shape.Rectangle;
import lombok.extern.slf4j.Slf4j;
import nl.mvdr.tinustris.model.Block;
import org.junit.Test;
/**
* Test class for {@link BlockStyle}.
*
* @author Martijn van de Rijdt
*/
@Slf4j
public class BlockStyleTest {
/** Tests {@link BlockStyle#apply(Rectangle, Block)} for all possible styles and tetrominoes. */
@Test
public void testApplyRectangle() {
Rectangle rectangle = new Rectangle(10, 10);
for (BlockStyle style: BlockStyle.values()) {
for (Block block: Block.values()) {
log.info("Applying style {} for block {}.", style, block);
style.apply(rectangle, block, 25, 0);
}
}
}
/** Tests {@link BlockStyle#apply(Rectangle, Block)} for a null tetromino value. */
@Test(expected = NullPointerException.class)
public void testApplyNullTetrominoRectangle() {
Rectangle rectangle = new Rectangle(10, 10);
BlockStyle.ACTIVE.apply(rectangle, null, 25, 0);
}
/** Tests {@link BlockStyle#apply(Rectangle, Block)} for a null rectangle value. */
@Test(expected = NullPointerException.class)
public void testApplyNullRectangleRectangle() {
BlockStyle.ACTIVE.apply((Rectangle)null, Block.I, 25, 0);
}
/** Tests {@link BlockStyle#apply(Box, Block)} for all possible styles and tetrominoes. */
@Test
public void testApplyBox() {
Box box = new Box();
for (BlockStyle style: BlockStyle.values()) {
for (Block block: Block.values()) {
log.info("Applying style {} for block {}.", style, block);
style.apply(box, block, 25, 0);
}
}
}
/** Tests {@link BlockStyle#apply(Box, Block)} for a null tetromino value. */
@Test(expected = NullPointerException.class)
public void testApplyNullTetrominoBox() {
Box box = new Box();
BlockStyle.ACTIVE.apply(box, null, 25, 0);
}
/** Tests {@link BlockStyle#apply(Box, Block)} for a null rectangle value. */
@Test(expected = NullPointerException.class)
public void testApplyNullRectangleBox() {
BlockStyle.ACTIVE.apply((Box)null, Block.I, 25, 0);
}
}
|
package org.eclipse.xtext.junit4.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.xtext.ISetup;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.junit4.util.ResourceLoadHelper;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextSourceViewer;
import org.eclipse.xtext.ui.editor.XtextSourceViewerConfiguration;
import org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ui.editor.contentassist.ReplacementTextApplier;
import org.eclipse.xtext.ui.editor.model.DocumentPartitioner;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.util.StringInputStream;
import org.eclipse.xtext.util.Strings;
import org.junit.Assert;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
* Represents a builder for <code>IContentAssistProcessor</code> tests.
*
* @author Michael Clay - Initial contribution and API
* @author Sven Efftinge
* @author Sebastian Zarnekow
*/
public class ContentAssistProcessorTestBuilder implements Cloneable {
private String model;
private int cursorPosition;
private Injector injector;
private final ResourceLoadHelper loadHelper;
public static class Factory {
private Injector injector;
@Inject
public Factory(Injector injector) {
this.injector = injector;
}
public ContentAssistProcessorTestBuilder create(ResourceLoadHelper resourceLoadHelper) throws Exception {
return new ContentAssistProcessorTestBuilder(this.injector,resourceLoadHelper);
}
}
public ContentAssistProcessorTestBuilder(ISetup setupClazz, AbstractXtextTests tests) throws Exception {
tests.with(setupClazz);
injector = tests.getInjector();
this.loadHelper = tests;
}
public ContentAssistProcessorTestBuilder(Injector injector, ResourceLoadHelper helper) throws Exception {
this.injector = injector;
this.loadHelper = helper;
}
public ContentAssistProcessorTestBuilder reset() throws Exception {
return clone("",0);
}
public ContentAssistProcessorTestBuilder append(String model) throws Exception {
return clone(getModel()+model, cursorPosition+model.length());
}
public ContentAssistProcessorTestBuilder appendNl(String model) throws Exception {
return append(model).append(Strings.newLine());
}
public ContentAssistProcessorTestBuilder insert(String model, int cursorPosition) throws Exception {
StringBuilder builder = new StringBuilder(getModel()).insert(cursorPosition, model);
return clone(builder.toString(), cursorPosition + model.length());
}
public ContentAssistProcessorTestBuilder cursorBack(int times) throws Exception {
return clone(model,this.cursorPosition -= times);
}
public ContentAssistProcessorTestBuilder applyText() throws Exception {
return applyText(0, true);
}
public ContentAssistProcessorTestBuilder applyText(boolean appendSpace) throws Exception {
return applyText(0, appendSpace);
}
public ContentAssistProcessorTestBuilder applyText(int index, boolean appendSpace) throws Exception {
ICompletionProposal proposal = computeCompletionProposals(getModel(), this.cursorPosition)[index];
String text = proposal.getDisplayString();
if (proposal instanceof ConfigurableCompletionProposal) {
text = ((ConfigurableCompletionProposal) proposal).getReplacementString();
}
ContentAssistProcessorTestBuilder ret = append(text);
if (appendSpace) {
return ret.append(" ");
}
return ret;
}
public ContentAssistProcessorTestBuilder assertCount(int completionProposalCount) throws Exception {
return assertCountAtCursorPosition(completionProposalCount, this.cursorPosition);
}
public ContentAssistProcessorTestBuilder assertText(String... expectedText) throws Exception {
return assertTextAtCursorPosition(this.cursorPosition, expectedText);
}
public ContentAssistProcessorTestBuilder assertTextAtCursorPosition(
String cursorPosition, String... expectedText) throws Exception {
return assertTextAtCursorPosition(getModel().indexOf(cursorPosition), expectedText);
}
public ContentAssistProcessorTestBuilder assertTextAtCursorPosition(
String cursorPosition, int offset, String... expectedText) throws Exception {
return assertTextAtCursorPosition(getModel().indexOf(cursorPosition) + offset, expectedText);
}
public ContentAssistProcessorTestBuilder assertTextAtCursorPosition(int cursorPosition, String... expectedText)
throws Exception {
String currentModelToParse = getModel();
ICompletionProposal[] computeCompletionProposals = computeCompletionProposals(currentModelToParse,
cursorPosition);
if (computeCompletionProposals == null)
computeCompletionProposals = new ICompletionProposal[0];
Arrays.sort(expectedText);
final String expectation = Strings.concat(", ", Arrays.asList(expectedText));
final String actual = Strings.concat(", ", toString(computeCompletionProposals));
Assert.assertEquals(expectation, actual);
for (int i = 0; i < computeCompletionProposals.length; i++) {
ICompletionProposal completionProposal = computeCompletionProposals[i];
String proposedText = completionProposal.getDisplayString();
if (completionProposal instanceof ConfigurableCompletionProposal) {
ConfigurableCompletionProposal configurableProposal = (ConfigurableCompletionProposal) completionProposal;
proposedText = configurableProposal.getReplacementString();
if (configurableProposal.getTextApplier() instanceof ReplacementTextApplier) {
proposedText = ((ReplacementTextApplier) configurableProposal.getTextApplier()).getActualReplacementString(configurableProposal);
}
}
Assert.assertTrue("Missing proposal '" + proposedText + "'. Expect completionProposal text '" + expectation + "', but got " +
actual,
Arrays.asList(expectedText).contains(proposedText));
}
return this;
}
public ContentAssistProcessorTestBuilder assertMatchString(String matchString)
throws Exception {
String currentModelToParse = getModel();
final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
Shell shell = new Shell();
try {
ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
String contentType = xtextDocument.getContentType(currentModelToParse.length());
if (contentAssistant.getContentAssistProcessor(contentType) != null) {
ContentAssistContext.Factory factory = get(ContentAssistContext.Factory.class);
ContentAssistContext[] contexts = factory.create(sourceViewer, currentModelToParse.length(), xtextResource);
for(ContentAssistContext context: contexts) {
Assert.assertTrue("matchString = '" + matchString + "', actual: '" + context.getPrefix() + "'",
"".equals(context.getPrefix()) || matchString.equals(context.getPrefix()));
}
} else {
Assert.fail("No content assistant for content type " + contentType);
}
return this;
} finally {
shell.dispose();
}
}
protected String getModel() {
return this.model == null ? "":model;
}
public List<String> toString(ICompletionProposal[] proposals) {
if (proposals == null)
return Collections.emptyList();
List<String> res = new ArrayList<String>(proposals.length);
for (ICompletionProposal proposal : proposals) {
String proposedText = proposal.getDisplayString();
if (proposal instanceof ConfigurableCompletionProposal) {
ConfigurableCompletionProposal configurableProposal = (ConfigurableCompletionProposal) proposal;
proposedText = configurableProposal.getReplacementString();
if (configurableProposal.getTextApplier() instanceof ReplacementTextApplier)
proposedText = ((ReplacementTextApplier) configurableProposal.getTextApplier()).getActualReplacementString(configurableProposal);
}
res.add(proposedText);
}
Collections.sort(res);
return res;
}
public ContentAssistProcessorTestBuilder assertCountAtCursorPosition(int completionProposalCount, int cursorPosition)
throws Exception {
String currentModelToParse = getModel();
ICompletionProposal[] computeCompletionProposals = computeCompletionProposals(currentModelToParse,
cursorPosition);
StringBuffer computedProposals = new StringBuffer();
for (int i = 0; i < computeCompletionProposals.length; i++) {
computedProposals.append(computeCompletionProposals[i].getDisplayString());
if (i<(computeCompletionProposals.length-1)) {
computedProposals.append(",");
}
}
Assert.assertEquals("expect only " + completionProposalCount + " CompletionProposal item for model '"
+ currentModelToParse + "' but got '"+computedProposals+"'", completionProposalCount, computeCompletionProposals.length);
return this;
}
public ICompletionProposal[] computeCompletionProposals(final String currentModelToParse, int cursorPosition)
throws Exception {
final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
Shell shell = new Shell();
try {
ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
String contentType = xtextDocument.getContentType(cursorPosition);
IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(contentType);
if (processor != null) {
return processor.computeCompletionProposals(sourceViewer, cursorPosition);
}
return new ICompletionProposal[0];
} finally {
shell.dispose();
}
}
protected ISourceViewer getSourceViewer(Shell shell, final IXtextDocument xtextDocument,
XtextSourceViewerConfiguration configuration) {
XtextSourceViewer.Factory factory = get(XtextSourceViewer.Factory.class);
ISourceViewer sourceViewer = factory.createSourceViewer(shell, null, null, false, 0);
sourceViewer.configure(configuration);
sourceViewer.setDocument(xtextDocument);
return sourceViewer;
}
public ICompletionProposal[] computeCompletionProposals(int cursorPosition) throws Exception {
return computeCompletionProposals(getModel(), cursorPosition);
}
public ICompletionProposal[] computeCompletionProposals(String cursorPosition) throws Exception {
return computeCompletionProposals(getModel(), getModel().indexOf(cursorPosition));
}
public ICompletionProposal[] computeCompletionProposals() throws Exception {
return computeCompletionProposals(getModel(), cursorPosition);
}
@Override
public String toString() {
return getModel() + "\n length: " + getModel().length() + "\n cursor at: "
+ this.cursorPosition;
}
public IXtextDocument getDocument(final XtextResource xtextResource, final String model) {
XtextDocument document = get(XtextDocument.class);
document.set(model);
document.setInput(xtextResource);
DocumentPartitioner partitioner = get(DocumentPartitioner.class);
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
return document;
}
public ITextViewer getSourceViewer(final String currentModelToParse, final IXtextDocument xtextDocument) {
ITextViewer result = new MockableTextViewer() {
@Override
public IDocument getDocument() {
return xtextDocument;
}
@Override
public ISelectionProvider getSelectionProvider() {
return new MockableSelectionProvider() {
@Override
public ISelection getSelection() {
return TextSelection.emptySelection();
}
};
}
@Override
public StyledText getTextWidget() {
return null;
}
};
return result;
}
protected ContentAssistProcessorTestBuilder clone(String model, int offset) throws Exception {
ContentAssistProcessorTestBuilder builder = (ContentAssistProcessorTestBuilder) clone();
builder.model = model;
builder.cursorPosition = offset;
return builder;
}
public <T> T get(Class<T> clazz) {
return injector.getInstance(clazz);
}
protected int getCursorPosition() {
return cursorPosition;
}
}
|
package org.jkiss.dbeaver.ui.controls.resultset;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.text.IFindReplaceTarget;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.texteditor.FindReplaceAction;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.DBeaverActivator;
import org.jkiss.dbeaver.model.data.DBDAttributeBinding;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.MultiPageAbstractEditor;
import org.jkiss.dbeaver.utils.GeneralUtils;
/**
* ResultSetCommandHandler
*/
public class ResultSetCommandHandler extends AbstractHandler {
public static final String CMD_TOGGLE_MODE = "org.jkiss.dbeaver.core.resultset.toggleMode";
public static final String CMD_SWITCH_PRESENTATION = "org.jkiss.dbeaver.core.resultset.switchPresentation";
public static final String CMD_ROW_FIRST = "org.jkiss.dbeaver.core.resultset.row.first";
public static final String CMD_ROW_PREVIOUS = "org.jkiss.dbeaver.core.resultset.row.previous";
public static final String CMD_ROW_NEXT = "org.jkiss.dbeaver.core.resultset.row.next";
public static final String CMD_ROW_LAST = "org.jkiss.dbeaver.core.resultset.row.last";
public static final String CMD_FETCH_PAGE = "org.jkiss.dbeaver.core.resultset.fetch.page";
public static final String CMD_FETCH_ALL = "org.jkiss.dbeaver.core.resultset.fetch.all";
public static final String CMD_ROW_EDIT = "org.jkiss.dbeaver.core.resultset.row.edit";
public static final String CMD_ROW_EDIT_INLINE = "org.jkiss.dbeaver.core.resultset.row.edit.inline";
public static final String CMD_ROW_ADD = "org.jkiss.dbeaver.core.resultset.row.add";
public static final String CMD_ROW_COPY = "org.jkiss.dbeaver.core.resultset.row.copy";
public static final String CMD_ROW_DELETE = "org.jkiss.dbeaver.core.resultset.row.delete";
public static final String CMD_APPLY_CHANGES = "org.jkiss.dbeaver.core.resultset.applyChanges";
public static final String CMD_REJECT_CHANGES = "org.jkiss.dbeaver.core.resultset.rejectChanges";
public static final String CMD_NAVIGATE_LINK = "org.jkiss.dbeaver.core.resultset.navigateLink";
public static ResultSetViewer getActiveResultSet(IWorkbenchPart activePart) {
//IWorkbenchPart activePart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
if (activePart instanceof IResultSetContainer) {
return ((IResultSetContainer) activePart).getResultSetViewer();
} else if (activePart instanceof MultiPageAbstractEditor) {
return getActiveResultSet(((MultiPageAbstractEditor) activePart).getActiveEditor());
}
return null;
}
@Nullable
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
final ResultSetViewer rsv = getActiveResultSet(HandlerUtil.getActivePart(event));
if (rsv == null) {
return null;
}
String actionId = event.getCommand().getId();
IResultSetPresentation presentation = rsv.getActivePresentation();
switch (actionId) {
case IWorkbenchCommandConstants.FILE_REFRESH:
rsv.refresh();
break;
case CMD_TOGGLE_MODE:
rsv.toggleMode();
break;
case CMD_SWITCH_PRESENTATION:
rsv.switchPresentation();
break;
case CMD_ROW_PREVIOUS:
case ITextEditorActionDefinitionIds.WORD_PREVIOUS:
presentation.scrollToRow(IResultSetPresentation.RowPosition.PREVIOUS);
break;
case CMD_ROW_NEXT:
case ITextEditorActionDefinitionIds.WORD_NEXT:
presentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT);
break;
case CMD_ROW_FIRST:
case ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS:
presentation.scrollToRow(IResultSetPresentation.RowPosition.FIRST);
break;
case CMD_ROW_LAST:
case ITextEditorActionDefinitionIds.SELECT_WORD_NEXT:
presentation.scrollToRow(IResultSetPresentation.RowPosition.LAST);
break;
case CMD_FETCH_PAGE:
rsv.readNextSegment();
break;
case CMD_FETCH_ALL:
rsv.readAllData();
break;
case CMD_ROW_EDIT:
if (presentation instanceof IResultSetEditor) {
((IResultSetEditor) presentation).openValueEditor(false);
}
break;
case CMD_ROW_EDIT_INLINE:
if (presentation instanceof IResultSetEditor) {
((IResultSetEditor) presentation).openValueEditor(true);
}
break;
case CMD_ROW_ADD:
rsv.addNewRow(false);
break;
case CMD_ROW_COPY:
rsv.addNewRow(true);
break;
case CMD_ROW_DELETE:
case IWorkbenchCommandConstants.EDIT_DELETE:
rsv.deleteSelectedRows();
break;
case CMD_APPLY_CHANGES:
rsv.applyChanges(null);
break;
case CMD_REJECT_CHANGES:
rsv.rejectChanges();
break;
case IWorkbenchCommandConstants.EDIT_COPY:
ResultSetUtils.copyToClipboard(
presentation.copySelectionToString(
false, false, false, null, DBDDisplayFormat.EDIT));
break;
case IWorkbenchCommandConstants.EDIT_PASTE:
if (presentation instanceof IResultSetEditor) {
((IResultSetEditor) presentation).pasteFromClipboard();
}
break;
case IWorkbenchCommandConstants.EDIT_CUT:
ResultSetUtils.copyToClipboard(
presentation.copySelectionToString(
false, false, true, null, DBDDisplayFormat.EDIT)
);
break;
case ITextEditorActionDefinitionIds.SMART_ENTER:
if (presentation instanceof IResultSetEditor) {
((IResultSetEditor) presentation).openValueEditor(false);
}
break;
case IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE:
FindReplaceAction action = new FindReplaceAction(
DBeaverActivator.getCoreResourceBundle(),
"Editor.FindReplace.",
HandlerUtil.getActiveShell(event),
rsv.getAdapter(IFindReplaceTarget.class));
action.run();
break;
case CMD_NAVIGATE_LINK:
final ResultSetRow row = rsv.getCurrentRow();
final DBDAttributeBinding attr = rsv.getActivePresentation().getCurrentAttribute();
if (row != null && attr != null) {
new AbstractJob("Navigate association") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
rsv.navigateAssociation(monitor, attr, row, false);
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
}
break;
case IWorkbenchCommandConstants.NAVIGATE_BACKWARD_HISTORY: {
final int hp = rsv.getHistoryPosition();
if (hp > 0) {
rsv.navigateHistory(hp - 1);
}
break;
}
case IWorkbenchCommandConstants.NAVIGATE_FORWARD_HISTORY: {
final int hp = rsv.getHistoryPosition();
if (hp < rsv.getHistorySize() - 1) {
rsv.navigateHistory(hp + 1);
}
break;
}
case ITextEditorActionDefinitionIds.LINE_GOTO: {
ResultSetRow currentRow = rsv.getCurrentRow();
final int rowCount = rsv.getModel().getRowCount();
if (rowCount <= 0) {
break;
}
GotoLineDialog d = new GotoLineDialog(
HandlerUtil.getActiveShell(event),
"Go to Row",
"Enter row number (1.." + rowCount + ")",
String.valueOf(currentRow == null ? 1 : currentRow.getVisualNumber() + 1),
new IInputValidator() {
@Override
public String isValid(String input) {
try {
int i = Integer.parseInt(input);
if (i <= 0 || rowCount < i) {
return "Invalid row number";
}
} catch (NumberFormatException x) {
return "Not a number";
}
return null;
}
});
if (d.open() == Window.OK) {
int line = Integer.parseInt(d.getValue());
rsv.getActivePresentation().scrollToRow(IResultSetPresentation.RowPosition.LAST);
}
System.out.println(1);
break;
}
}
return null;
}
static class GotoLineDialog extends InputDialog {
private static final String DIALOG_ID = "ResultSetCommandHandler.GotoLineDialog";
public GotoLineDialog(Shell parent, String title, String message, String initialValue, IInputValidator validator) {
super(parent, title, message, initialValue, validator);
}
protected IDialogSettings getDialogBoundsSettings() {
return UIUtils.getDialogSettings(DIALOG_ID);
}
}
}
|
package jtermios.linux;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import jtermios.FDSet;
import jtermios.JTermios;
import jtermios.Pollfd;
import jtermios.Termios;
import jtermios.TimeVal;
import jtermios.JTermios.JTermiosInterface;
import jtermios.linux.JTermiosImpl.Linux_C_lib.pollfd;
import jtermios.linux.JTermiosImpl.Linux_C_lib.serial_struct;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import static jtermios.JTermios.*;
import static jtermios.JTermios.JTermiosLogging.log;
public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface {
private static String DEVICE_DIR_PATH = "/dev/";
private static final boolean IS64B = NativeLong.SIZE == 8;
static Linux_C_lib_DirectMapping m_ClibDM = new Linux_C_lib_DirectMapping();
static Linux_C_lib m_Clib = m_ClibDM;
private final static int TIOCGSERIAL = 0x0000541E;
private final static int TIOCSSERIAL = 0x0000541F;
private final static int ASYNC_SPD_MASK = 0x00001030;
private final static int ASYNC_SPD_CUST = 0x00000030;
private final static int[] m_BaudRates = {
50, 0000001,
75, 0000002,
110, 0000003,
134, 0000004,
150, 0000005,
200, 0000006,
300, 0000007,
600, 0000010,
1200, 0000011,
1800, 0000012,
2400, 0000013,
4800, 0000014,
9600, 0000015,
19200, 0000016,
38400, 0000017,
57600, 0010001,
115200, 0010002,
230400, 0010003,
460800, 0010004,
500000, 0010005,
576000, 0010006,
921600, 0010007,
1000000, 0010010,
1152000, 0010011,
1500000, 0010012,
2000000, 0010013,
2500000, 0010014,
3000000, 0010015,
3500000, 0010016,
4000000, 0010017
};
public static class Linux_C_lib_DirectMapping implements Linux_C_lib {
native public long memcpy(int[] dst, short[] src, long n);
native public int memcpy(int[] dst, short[] src, int n);
native public int pipe(int[] fds);
native public int tcdrain(int fd);
native public void cfmakeraw(termios termios);
native public int fcntl(int fd, int cmd, int[] arg);
native public int fcntl(int fd, int cmd, int arg);
native public int ioctl(int fd, int cmd, int[] arg);
native public int ioctl(int fd, int cmd, serial_struct arg);
native public int open(String path, int flags);
native public int close(int fd);
native public int tcgetattr(int fd, termios termios);
native public int tcsetattr(int fd, int cmd, termios termios);
native public int cfsetispeed(termios termios, NativeLong i);
native public int cfsetospeed(termios termios, NativeLong i);
native public NativeLong cfgetispeed(termios termios);
native public NativeLong cfgetospeed(termios termios);
native public int write(int fd, byte[] buffer, int count);
native public int read(int fd, byte[] buffer, int count);
native public long write(int fd, byte[] buffer, long count);
native public long read(int fd, byte[] buffer, long count);
native public int select(int n, int[] read, int[] write, int[] error, timeval timeout);
native public int poll(int[] fds, int nfds, int timeout);
public int poll(pollfd[] fds, int nfds, int timeout) {
throw new IllegalArgumentException();
}
native public int tcflush(int fd, int qs);
native public void perror(String msg);
native public int tcsendbreak(int fd, int duration);
static {
try {
Native.register("c");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public interface Linux_C_lib extends com.sun.jna.Library {
public long memcpy(int[] dst, short[] src, long n);
public int memcpy(int[] dst, short[] src, int n);
public int pipe(int[] fds);
public int tcdrain(int fd);
public void cfmakeraw(termios termios);
public int fcntl(int fd, int cmd, int[] arg);
public int fcntl(int fd, int cmd, int arg);
public int ioctl(int fd, int cmd, int[] arg);
public int ioctl(int fd, int cmd, serial_struct arg);
public int open(String path, int flags);
public int close(int fd);
public int tcgetattr(int fd, termios termios);
public int tcsetattr(int fd, int cmd, termios termios);
public int cfsetispeed(termios termios, NativeLong i);
public int cfsetospeed(termios termios, NativeLong i);
public NativeLong cfgetispeed(termios termios);
public NativeLong cfgetospeed(termios termios);
public int write(int fd, byte[] buffer, int count);
public int read(int fd, byte[] buffer, int count);
public long write(int fd, byte[] buffer, long count);
public long read(int fd, byte[] buffer, long count);
public int select(int n, int[] read, int[] write, int[] error, timeval timeout);
public int poll(pollfd[] fds, int nfds, int timeout);
public int poll(int[] fds, int nfds, int timeout);
public int tcflush(int fd, int qs);
public void perror(String msg);
public int tcsendbreak(int fd, int duration);
static public class timeval extends Structure {
public NativeLong tv_sec;
public NativeLong tv_usec;
@Override
protected List getFieldOrder() {
return Arrays.asList(
"tv_sec",
"tv_usec"
);
}
public timeval(jtermios.TimeVal timeout) {
tv_sec = new NativeLong(timeout.tv_sec);
tv_usec = new NativeLong(timeout.tv_usec);
}
}
static public class pollfd extends Structure {
public int fd;
public short events;
public short revents;
@Override
protected List getFieldOrder() {
return Arrays.asList(
"fd",
"events",
"revents"
);
}
public pollfd(Pollfd pfd) {
fd = pfd.fd;
events = pfd.events;
revents = pfd.revents;
}
}
public static class serial_struct extends Structure {
public int type;
public int line;
public int port;
public int irq;
public int flags;
public int xmit_fifo_size;
public int custom_divisor;
public int baud_base;
public short close_delay;
public short io_type;
//public char io_type;
//public char reserved_char;
public int hub6;
public short closing_wait;
public short closing_wait2;
public Pointer iomem_base;
public short iomem_reg_shift;
public int port_high;
public NativeLong iomap_base;
@Override
protected List getFieldOrder() {
return Arrays.asList(
"type",
"line",
"port",
"irq",
"flags",
"xmit_fifo_size",
"custom_divisor",
"baud_base",
"close_delay",
"io_type",
//public char io_type;
//public char reserved_char;
"hub6",
"closing_wait",
"closing_wait2",
"iomem_base",
"iomem_reg_shift",
"port_high",
"iomap_base"
);
}
};
static public class termios extends Structure {
public int c_iflag;
public int c_oflag;
public int c_cflag;
public int c_lflag;
public byte c_line;
public byte[] c_cc = new byte[32];
public int c_ispeed;
public int c_ospeed;
@Override
protected List getFieldOrder() {
return Arrays.asList(
"c_iflag",
"c_oflag",
"c_cflag",
"c_lflag",
"c_line",
"c_cc",
"c_ispeed",
"c_ospeed"
);
}
public termios() {
}
public termios(jtermios.Termios t) {
c_iflag = t.c_iflag;
c_oflag = t.c_oflag;
c_cflag = t.c_cflag;
c_lflag = t.c_lflag;
System.arraycopy(t.c_cc, 0, c_cc, 0, t.c_cc.length);
c_ispeed = t.c_ispeed;
c_ospeed = t.c_ospeed;
}
public void update(jtermios.Termios t) {
t.c_iflag = c_iflag;
t.c_oflag = c_oflag;
t.c_cflag = c_cflag;
t.c_lflag = c_lflag;
System.arraycopy(c_cc, 0, t.c_cc, 0, t.c_cc.length);
t.c_ispeed = c_ispeed;
t.c_ospeed = c_ospeed;
}
}
}
static private class FDSetImpl extends FDSet {
static final int FD_SET_SIZE = 1024;
static final int NFBBITS = 32;
int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS];
public String toString() {
return String.format("%08X%08X", bits[0], bits[1]);
}
}
public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
//linux/serial.h stuff
FIONREAD = 0x541B; // Looked up manually
//fcntl.h stuff
O_RDWR = 0x00000002;
O_NONBLOCK = 0x00000800;
O_NOCTTY = 0x00000100;
O_NDELAY = 0x00000800;
F_GETFL = 0x00000003;
F_SETFL = 0x00000004;
//errno.h stuff
EAGAIN = 11;
EACCES = 13;
EEXIST = 17;
EINTR = 4;
EINVAL = 22;
EIO = 5;
EISDIR = 21;
ELOOP = 40;
EMFILE = 24;
ENAMETOOLONG = 36;
ENFILE = 23;
ENOENT = 2;
ENOSR = 63;
ENOSPC = 28;
ENOTDIR = 20;
ENXIO = 6;
EOVERFLOW = 75;
EROFS = 30;
ENOTSUP = 95;
//termios.h stuff
TIOCM_RNG = 0x00000080;
TIOCM_CAR = 0x00000040;
IGNBRK = 0x00000001;
BRKINT = 0x00000002;
PARMRK = 0x00000008;
INLCR = 0x00000040;
IGNCR = 0x00000080;
ICRNL = 0x00000100;
ECHONL = 0x00000040;
IEXTEN = 0x00008000;
CLOCAL = 0x00000800;
OPOST = 0x00000001;
VSTART = 0x00000008;
TCSANOW = 0x00000000;
VSTOP = 0x00000009;
VMIN = 0x00000006;
VTIME = 0x00000005;
VEOF = 0x00000004;
TIOCMGET = 0x00005415;
TIOCM_CTS = 0x00000020;
TIOCM_DSR = 0x00000100;
TIOCM_RI = 0x00000080;
TIOCM_CD = 0x00000040;
TIOCM_DTR = 0x00000002;
TIOCM_RTS = 0x00000004;
ICANON = 0x00000002;
ECHO = 0x00000008;
ECHOE = 0x00000010;
ISIG = 0x00000001;
TIOCMSET = 0x00005418;
IXON = 0x00000400;
IXOFF = 0x00001000;
IXANY = 0x00000800;
CRTSCTS = 0x80000000;
TCSADRAIN = 0x00000001;
INPCK = 0x00000010;
ISTRIP = 0x00000020;
CSIZE = 0x00000030;
TCIFLUSH = 0x00000000;
TCOFLUSH = 0x00000001;
TCIOFLUSH = 0x00000002;
CS5 = 0x00000000;
CS6 = 0x00000010;
CS7 = 0x00000020;
CS8 = 0x00000030;
CSTOPB = 0x00000040;
CREAD = 0x00000080;
PARENB = 0x00000100;
PARODD = 0x00000200;
B0 = 0;
B50 = 1;
B75 = 2;
B110 = 3;
B134 = 4;
B150 = 5;
B200 = 6;
B300 = 7;
B600 = 8;
B1200 = 9;
B1800 = 10;
B2400 = 11;
B4800 = 12;
B9600 = 13;
B19200 = 14;
B38400 = 15;
B57600 = 4097;
B115200 = 4098;
B230400 = 4099;
//poll.h stuff
POLLIN = 0x0001;
POLLPRI = 0x0002;
POLLOUT = 0x0004;
POLLERR = 0x0008;
POLLNVAL = 0x0020;
// these depend on the endianness off the machine
POLLIN_IN = pollMask(0, POLLIN);
POLLOUT_IN = pollMask(0, POLLOUT);
POLLIN_OUT = pollMask(1, POLLIN);
POLLOUT_OUT = pollMask(1, POLLOUT);
POLLNVAL_OUT = pollMask(1, POLLNVAL);
}
public static int pollMask(int i, short n) {
short[] s = new short[2];
int[] d = new int[1];
s[i] = n;
// the native call depends on weather this is 32 or 64 bit arc
if (IS64B)
m_ClibDM.memcpy(d, s, (long) 4);
else
m_ClibDM.memcpy(d, s, (int) 4);
return d[0];
}
public int errno() {
return Native.getLastError();
}
public void cfmakeraw(Termios termios) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
m_Clib.cfmakeraw(t);
t.update(termios);
}
public int fcntl(int fd, int cmd, int[] arg) {
return m_Clib.fcntl(fd, cmd, arg);
}
public int fcntl(int fd, int cmd, int arg) {
return m_Clib.fcntl(fd, cmd, arg);
}
public int tcdrain(int fd) {
return m_Clib.tcdrain(fd);
}
public int cfgetispeed(Termios termios) {
return m_Clib.cfgetispeed(new Linux_C_lib.termios(termios)).intValue();
}
public int cfgetospeed(Termios termios) {
return m_Clib.cfgetospeed(new Linux_C_lib.termios(termios)).intValue();
}
public int cfsetispeed(Termios termios, int speed) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
int ret = m_Clib.cfsetispeed(t, new NativeLong(speed));
t.update(termios);
return ret;
}
public int cfsetospeed(Termios termios, int speed) {
Linux_C_lib.termios t = new Linux_C_lib.termios(termios);
int ret = m_Clib.cfsetospeed(t, new NativeLong(speed));
t.update(termios);
return ret;
}
public int open(String s, int t) {
if (s != null && !s.startsWith("/"))
s = DEVICE_DIR_PATH + s;
return m_Clib.open(s, t);
}
public int read(int fd, byte[] buffer, int len) {
if (IS64B)
return (int) m_Clib.read(fd, buffer, (long) len);
else
return m_Clib.read(fd, buffer, len);
}
public int write(int fd, byte[] buffer, int len) {
if (IS64B)
return (int) m_Clib.write(fd, buffer, (long) len);
else
return m_Clib.write(fd, buffer, len);
}
public int close(int fd) {
return m_Clib.close(fd);
}
public int tcflush(int fd, int b) {
return m_Clib.tcflush(fd, b);
}
public int tcgetattr(int fd, Termios termios) {
Linux_C_lib.termios t = new Linux_C_lib.termios();
int ret = m_Clib.tcgetattr(fd, t);
t.update(termios);
return ret;
}
public void perror(String msg) {
m_Clib.perror(msg);
}
public int tcsendbreak(int fd, int duration) {
// If duration is not zero, it sends zero-valued bits for duration*N seconds,
// where N is at least 0.25, and not more than 0.5.
return m_Clib.tcsendbreak(fd, duration / 250);
}
public int tcsetattr(int fd, int cmd, Termios termios) {
return m_Clib.tcsetattr(fd, cmd, new Linux_C_lib.termios(termios));
}
public void FD_CLR(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS));
}
public boolean FD_ISSET(int fd, FDSet set) {
if (set == null)
return false;
FDSetImpl p = (FDSetImpl) set;
return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0;
}
public void FD_SET(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS);
}
public void FD_ZERO(FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
java.util.Arrays.fill(p.bits, 0);
}
public int select(int nfds, FDSet rfds, FDSet wfds, FDSet efds, TimeVal timeout) {
Linux_C_lib.timeval tout = null;
if (timeout != null)
tout = new Linux_C_lib.timeval(timeout);
int[] r = rfds != null ? ((FDSetImpl) rfds).bits : null;
int[] w = wfds != null ? ((FDSetImpl) wfds).bits : null;
int[] e = efds != null ? ((FDSetImpl) efds).bits : null;
return m_Clib.select(nfds, r, w, e, tout);
}
public int poll(Pollfd fds[], int nfds, int timeout) {
pollfd[] pfds = new pollfd[fds.length];
for (int i = 0; i < nfds; i++)
pfds[i] = new pollfd(fds[i]);
int ret = m_Clib.poll(pfds, nfds, timeout);
for (int i = 0; i < nfds; i++)
fds[i].revents = pfds[i].revents;
return ret;
}
public int poll(int fds[], int nfds, int timeout) {
return m_Clib.poll(fds, nfds, timeout);
}
public FDSet newFDSet() {
return new FDSetImpl();
}
public int ioctl(int fd, int cmd, int[] data) {
return m_Clib.ioctl(fd, cmd, data);
}
// This ioctl is Linux specific, so keep it private for now
private int ioctl(int fd, int cmd, serial_struct data) {
// Do the logging here as this does not go through the JTermios which normally does the logging
log = log && log(5, "> ioctl(%d,%d,%s)\n", fd, cmd, data);
int ret = m_Clib.ioctl(fd, cmd, data);
log = log && log(3, "< tcsetattr(%d,%d,%s) => %d\n", fd, cmd, data, ret);
return ret;
}
public String getPortNamePattern() {
// First we have to determine which serial drivers exist and which
// prefixes they use
final List<String> prefixes = new ArrayList<String>();
try {
BufferedReader drivers = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/tty/drivers"), "US-ASCII"));
String line;
while ((line = drivers.readLine()) != null) {
// /proc/tty/drivers contains the prefix in the second column
// and "serial" in the fifth
String[] parts = line.split(" +");
if (parts.length != 5) {
continue;
}
if (!"serial".equals(parts[4])) {
continue;
}
// Sanity check the prefix
if (!parts[1].startsWith("/dev/")) {
continue;
}
prefixes.add(parts[1].substring(5));
}
drivers.close();
} catch (IOException e) {
log = log && log(1, "failed to read /proc/tty/drivers\n");
prefixes.add("ttyS");
prefixes.add("ttyUSB");
prefixes.add("ttyACM");
}
// Now build the pattern from the known prefixes
StringBuilder pattern = new StringBuilder();
pattern.append('^');
boolean first = false;
for (String prefix : prefixes) {
if (!first) {
first = true;
} else {
pattern.append('|');
}
pattern.append("(");
pattern.append(prefix);
pattern.append(".+)");
}
return pattern.toString();
}
public List<String> getPortList() {
File dir = new File(DEVICE_DIR_PATH);
if (!dir.isDirectory()) {
log = log && log(1, "device directory %s does not exist\n", DEVICE_DIR_PATH);
return null;
}
String[] devs = dir.list();
LinkedList<String> list = new LinkedList<String>();
Pattern p = JTermios.getPortNamePattern(this);
if (devs != null) {
for (int i = 0; i < devs.length; i++) {
String s = devs[i];
if (p.matcher(s).matches())
list.add(s);
}
}
return list;
}
public void shutDown() {
}
public int setspeed(int fd, Termios termios, int speed) {
int c = speed;
int r;
for (int i = 0; i < m_BaudRates.length; i += 2) {
if (m_BaudRates[i] == speed) {
// found the baudrate from the table
// in case custom divisor was in use, turn it off first
serial_struct ss = new serial_struct();
r = ioctl(fd, TIOCGSERIAL, ss);
if (r != 0) {
// not every driver supports TIOCGSERIAL, so if it fails, just ignore it
if (errno() != EINVAL)
return r;
} else {
ss.flags &= ~ASYNC_SPD_MASK;
r = ioctl(fd, TIOCSSERIAL, ss);
if (r != 0) {
// not every driver supports TIOCSSERIAL, so if it fails, just ignore it
if (errno() != EINVAL)
return r;
}
}
// now set the speed with the constant from the table
c = m_BaudRates[i + 1];
if ((r = JTermios.cfsetispeed(termios, c)) != 0)
return r;
if ((r = JTermios.cfsetospeed(termios, c)) != 0)
return r;
if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
}
// baudrate not defined in the table, try custom divisor approach
// configure port to use custom speed instead of 38400
serial_struct ss = new serial_struct();
if ((r = ioctl(fd, TIOCGSERIAL, ss)) != 0)
return r;
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
if (speed == 0) {
log = log && log(1, "unable to set custom baudrate %d \n", speed);
return -1;
}
ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed;
if (ss.custom_divisor == 0) {
log = log && log(1, "unable to set custom baudrate %d (possible division by zero)\n", speed);
return -1;
}
int closestSpeed = ss.baud_base / ss.custom_divisor;
if (closestSpeed < speed * 98 / 100 || closestSpeed > speed * 102 / 100) {
log = log && log(1, "best available baudrate %d not close enough to requested %d \n", closestSpeed, speed);
return -1;
}
if ((r = ioctl(fd, TIOCSSERIAL, ss)) != 0)
return r;
if ((r = JTermios.cfsetispeed(termios, B38400)) != 0)
return r;
if ((r = JTermios.cfsetospeed(termios, B38400)) != 0)
return r;
if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
public int pipe(int[] fds) {
return m_Clib.pipe(fds);
}
}
|
package prefuse.data.tuple;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import prefuse.data.Table;
import prefuse.data.Tuple;
import prefuse.data.event.TupleSetListener;
import prefuse.data.expression.Expression;
import prefuse.data.expression.Predicate;
import prefuse.data.expression.parser.ExpressionParser;
import prefuse.util.collections.CompositeIterator;
public class CompositeTupleSet extends AbstractTupleSet {
private static final Logger s_logger
= Logger.getLogger(CompositeTupleSet.class.getName());
private Map m_map; // map names to tuple sets
private Set m_sets; // support quick reverse lookup
private int m_count; // count of total tuples
private Listener m_lstnr;
/**
* Create a new, empty CompositeTupleSet
*/
public CompositeTupleSet() {
this(true);
}
protected CompositeTupleSet(boolean listen) {
m_map = new LinkedHashMap();
m_sets = new HashSet();
m_count = 0;
m_lstnr = listen ? new Listener() : null;
}
/**
* Add a TupleSet to this composite.
* @param name the name of the TupleSet to add
* @param set the set to add
*/
public void addSet(String name, TupleSet set) {
if ( hasSet(name) ) {
throw new IllegalArgumentException("Name already in use: "+name);
}
m_map.put(name, set);
m_sets.add(set);
m_count += set.getTupleCount();
if ( m_lstnr != null )
set.addTupleSetListener(m_lstnr);
}
/**
* Indicates if this composite contains a TupleSet with the given name.
* @param name the name to look for
* @return true if a TupleSet with the given name is found, false otherwise
*/
public boolean hasSet(String name) {
return m_map.containsKey(name);
}
/**
* Indicates if this composite contains the given TupleSet.
* @param set the TupleSet to check for containment
* @return true if the TupleSet is contained in this composite,
* false otherwise
*/
public boolean containsSet(TupleSet set) {
return m_sets.contains(set);
}
/**
* Get the TupleSet associated with the given name.
* @param name the name of the TupleSet to get
* @return the associated TupleSet, or null if not found
*/
public TupleSet getSet(String name) {
return (TupleSet)m_map.get(name);
}
/**
* Get an iterator over the names of all the TupleSets in this composite.
* @return the iterator over contained set names.
*/
public Iterator setNames() {
return m_map.keySet().iterator();
}
/**
* Get an iterator over all the TupleSets in this composite.
* @return the iterator contained sets.
*/
public Iterator sets() {
return m_map.values().iterator();
}
/**
* Remove the TupleSet with the given name from this composite.
* @param name the name of the TupleSet to remove
* @return the removed TupleSet, or null if not found
*/
public TupleSet removeSet(String name) {
TupleSet ts = (TupleSet)m_map.remove(name);
if ( ts != null ) {
m_sets.remove(ts);
if ( m_lstnr != null )
ts.removeTupleSetListener(m_lstnr);
}
return ts;
}
/**
* Remove all contained TupleSets from this composite.
*/
public void removeAllSets() {
Iterator sets = m_map.entrySet().iterator();
while ( sets.hasNext() ) {
Map.Entry entry = (Map.Entry)sets.next();
TupleSet ts = (TupleSet)entry.getValue();
sets.remove();
m_sets.remove(ts);
if ( m_lstnr != null )
ts.removeTupleSetListener(m_lstnr);
}
m_count = 0;
}
/**
* Clear this TupleSet, calling clear on all contained TupleSet
* instances. All contained TupleSets remain members of this
* composite, but they have their data cleared.
* @see prefuse.data.tuple.TupleSet#clear()
*/
public void clear() {
Iterator sets = m_map.entrySet().iterator();
while ( sets.hasNext() ) {
Map.Entry entry = (Map.Entry)sets.next();
((TupleSet)entry.getValue()).clear();
}
m_count = 0;
}
// TupleSet Interface
/**
* Not supported.
* @see prefuse.data.tuple.TupleSet#addTuple(prefuse.data.Tuple)
*/
public Tuple addTuple(Tuple t) {
throw new UnsupportedOperationException();
}
/**
* Not supported.
* @see prefuse.data.tuple.TupleSet#setTuple(prefuse.data.Tuple)
*/
public Tuple setTuple(Tuple t) {
throw new UnsupportedOperationException();
}
/**
* Removes the tuple from its source set if that source set is contained
* within this composite.
* @see prefuse.data.tuple.TupleSet#removeTuple(prefuse.data.Tuple)
*/
public boolean removeTuple(Tuple t) {
Table table = t.getTable();
if ( m_sets.contains(table) ) {
return table.removeTuple(t);
} else {
return false;
}
}
/**
* @see prefuse.data.tuple.TupleSet#containsTuple(prefuse.data.Tuple)
*/
public boolean containsTuple(Tuple t) {
Table table = t.getTable();
return containsSet(table);
}
/**
* @see prefuse.data.tuple.TupleSet#getTupleCount()
*/
public int getTupleCount() {
if ( m_lstnr != null ) {
return m_count;
} else {
int count = 0;
Iterator it = m_map.entrySet().iterator();
for ( int i=0; it.hasNext(); ++i ) {
Map.Entry entry = (Map.Entry)it.next();
TupleSet ts = (TupleSet)entry.getValue();
count += ts.getTupleCount();
}
return count;
}
}
/**
* @see prefuse.data.tuple.TupleSet#tuples()
*/
public Iterator tuples() {
CompositeIterator ci = new CompositeIterator(m_map.size());
Iterator it = m_map.entrySet().iterator();
for ( int i=0; it.hasNext(); ++i ) {
Map.Entry entry = (Map.Entry)it.next();
TupleSet ts = (TupleSet)entry.getValue();
ci.setIterator(i, ts.tuples());
}
return ci;
}
/**
* @see prefuse.data.tuple.TupleSet#tuples(prefuse.data.expression.Predicate)
*/
public Iterator tuples(Predicate filter) {
CompositeIterator ci = new CompositeIterator(m_map.size());
Iterator it = m_map.entrySet().iterator();
for ( int i=0; it.hasNext(); ++i ) {
Map.Entry entry = (Map.Entry)it.next();
TupleSet ts = (TupleSet)entry.getValue();
ci.setIterator(i, ts.tuples(filter));
}
return ci;
}
/**
* Returns true.
* @see prefuse.data.tuple.TupleSet#isAddColumnSupported()
*/
public boolean isAddColumnSupported() {
return true;
}
/**
* Adds the value to all contained TupleSets that return a true value for
* {@link TupleSet#isAddColumnSupported()}.
* @see prefuse.data.tuple.TupleSet#addColumn(java.lang.String, java.lang.Class, java.lang.Object)
*/
public void addColumn(String name, Class type, Object defaultValue) {
Iterator it = m_map.entrySet().iterator();
while ( it.hasNext() ) {
Map.Entry entry = (Map.Entry)it.next();
TupleSet ts = (TupleSet)entry.getValue();
if ( ts.isAddColumnSupported() ) {
try {
ts.addColumn(name, type, defaultValue);
} catch ( IllegalArgumentException iae ) {
// already exists
}
} else {
s_logger.fine("Skipped addColumn for "+entry.getKey());
}
}
}
/**
* Adds the value to all contained TupleSets that return a true value for
* {@link TupleSet#isAddColumnSupported()}.
* @see prefuse.data.tuple.TupleSet#addColumn(java.lang.String, java.lang.Class)
*/
public void addColumn(String name, Class type) {
Iterator it = m_map.entrySet().iterator();
while ( it.hasNext() ) {
Map.Entry entry = (Map.Entry)it.next();
TupleSet ts = (TupleSet)entry.getValue();
if ( ts.isAddColumnSupported() ) {
try {
ts.addColumn(name, type);
} catch ( IllegalArgumentException iae ) {
// already exists
}
} else {
s_logger.fine("Skipped addColumn for "+entry.getKey());
}
}
}
/**
* Adds the value to all contained TupleSets that return a true value for
* {@link TupleSet#isAddColumnSupported()}.
* @see prefuse.data.tuple.TupleSet#addColumn(java.lang.String, prefuse.data.expression.Expression)
*/
public void addColumn(String name, Expression expr) {
Iterator it = m_map.entrySet().iterator();
while ( it.hasNext() ) {
Map.Entry entry = (Map.Entry)it.next();
TupleSet ts = (TupleSet)entry.getValue();
if ( ts.isAddColumnSupported() ) {
try {
ts.addColumn(name, expr);
} catch ( IllegalArgumentException iae ) {
// already exists
}
} else {
s_logger.fine("Skipped addColumn for "+entry.getKey());
}
}
}
/**
* Adds the value to all contained TupleSets that return a true value for
* {@link TupleSet#isAddColumnSupported()}.
* @see prefuse.data.tuple.TupleSet#addColumn(java.lang.String, java.lang.String)
*/
public void addColumn(String name, String expr) {
Expression ex = ExpressionParser.parse(expr);
Throwable t = ExpressionParser.getError();
if ( t != null ) {
throw new RuntimeException(t);
} else {
addColumn(name, ex);
}
}
// Internal TupleSet Listener
/**
* Listener that relays tuple set change events as they occur and updates
* the total tuple count appropriately.
*/
private class Listener implements TupleSetListener {
public void tupleSetChanged(TupleSet tset, Tuple[] add, Tuple[] rem) {
m_count += add.length - rem.length;
fireTupleEvent(add, rem);
}
}
} // end of class CompositeTupleSet
|
package org.tigris.subversion.subclipse.ui.actions;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.team.core.TeamException;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
public class CopyAction extends WorkspaceAction {
protected void execute(IAction action) throws InvocationTargetException, InterruptedException {
final IResource[] resources = getSelectedResources();
final IProject project = resources[0].getProject();
ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), project, false, Policy.bind("CopyAction.selectionLabel")); //$NON-NLS-1$
if (dialog.open() == ContainerSelectionDialog.CANCEL) return;
Object[] result = dialog.getResult();
if (result == null || result.length == 0) return;
final Path path = (Path)result[0];
IProject selectedProject;
File target = null;
if (path.segmentCount() == 1) {
selectedProject = ResourcesPlugin.getWorkspace().getRoot().getProject(path.toString());
target = selectedProject.getLocation().toFile();
} else {
IFile targetFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
selectedProject = targetFile.getProject();
target = targetFile.getLocation().toFile();
}
final IProject targetProject = selectedProject;
final File destPath = target;
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = null;
for (int i = 0; i < resources.length; i++) {
final IResource resource = resources[i];
if (client == null)
client = SVNWorkspaceRoot.getSVNResourceFor(resources[i]).getRepository().getSVNClient();
File checkFile = new File(destPath.getPath() + File.separator + resource.getName());
File srcPath = new File(resource.getLocation().toString());
File newDestPath = new File(destPath.getPath() + File.separator + resource.getName());
if (checkFile.exists()) {
IInputValidator inputValidator = new IInputValidator() {
public String isValid(String newText) {
if (newText.equals(resource.getName()))
return Policy.bind("CopyAction.nameConflictSame"); //$NON-NLS-1$
return null;
}
};
InputDialog inputDialog = new InputDialog(getShell(), Policy.bind("CopyAction.nameConflictTitle"), Policy.bind("CopyAction.nameConflictMessage", resource.getName()), "Copy of " + resource.getName(), inputValidator); //$NON-NLS-1$
if (inputDialog.open() == InputDialog.CANCEL) return;
String newName = inputDialog.getValue();
if (newName == null || newName.trim().length() == 0) return;
newDestPath = new File(destPath.getPath() + File.separator + newName);
}
if (project.getFullPath().isPrefixOf(path))
client.copy(srcPath, newDestPath);
else
client.doExport(srcPath, newDestPath, true);
}
targetProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (Exception e) {
MessageDialog.openError(getShell(), Policy.bind("CopyAction.copy"), e.getMessage()); //$NON-NLS-1$
}
}
});
}
protected boolean isEnabled() throws TeamException {
// Only enabled if all selections are from same project.
boolean enabled = super.isEnabled();
if (!enabled) return false;
IResource[] resources = getSelectedResources();
IProject project = null;
for (int i = 0; i < resources.length; i++) {
if (resources[i] instanceof IProject) return false;
if (project != null && !resources[i].getProject().equals(project)) return false;
project = resources[i].getProject();
}
return true;
}
}
|
package ox.softeng.burst.services;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import ox.softeng.burst.domain.Frequency;
import ox.softeng.burst.domain.Severity;
import ox.softeng.burst.domain.Subscription;
import ox.softeng.burst.domain.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException
{
// Arguments:
// rabbitmq host name
// rabbitmq exchange name
// rabbitmq queue name
// database server
// database db name
// database username
// database password
if(args.length < 1)
{
System.err.println("Usage: Main config.properties");
System.exit(0);
}
Properties props = new Properties();
props.load(new FileInputStream(new File(args[0])));
String RabbitMQHost = props.getProperty("RabbitMQHost");
String RabbitMQExchange = props.getProperty("RabbitMQExchange");
String RabbitMQQueue = props.getProperty("RabbitMQQueue");
System.out.println("RabbitMQ Host Name: " + RabbitMQHost);
System.out.println("RabbitMQ Exchange Name: " + RabbitMQExchange);
System.out.println("RabbitMQ Queue Name: " + RabbitMQQueue);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( "ox.softeng.burst", props);
/* Set up a test user...
User u = new User("James", "Welch", "jamesrwelch@gmail.com");
Subscription s = new Subscription(u, Frequency.IMMEDIATE, Severity.DEBUG);
s.addTopic("File Receipt");
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
em.persist(u);
em.persist(s);
em.getTransaction().commit();
em.close();
*/
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Runnable rabbitReceiver = new RabbitService(RabbitMQHost, RabbitMQExchange, RabbitMQQueue, entityManagerFactory);
executor.execute(rabbitReceiver);
ReportScheduler repSched = new ReportScheduler(entityManagerFactory, props);
executor.scheduleAtFixedRate(repSched, 0, 1, TimeUnit.MINUTES);
}
}
|
import com.sun.org.apache.bcel.internal.Repository;
import com.sun.org.apache.bcel.internal.classfile.JavaClass;
import com.sun.org.apache.bcel.internal.classfile.LineNumberTable;
import com.sun.org.apache.bcel.internal.classfile.Method;
import com.sun.org.apache.bcel.internal.util.ClassLoaderRepository;
import java.io.IOException;
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws IOException {
JavaClass javaClass;
// ClassParser parser = new ClassParser("D:\\DOCUMENTS\\PROGRAMS\\OMAT\\weenyconsole\\target\\test-classes\\Test.class");
// javaClass = parser.parse();
Repository.setRepository(new ClassLoaderRepository(Test.class
.getClassLoader()));
javaClass = Repository.lookupClass(Test.class.getName());
System.out.println("javaClass = " + javaClass);
for (Method method : javaClass.getMethods()) {
System.out.println("
LineNumberTable table = method.getLineNumberTable();
System.out.println("Method = " + method.getName());
System.out.println("LineNumberTable = "
+ Arrays.toString(table.getLineNumberTable()));
System.out.println("Code = " + method.getCode());
}
}
public void empty() {
}
// TODO: try to use com.sun.org.apache.bcel.internal.classfile.ClassParser to get the line numbers of the code in Method classes
// - if it works, fix the sorting of SpecRunner (classes and methods)
}
|
package com.unidev.polydata.storage.sqlite4a;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import com.unidev.polydata.storage.PolyStorage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import sqlite4a.SQLite;
import sqlite4a.SQLiteCursor;
import sqlite4a.SQLiteDb;
import sqlite4a.SQLiteStmt;
/**
* SQL lite backed poly storage
*/
public class SQLiteStorage implements PolyStorage {
private SQLiteDb db;
public static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
public SQLiteStorage(String path) {
db = SQLite.open(path, SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE);
initdb();
}
protected void initdb() {
db.exec("CREATE TABLE IF NOT EXISTS polys( id TEXT PRIMARY KEY, data TEXT);");
}
public SQLiteDb fetchDb() {
return db;
}
@Override
public <T extends Poly> T fetchById(String id) {
return null;
}
@Override
public Collection<? extends Poly> list() {
List<Poly> list = new ArrayList<>();
SQLiteStmt stmt = db.prepare("SELECT * FROM polys ;");
SQLiteCursor cursor = stmt.executeSelect();
while(cursor.step()) {
String data = cursor.getColumnString(1);// fetch data
Poly poly = loadPoly(data);
list.add(poly);
}
return list;
}
protected Poly loadPoly(String raw) {
try {
BasicPoly basicPoly = objectMapper.readValue(raw, BasicPoly.class);
return basicPoly;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
|
package reactor.spring.core.concurrent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Processor;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.error.Exceptions.UpstreamException;
import reactor.fn.Consumer;
import reactor.rx.Promise;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.SuccessCallback;
/**
* Adapt a Reactor {@link reactor.rx.Promise} to a Spring {@link org.springframework.util.concurrent.ListenableFuture}
* and possibly convert the value before setting it on the {@code Promise}.
*/
public abstract class AdaptingListenableFutureProcessor<T, V> implements ListenableFuture<V>, Processor<T, V> {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final Promise<V> promise = Promise.ready();
@Override
public void subscribe(Subscriber<? super V> s) {
promise.subscribe(s);
}
@Override
public void onSubscribe(Subscription s) {
promise.onSubscribe(s);
}
@Override
public void onNext(T t) {
promise.onNext(adapt(t));
}
@Override
public void onError(Throwable t) {
try{
promise.onError(t);
}
catch (Exceptions.UpstreamException x){
if(x.getCause() instanceof RuntimeException){
throw (RuntimeException)x.getCause();
}
throw x;
}
}
@Override
public void onComplete() {
promise.onComplete();
}
@Override
public void addCallback(ListenableFutureCallback<? super V> callback) {
addCallback(callback, callback);
}
@Override
public void addCallback(final SuccessCallback<? super V> successCallback,
final FailureCallback failureCallback) {
promise
.doOnSuccess(new Consumer<V>() {
@Override
public void accept(V val) {
if (null != successCallback) {
successCallback.onSuccess(val);
}
}
})
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
if (null != failureCallback) {
failureCallback.onFailure(throwable);
}
}
})
.subscribe();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (promise.isPending() && cancelled.compareAndSet(false, true)) {
promise.onComplete();
return true;
} else {
return cancelled.get();
}
}
@Override
public boolean isCancelled() {
return cancelled.get();
}
@Override
public boolean isDone() {
return promise.isTerminated();
}
@Override
public V get() throws InterruptedException, ExecutionException {
return promise.await();
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return promise.await(timeout, unit);
}
protected abstract V adapt(T val);
}
|
package com.biomatters.plugins.barcoding.validator.research.report;
import com.biomatters.geneious.publicapi.components.*;
import com.biomatters.geneious.publicapi.documents.DocumentUtilities;
import com.biomatters.geneious.publicapi.documents.URN;
import com.biomatters.geneious.publicapi.plugin.ActionProvider;
import com.biomatters.geneious.publicapi.plugin.DocumentViewer;
import com.biomatters.geneious.publicapi.plugin.GeneiousAction;
import com.biomatters.geneious.publicapi.plugin.Options;
import com.biomatters.geneious.publicapi.utilities.GeneralUtilities;
import com.biomatters.geneious.publicapi.utilities.IconUtilities;
import com.biomatters.geneious.publicapi.utilities.StringUtilities;
import com.biomatters.plugins.barcoding.validator.output.RecordOfValidationResult;
import com.biomatters.plugins.barcoding.validator.output.ValidationOutputRecord;
import com.biomatters.plugins.barcoding.validator.output.ValidationReportDocument;
import com.biomatters.plugins.barcoding.validator.research.report.table.ColumnGroup;
import com.biomatters.plugins.barcoding.validator.research.report.table.GroupableTableHeader;
import com.biomatters.plugins.barcoding.validator.research.report.table.GroupableTableHeaderUI;
import com.biomatters.plugins.barcoding.validator.validation.ValidationOptions;
import com.biomatters.plugins.barcoding.validator.validation.results.LinkResultColumn;
import com.biomatters.plugins.barcoding.validator.validation.results.ResultColumn;
import com.biomatters.plugins.barcoding.validator.validation.results.ResultFact;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;
public class ValidationReportViewer extends DocumentViewer {
ValidationReportDocument reportDocument;
JTable table = null;
public ValidationReportViewer(ValidationReportDocument reportDocument) {
this.reportDocument = reportDocument;
}
public String getHtml() {
return generateHtml(reportDocument);
}
public static final String OPTION_PREFIX = "option:";
public HyperlinkListener getHyperlinkListener() {
final Map<String, ValidationOptions> optionsMap = getOptionMap(reportDocument);
return new DocumentOpeningHyperlinkListener("ReportDocumentFactory",
Collections.<String, DocumentOpeningHyperlinkListener.UrlProcessor>singletonMap(OPTION_PREFIX,
new DocumentOpeningHyperlinkListener.UrlProcessor() {
@Override
void process(String url) {
final String optionLable = url.substring(OPTION_PREFIX.length());
final ValidationOptions options = optionsMap.get(optionLable);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
options.setEnabled(false);
Dialogs.DialogOptions dialogOptions = new Dialogs.DialogOptions(Dialogs.OK_ONLY, "Options");
Dialogs.showMoreOptionsDialog(dialogOptions, options.getPanel(), options.getAdvancedPanel());
}
});
}
}));
}
private static Map<String, ValidationOptions> getOptionMap(ValidationReportDocument reportDocument) {
Map<String, ValidationOptions> ret = new HashMap<String, ValidationOptions>();
if (reportDocument == null || reportDocument.getRecords() == null)
return ret;
List<ValidationOutputRecord> records = reportDocument.getRecords();
for (ValidationOutputRecord record : records) {
for (RecordOfValidationResult result : record.getValidationResults()) {
ValidationOptions options = result.getOptions();
ret.put(options.getLabel(), options);
}
}
return ret;
}
private static String generateHtml(ValidationReportDocument reportDocument) {
List<ValidationOutputRecord> records = reportDocument.getRecords();
return getHeaderOfReport(records, reportDocument.getDescriptionOfOptions());
}
private static String getHeaderOfReport(List<ValidationOutputRecord> records, String descriptionOfOptionUsed) {
List<ValidationOutputRecord> recordsThatPassedAll = new ArrayList<ValidationOutputRecord>();
List<ValidationOutputRecord> recordsThatFailedAtLeastOnce = new ArrayList<ValidationOutputRecord>();
for (ValidationOutputRecord record : records) {
if(record.isAllPassedForConsensus()) {
recordsThatPassedAll.add(record);
} else {
recordsThatFailedAtLeastOnce.add(record);
}
}
boolean allPassed = recordsThatPassedAll.size() == records.size();
boolean allFailed = recordsThatFailedAtLeastOnce.size() == records.size();
StringBuilder headerBuilder = new StringBuilder("<h1>Validation Report</h1>");
headerBuilder.append(descriptionOfOptionUsed);
headerBuilder.append("<br><br>").append(
"Ran validations on <strong>").append(records.size()).append("</strong> sets of barcode data:");
headerBuilder.append("<ul>");
if(!allFailed) {
appendHeaderLineItem(headerBuilder, "green", allPassed, recordsThatPassedAll, "passed all validations");
}
if(!allPassed) {
appendHeaderLineItem(headerBuilder, "red", allFailed, recordsThatFailedAtLeastOnce,
"failed at least one validations");
}
headerBuilder.append("</ul>");
return headerBuilder.toString();
}
private static void appendHeaderLineItem(StringBuilder headerBuilder, String colour, boolean isAll, List<ValidationOutputRecord> records, String whatHappened) {
List<URN> barcodeUrns = new ArrayList<URN>();
for (ValidationOutputRecord record : records) {
barcodeUrns.add(record.getBarcodeSequenceUrn());
}
String countString = (isAll ? "All " : "") + records.size();
headerBuilder.append(
"<li><font color=\"").append(colour).append("\"><strong>").append(
countString).append("</strong></font> sets ").append(whatHappened).append(". ").append(
getLinkForSelectingDocuments("Select all", barcodeUrns));
}
private static String getLinkForSelectingDocuments(String label, List<URN> documentUrns) {
List<String> urnStrings = new ArrayList<String>();
for (URN inputUrn : documentUrns) {
urnStrings.add(inputUrn.toString());
}
return "<a href=\"" + StringUtilities.join(",", urnStrings) + "\">" + label + "</a>";
}
private JTextPane getTextPane() {
String html = getHtml();
if(html == null || html.isEmpty()) {
return null;
}
final JTextPane textPane = new GTextPane();
textPane.setContentType("text/html");
textPane.setEditable(false);
HyperlinkListener hyperlinkListener = getHyperlinkListener();
if(hyperlinkListener != null) {
textPane.addHyperlinkListener(hyperlinkListener);
}
textPane.setText(html);
return textPane;
}
@Override
public JComponent getComponent() {
JComponent textPane = getTextPane();
final GPanel rootPanel = new GPanel(new BorderLayout()) {
@Override
public Dimension getPreferredSize() {
Dimension defaultPrefSize = super.getPreferredSize();
// Add 500 px to the preferred height so users can scroll past the table
return new Dimension(defaultPrefSize.width, defaultPrefSize.height + 500);
}
};
rootPanel.add(textPane, BorderLayout.NORTH);
if (table == null) {
table = getTable();
}
if (table != null) {
final JScrollPane tableScrollPane = new JScrollPane(table);
// Set the scroll pane's preferred size to the same as the table so scroll bars are never needed
tableScrollPane.getViewport().setPreferredSize(table.getPreferredSize());
table.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
tableScrollPane.getViewport().setPreferredSize(table.getPreferredSize());
rootPanel.validate();
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
rootPanel.add(tableScrollPane, BorderLayout.CENTER);
}
return rootPanel;
}
public JTable getTable() {
List<ValidationOutputRecord> records = reportDocument.getRecords();
final ValidationReportTableModel tableModel = new ValidationReportTableModel(records, reportDocument.getPciValues());
final JTable table = new GTable(tableModel, new DefaultTableColumnModel(){
@Override
public void moveColumn(int columnIndex, int newIndex) {
if (tableModel.getOptionAt(columnIndex) == tableModel.getOptionAt(newIndex)) {
super.moveColumn(columnIndex, newIndex);
}
}
});
table.setAutoCreateColumnsFromModel(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(ResultColumn.class, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return super.getTableCellRendererComponent(table, ((ResultColumn) value).getDisplayValue(), isSelected, hasFocus, row, column);
}
});
TableRowSorter<ValidationReportTableModel> sorter = new TableRowSorter<ValidationReportTableModel>(tableModel);
for (int i = 0; i < table.getColumnCount(); i++) {
Class<?> columnClass = table.getColumnClass(i);
if(CellValue.class.isAssignableFrom(columnClass)) {
sorter.setComparator(i, getCellValueComparator(CellValue.class, sorter));
}
}
table.setRowSorter(sorter);
GroupableTableHeader head = new GroupableTableHeader(table.getTableHeader());
table.setTableHeader(head);
TableCellRenderer headerRenderer = head.getDefaultRenderer();
if(headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER);
}
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
Object source = e.getSource();
if (source instanceof JTable) {
JTable table = (JTable) source;
Object cell = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
if (cell instanceof CellValue) {
ResultColumn value = ((CellValue) cell).value;
if(value instanceof LinkResultColumn) {
((LinkResultColumn)value).getData().openLink();
}
}
}
}
});
mergeHeader(table, records);
final GroupableTableHeaderUI groupableTableHeaderUI = new GroupableTableHeaderUI();
table.getTableHeader().setUI(groupableTableHeaderUI);
table.setAutoCreateRowSorter(false);
MouseListener[] mouseListeners = head.getMouseListeners();
MouseInputListener originalHeaderMouseListener = null;
for (final MouseListener mouseListener : mouseListeners) {
if(mouseListener instanceof BasicTableHeaderUI.MouseInputHandler) {
originalHeaderMouseListener = (BasicTableHeaderUI.MouseInputHandler)mouseListener;
}
}
if(originalHeaderMouseListener != null) {
head.removeMouseListener(originalHeaderMouseListener);
MouseAdapter wrapper = wrapMouseListenerForHeader(tableModel, table, groupableTableHeaderUI, originalHeaderMouseListener);
head.addMouseListener(wrapper);
}
table.getTableHeader().setReorderingAllowed(true);
return table;
}
private MouseInputAdapter wrapMouseListenerForHeader(final ValidationReportTableModel tableModel, final JTable table, final GroupableTableHeaderUI groupableTableHeaderUI, final MouseInputListener originalHeaderMouseListener) {
return new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int column = table.columnAtPoint(e.getPoint());
if (column >= tableModel.getFixedColumnLength() && e.getY() <= groupableTableHeaderUI.getHeaderHeight() / 2) {
tableModel.displayOptions(column);
} else {
originalHeaderMouseListener.mouseClicked(e);
}
}
@Override
public void mousePressed(MouseEvent e) {
originalHeaderMouseListener.mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
originalHeaderMouseListener.mouseReleased(e);
}
@Override
public void mouseEntered(MouseEvent e) {
originalHeaderMouseListener.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
originalHeaderMouseListener.mouseExited(e);
}
@Override
public void mouseDragged(MouseEvent e) {
originalHeaderMouseListener.mouseDragged(e);
}
@Override
public void mouseMoved(MouseEvent e) {
originalHeaderMouseListener.mouseMoved(e);
}
};
}
private static <T extends Comparable<T>> Comparator getCellValueComparator(
// There is a warning that we don't use the class. But we need this parameter at compile time to type the generic
@SuppressWarnings("UnusedParameters") Class<T> columnClass, final RowSorter rowSorter) {
return new Comparator<CellValue<T>>() {
@Override
public int compare(CellValue<T> o1, CellValue<T> o2) {
int value = o1.compareTo(o2);
if(o1.consensusValue == o2.consensusValue) {
// If the values are from the same set we must keep the order. So we need to check direction.
//noinspection unchecked
List<RowSorter.SortKey> sortKeys = rowSorter.getSortKeys();
if (!sortKeys.isEmpty()) {
RowSorter.SortKey sortKey = sortKeys.get(0);
SortOrder sortOrder = sortKey.getSortOrder();
return (sortOrder == SortOrder.ASCENDING ? 1 : -1) * value;
}
}
return value;
}
};
}
private void mergeHeader(JTable table, List<ValidationOutputRecord> records) {
assert records != null && records.size() > 0;
ValidationOutputRecord record = records.get(0);
TableColumnModel cm = table.getColumnModel();
GroupableTableHeader head = (GroupableTableHeader) table.getTableHeader();
TableCellRenderer headerRenderer = head.getDefaultRenderer();
ValidationReportTableModel model = (ValidationReportTableModel) table.getModel();
int colIndex = record.getFixedColumns(record.getTraceDocumentUrns().get(0), null).size();
Map<Class, Map<URN, RecordOfValidationResult>> validationResultsMap = record.getValidationResultsMap();
for (Map.Entry<Class, Map<URN, RecordOfValidationResult>> classMapEntry : validationResultsMap.entrySet()) {
Map<URN, RecordOfValidationResult> entry = classMapEntry.getValue();
assert entry.size() > 0;
int failCount = 0;
int successCount = 0;
for (Map.Entry<URN, RecordOfValidationResult> resultEntry : model.getResultsAt(colIndex).entrySet()) {
if (resultEntry.getValue().isPassed()) {
successCount++;
} else {
failCount++;
}
}
ResultFact fact = entry.values().iterator().next().getFact();
String headText = fact.getFactName() + "<br>(" + successCount + " Passed/" + failCount + " Failed)";
ColumnGroup factGroup = new ColumnGroup(headText, headerRenderer);
for (int i = 0; i < fact.getColumns().size(); i++) {
factGroup.add(cm.getColumn(colIndex++));
}
head.addColumnGroup(factGroup);
}
}
@Override
public ActionProvider getActionProvider() {
return new ActionProvider() {
@Override
public List<GeneiousAction> getOtherActions() {
List<GeneiousAction> ret = new ArrayList<GeneiousAction>();
ret.add(new ExportReportAction("Export report table to csv file", table));
return ret;
}
};
}
protected static class ExportReportAction extends GeneiousAction {
private JTable table = null;
public ExportReportAction(String name, JTable table) {
super(name, null, IconUtilities.getIcons("export16.png"));
this.table = table;
}
public void actionPerformed(ActionEvent e) {
if (table == null) {
Dialogs.showMessageDialog("Can not find table");
return;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Options options = new Options(ValidationReportViewer.class);
Options.FileSelectionOption selectionOption = options.addFileSelectionOption("targetFolder", "Export Folder:", "", new String[0], "Browse...");
selectionOption.setSelectionType(JFileChooser.DIRECTORIES_ONLY);
Options.StringOption filenameOption = options.addStringOption("filename", "Filename:", "report.csv", "Name of CSV file");
options.setEnabled(true);
if (!Dialogs.showOptionsDialog(options, "Export report table to csv file", false)) {
return;
}
File outFile = new File(selectionOption.getValue(), filenameOption.getValue());
if(outFile.exists()) {
if (!Dialogs.showYesNoDialog(outFile.getName() + " already exists, do you want to replace it?",
"Replace File?", null, Dialogs.DialogIcon.QUESTION)) {
return;
}
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(outFile));
int columnCount = table.getColumnModel().getColumnCount();
List<String> values = getHeader();
writeRow(writer, values);
int rowCount = table.getRowCount();
for (int row = 0; row < rowCount; row++) {
values.clear();
for (int column=0; column < columnCount; column++) {
Object value = table.getValueAt(row, column);
if(value instanceof CellValue) {
value = ((CellValue)value).value.getDisplayValue();
}
if (value == null) {
values.add("");
} else {
values.add(stripHtmlTags(value.toString(), true));
}
}
writeRow(writer, values);
}
Dialogs.showMessageDialog("Table exported to " + outFile.getAbsolutePath() + " successfully.");
} catch (IOException e1) {
Dialogs.showMessageDialog("Failed to export table: " + e1.getMessage());
} finally {
GeneralUtilities.attemptClose(writer);
}
}
});
}
protected List<String> getHeader(){
int columnCount = table.getColumnModel().getColumnCount();
GroupableTableHeader header = (GroupableTableHeader) table.getTableHeader();
List<String> values = new LinkedList<String>();
for (int column = 0; column < columnCount; column++) {
StringBuilder sb = new StringBuilder();
Enumeration columnGroups = header.getColumnGroups(table.getColumnModel().getColumn(column));
while (columnGroups != null && columnGroups.hasMoreElements()) {
sb.append(((ColumnGroup) columnGroups.nextElement()).getText()).append(" - ");
}
sb.append(table.getColumnModel().getColumn(column).getHeaderValue().toString());
values.add(sb.toString());
}
return values;
}
private void writeRow(BufferedWriter writer, List<String> values) throws IOException {
boolean first = true;
for (String value : values) {
if (first) {
first = false;
} else {
writer.write(",");
}
writer.write(escapeValueForCsv(value));
}
writer.newLine();
}
private String escapeValueForCsv(String value) {
value = value.replaceAll("\"", "\"\"");
if (value.contains("\"") || value.contains(",") || value.contains("\n")) {
value = "\"" + value + "\"";
}
return value;
}
private String stripHtmlTags(String string, boolean onlyIfStartsWithHtmlTag) {
if ((string == null) || "".equals(string) || (onlyIfStartsWithHtmlTag && !string.regionMatches(true, 0, "<html>", 0, 6))) {
return string;
}
string = Pattern.compile("</?[a-zA-Z0-9][^>]*>").matcher(string).replaceAll("");
string = string.replace(">",">");
string = string.replace("<","<");
return string;
}
}
/**
* A value in the table model that is aware of it's index and the value associated with the consensus
* @param <T> Type of the data contained in a cell. Corresponds to the {@link com.biomatters.plugins.barcoding.validator.validation.results.ResultColumn} type.
*/
private static class CellValue<T extends Comparable<T>> implements Comparable<CellValue<T>> {
private ResultColumn<T> consensusValue;
private Integer index;
private ResultColumn<T> value;
public CellValue(ResultColumn<T> consensusValue, ResultColumn<T> value, Integer index) {
this.consensusValue = consensusValue;
this.value = value;
this.index = index;
}
@Override
public String toString() {
return value.getDisplayValue().toString();
}
@Override
public int compareTo(CellValue<T> o) {
T value = consensusValue.getData();
T value2 = o.consensusValue.getData();
if (value == null && value2 == null) {
return 0;
} else if(value == null) {
return -1;
} else if(value2 == null) {
return 1;
}
int consensusCompareResult = value.compareTo(value2);
if(consensusCompareResult == 0) {
return index.compareTo(o.index);
} else {
return consensusCompareResult;
}
}
}
public static class ValidationReportTableModel extends AbstractTableModel {
private List<ValidationOutputRecord> records;
private List<List<CellValue<?>>> data;
public ValidationReportTableModel(List<ValidationOutputRecord> records, Map<URN, Double> pciScores) {
this.records = new ArrayList<ValidationOutputRecord>();
for (ValidationOutputRecord record : records) {
this.records.add(record);
}
data = createTableData(records, pciScores);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return CellValue.class;
}
private static List<List<CellValue<?>>> createTableData(List<ValidationOutputRecord> records, Map<URN, Double> pciValues) {
List<List<CellValue<?>>> data = new ArrayList<List<CellValue<?>>>();
for (ValidationOutputRecord record : records) {
List<ResultColumn> firstRow = null;
for (List<ResultColumn> resultColumns : record.exportTable(pciValues)) {
if(firstRow == null) {
firstRow = resultColumns;
}
List<CellValue<?>> values = new ArrayList<CellValue<?>>();
for(int columnIndex=0; columnIndex<resultColumns.size(); columnIndex++) {
CellValue<?> cellValue = getCellValue(firstRow.get(columnIndex), resultColumns.get(columnIndex), columnIndex);
values.add(cellValue);
}
data.add(values);
}
}
return data;
}
private static <T extends Comparable<T>> CellValue getCellValue(ResultColumn<T> firstRowValue, ResultColumn currentRowValue, int columnIndex) {
// Have to cast because getClass() actually returns Class<? extends ResultColumn> due to type erasure :(
//noinspection unchecked
Class<ResultColumn<T>> firstRowClass = (Class<ResultColumn<T>>) firstRowValue.getClass();
return new CellValue<T>(firstRowClass.cast(firstRowValue), firstRowClass.cast(currentRowValue), columnIndex);
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
if (data.size() == 0) {
return 0;
}
return data.get(0).size();
}
@Override
public CellValue getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex).get(columnIndex);
}
@Override
public String getColumnName(int column) {
if (data.size() == 0) {
return super.getColumnName(column);
}
return data.get(0).get(column).value.getName();
}
public void displayOptions(int columnIndex) {
final ValidationOptions options = getOptionAt(columnIndex);
if (options == null) {
return;
}
final List<URN> failedResults = new ArrayList<URN>();
final List<URN> passedResults = new ArrayList<URN>();
for (Map.Entry<URN, RecordOfValidationResult> resultEntry : getResultsAt(columnIndex).entrySet()) {
if (resultEntry.getValue().isPassed()) {
passedResults.add(resultEntry.getKey());
} else {
failedResults.add(resultEntry.getKey());
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
options.setEnabled(false);
Dialogs.DialogAction failButton = new Dialogs.DialogAction("View Failed") {
@Override
public boolean performed(GDialog dialog) {
DocumentUtilities.selectDocuments(failedResults);
return true;
}
};
Dialogs.DialogAction passButton = new Dialogs.DialogAction("View Passed") {
@Override
public boolean performed(GDialog dialog) {
DocumentUtilities.selectDocuments(passedResults);
return true;
}
};
Dialogs.DialogOptions dialogOptions = new Dialogs.DialogOptions(new Dialogs.DialogAction[]{
Dialogs.OK, passButton, failButton}, "Validation Options");
dialogOptions.setCancelButton(Dialogs.OK);
Dialogs.showMoreOptionsDialog(dialogOptions, options.getPanel(), options.getAdvancedPanel());
}
});
}
public ValidationOptions getOptionAt(int columnIndex) {
assert records != null && records.size() > 0;
Map<Integer, ValidationOptions> colunmOptionsMap = records.get(0).getColunmOptionsMap(false);
assert colunmOptionsMap != null;
return colunmOptionsMap.get(columnIndex);
}
public Map<URN, RecordOfValidationResult> getResultsAt(int columnIndex) {
assert records != null && records.size() > 0;
Map<URN, RecordOfValidationResult> ret = new HashMap<URN, RecordOfValidationResult>();
Class aClass = records.get(0).getColunmClassMap(true).get(columnIndex);
for (ValidationOutputRecord record : records) {
ret.putAll(record.getValidationResultsMap().get(aClass));
}
return ret;
}
public int getFixedColumnLength() {
assert records != null && records.size() > 0;
ValidationOutputRecord record = records.get(0);
return record.getFixedColumns(record.getOneURN(), null).size();
}
}
}
|
package com.quickblox.sample.groupchatwebrtc.activities;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBSignaling;
import com.quickblox.chat.QBWebRTCSignaling;
import com.quickblox.chat.listeners.QBVideoChatSignalingManagerListener;
import com.quickblox.sample.core.utils.Toaster;
import com.quickblox.sample.groupchatwebrtc.R;
import com.quickblox.sample.groupchatwebrtc.db.QbUsersDbManager;
import com.quickblox.sample.groupchatwebrtc.fragments.BaseConversationFragment;
import com.quickblox.sample.groupchatwebrtc.fragments.AudioConversationFragment;
import com.quickblox.sample.groupchatwebrtc.fragments.VideoConversationFragment;
import com.quickblox.sample.groupchatwebrtc.fragments.ConversationFragmentCallbackListener;
import com.quickblox.sample.groupchatwebrtc.fragments.IncomeCallFragment;
import com.quickblox.sample.groupchatwebrtc.fragments.OnCallEventsController;
import com.quickblox.sample.groupchatwebrtc.fragments.IncomeCallFragmentCallbackListener;
import com.quickblox.sample.groupchatwebrtc.util.NetworkConnectionChecker;
import com.quickblox.sample.groupchatwebrtc.utils.Consts;
import com.quickblox.sample.groupchatwebrtc.utils.FragmentExecuotr;
import com.quickblox.sample.groupchatwebrtc.utils.QBEntityCallbackImpl;
import com.quickblox.sample.groupchatwebrtc.utils.RingtonePlayer;
import com.quickblox.sample.groupchatwebrtc.utils.SettingsUtil;
import com.quickblox.sample.groupchatwebrtc.utils.UsersUtils;
import com.quickblox.sample.groupchatwebrtc.utils.WebRtcSessionManager;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.webrtc.AppRTCAudioManager;
import com.quickblox.videochat.webrtc.QBRTCClient;
import com.quickblox.videochat.webrtc.QBRTCConfig;
import com.quickblox.videochat.webrtc.QBRTCSession;
import com.quickblox.videochat.webrtc.QBRTCTypes;
import com.quickblox.videochat.webrtc.QBSignalingSpec;
import com.quickblox.videochat.webrtc.callbacks.QBRTCClientSessionCallbacks;
import com.quickblox.videochat.webrtc.callbacks.QBRTCSessionConnectionCallbacks;
import com.quickblox.videochat.webrtc.callbacks.QBRTCSignalingCallback;
import com.quickblox.videochat.webrtc.exception.QBRTCException;
import com.quickblox.videochat.webrtc.exception.QBRTCSignalException;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.webrtc.VideoCapturerAndroid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* QuickBlox team
*/
public class CallActivity extends BaseActivity implements QBRTCClientSessionCallbacks, QBRTCSessionConnectionCallbacks, QBRTCSignalingCallback,
OnCallEventsController, IncomeCallFragmentCallbackListener, ConversationFragmentCallbackListener, NetworkConnectionChecker.OnConnectivityChangedListener {
private static final String TAG = CallActivity.class.getSimpleName();
public static final String OPPONENTS_CALL_FRAGMENT = "opponents_call_fragment";
public static final String INCOME_CALL_FRAGMENT = "income_call_fragment";
public static final String CONVERSATION_CALL_FRAGMENT = "conversation_call_fragment";
public static final String CALLER_NAME = "caller_name";
public static final String SESSION_ID = "sessionID";
public static final String START_CONVERSATION_REASON = "start_conversation_reason";
private QBRTCSession currentSession;
public List<QBUser> opponentsList;
private Runnable showIncomingCallWindowTask;
private Handler showIncomingCallWindowTaskHandler;
private boolean closeByWifiStateAllow = true;
private String hangUpReason;
private boolean isInCommingCall;
private QBRTCClient rtcClient;
private QBRTCSessionUserCallback sessionUserCallback;
private boolean wifiEnabled = true;
private SharedPreferences sharedPref;
private RingtonePlayer ringtonePlayer;
private LinearLayout connectionView;
private AppRTCAudioManager audioManager;
private NetworkConnectionChecker networkConnectionChecker;
private WebRtcSessionManager sessionManager;
private QbUsersDbManager dbManager;
private ArrayList<CurrentCallStateCallback> currentCallStateCallbackList = new ArrayList<>();
private List<Integer> opponentsIdsList;
private boolean callStarted;
private long expirationReconnectionTime;
private int reconnectHangUpTimeMillis;
public static void start(Context context,
boolean isIncomingCall) {
Intent intent = new Intent(context, CallActivity.class);
intent.putExtra(Consts.EXTRA_IS_INCOMING_CALL, isIncomingCall);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parceIntentExtras();
if (!initFields()) {
// we have currentSession == null, so it's no reason to do further initialisation
finish();
Log.d(TAG, "finish CallActivity");
return;
}
initCurrentSession(currentSession);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
initQBRTCClient();
initAudioManager();
initWiFiManagerListener();
ringtonePlayer = new RingtonePlayer(this, R.raw.beep);
connectionView = (LinearLayout) View.inflate(this, R.layout.connection_popup, null);
startSuitableFragment(isInCommingCall);
}
private void startSuitableFragment(boolean isInComingCall) {
if (isInComingCall) {
initIncommingCallTask();
startLoadAbsentUsers();
addIncomeCallFragment();
} else {
addConversationFragment(isInComingCall);
}
}
private void startLoadAbsentUsers() {
ArrayList<QBUser> usersFromDb = dbManager.getAllUsers();
ArrayList<Integer> allParticipantsOfCall = new ArrayList<>();
allParticipantsOfCall.addAll(opponentsIdsList);
if (isInCommingCall) {
allParticipantsOfCall.add(currentSession.getCallerID());
}
ArrayList<Integer> idsUsersNeedLoad = UsersUtils.getIdsNotLoadedUsers(usersFromDb, allParticipantsOfCall);
if (!idsUsersNeedLoad.isEmpty()) {
requestExecutor.loadUsersByIds(idsUsersNeedLoad, new QBEntityCallbackImpl<ArrayList<QBUser>>() {
@Override
public void onSuccess(ArrayList<QBUser> result, Bundle params) {
dbManager.saveAllUsers(result, false);
needUpdateOpponentsList(result);
}
});
}
}
private void needUpdateOpponentsList(ArrayList<QBUser> newUsers) {
notifyCallStateListenersNeedUpdateOpponentsList(newUsers);
}
private boolean initFields() {
sessionManager = WebRtcSessionManager.getInstance(this);
dbManager = QbUsersDbManager.getInstance(getApplicationContext());
currentSession = sessionManager.getCurrentSession();
if (currentSession == null) {
return false;
}
opponentsIdsList = currentSession.getOpponents();
return true;
}
@Override
protected View getSnackbarAnchorView() {
return null;
}
private void parceIntentExtras() {
isInCommingCall = getIntent().getExtras().getBoolean(Consts.EXTRA_IS_INCOMING_CALL);
}
private void initAudioManager() {
audioManager = AppRTCAudioManager.create(this, new AppRTCAudioManager.OnAudioManagerStateListener() {
@Override
public void onAudioChangedState(AppRTCAudioManager.AudioDevice audioDevice) {
if (callStarted) {
Toaster.shortToast("Audio device switched to " + audioDevice);
}
}
});
audioManager.setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
audioManager.setOnWiredHeadsetStateListener(new AppRTCAudioManager.OnWiredHeadsetStateListener() {
@Override
public void onWiredHeadsetStateChanged(boolean plugged, boolean hasMicrophone) {
if (callStarted) {
Toaster.shortToast("Headset " + (plugged ? "plugged" : "unplugged"));
}
if (sessionUserCallback != null) {
sessionUserCallback.enableDynamicToggle(plugged);
}
}
});
audioManager.init();
}
private void initQBRTCClient() {
rtcClient = QBRTCClient.getInstance(this);
// Add signalling manager
QBChatService.getInstance().getVideoChatWebRTCSignalingManager().addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
@Override
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally) {
if (!createdLocally) {
rtcClient.addSignaling((QBWebRTCSignaling) qbSignaling);
}
}
});
rtcClient.setCameraErrorHendler(new VideoCapturerAndroid.CameraErrorHandler() {
@Override
public void onCameraError(final String s) {
CallActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toaster.longToast(s);
}
});
}
});
// Configure
QBRTCConfig.setMaxOpponentsCount(Consts.MAX_OPPONENTS_COUNT);
SettingsUtil.setSettingsStrategy(opponentsIdsList, sharedPref, CallActivity.this);
SettingsUtil.configRTCTimers(CallActivity.this);
QBRTCConfig.setDebugEnabled(true);
// Add activity as callback to RTCClient
rtcClient.addSessionCallbacksListener(this);
// Start mange QBRTCSessions according to VideoCall parser's callbacks
rtcClient.prepareToProcessCalls();
QBChatService.getInstance().addConnectionListener(new AbstractConnectionListener() {
@Override
public void connectionClosedOnError(Exception e) {
showNotificationPopUp(R.string.connection_was_lost, true);
setExpirationReconnectionTime();
}
@Override
public void reconnectionSuccessful() {
showNotificationPopUp(R.string.connection_was_lost, false);
}
@Override
public void reconnectingIn(int seconds) {
Log.i(TAG, "reconnectingIn " + seconds);
hangUpAfterLongReconnection();
}
});
}
private void setExpirationReconnectionTime() {
reconnectHangUpTimeMillis = SettingsUtil.getPreferenceInt(sharedPref, this, R.string.pref_disconnect_time_interval_key,
R.string.pref_disconnect_time_interval_default_value) * 1000;
expirationReconnectionTime = System.currentTimeMillis() + reconnectHangUpTimeMillis;
}
private void hangUpAfterLongReconnection() {
if (expirationReconnectionTime < System.currentTimeMillis()) {
hangUpCurrentSession();
}
}
@Override
public void connectivityChanged(boolean availableNow) {
if (callStarted) {
showToast("Internet connection " + (availableNow ? "available" : " unavailable"));
}
}
private void showNotificationPopUp(final int text, final boolean show) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (show) {
((TextView) connectionView.findViewById(R.id.notification)).setText(text);
if (connectionView.getParent() == null) {
((ViewGroup) CallActivity.this.findViewById(R.id.fragment_container)).addView(connectionView);
}
} else {
((ViewGroup) CallActivity.this.findViewById(R.id.fragment_container)).removeView(connectionView);
}
}
});
}
private void initWiFiManagerListener() {
networkConnectionChecker = new NetworkConnectionChecker(getApplication());
}
private void initIncommingCallTask() {
showIncomingCallWindowTaskHandler = new Handler(Looper.myLooper());
showIncomingCallWindowTask = new Runnable() {
@Override
public void run() {
if (currentSession == null) {
return;
}
QBRTCSession.QBRTCSessionState currentSessionState = currentSession.getState();
if (QBRTCSession.QBRTCSessionState.QB_RTC_SESSION_NEW.equals(currentSessionState)) {
rejectCurrentSession();
} else {
ringtonePlayer.stop();
hangUpCurrentSession();
}
Toaster.longToast("Call was stopped by timer");
}
};
}
private QBRTCSession getCurrentSession() {
return currentSession;
}
public void rejectCurrentSession() {
if (getCurrentSession() != null) {
getCurrentSession().rejectCall(new HashMap<String, String>());
}
}
public void hangUpCurrentSession() {
ringtonePlayer.stop();
if (getCurrentSession() != null) {
getCurrentSession().hangUp(new HashMap<String, String>());
}
}
private void setAudioEnabled(boolean isAudioEnabled) {
if (currentSession != null && currentSession.getMediaStreamManager() != null) {
currentSession.getMediaStreamManager().setAudioEnabled(isAudioEnabled);
}
}
private void setVideoEnabled(boolean isVideoEnabled) {
if (currentSession != null && currentSession.getMediaStreamManager() != null) {
currentSession.getMediaStreamManager().setVideoEnabled(isVideoEnabled);
}
}
private void startIncomeCallTimer(long time) {
showIncomingCallWindowTaskHandler.postAtTime(showIncomingCallWindowTask, SystemClock.uptimeMillis() + time);
}
private void stopIncomeCallTimer() {
Log.d(TAG, "stopIncomeCallTimer");
showIncomingCallWindowTaskHandler.removeCallbacks(showIncomingCallWindowTask);
}
@Override
protected void onResume() {
super.onResume();
networkConnectionChecker.registerListener(this);
}
@Override
protected void onPause() {
super.onPause();
networkConnectionChecker.unregisterListener(this);
}
@Override
protected void onStop() {
super.onStop();
}
private void forbiddenCloseByWifiState() {
closeByWifiStateAllow = false;
}
public void initCurrentSession(QBRTCSession session) {
if (session != null) {
Log.d(TAG, "Init new QBRTCSession");
this.currentSession = session;
this.currentSession.addSessionCallbacksListener(CallActivity.this);
this.currentSession.addSignalingCallback(CallActivity.this);
}
}
public void releaseCurrentSession() {
Log.d(TAG, "Release current session");
if (currentSession != null) {
this.currentSession.removeSessionCallbacksListener(CallActivity.this);
this.currentSession.removeSignalingCallback(CallActivity.this);
rtcClient.removeSessionsCallbacksListener(CallActivity.this);
this.currentSession = null;
}
}
@Override
public void onReceiveNewSession(final QBRTCSession session) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Session " + session.getSessionID() + " are income");
if (getCurrentSession() != null) {
Log.d(TAG, "Stop new session. Device now is busy");
session.rejectCall(null);
}
}
});
}
@Override
public void onUserNotAnswer(QBRTCSession session, Integer userID) {
if (!session.equals(getCurrentSession())) {
return;
}
if (sessionUserCallback != null) {
sessionUserCallback.onUserNotAnswer(session, userID);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ringtonePlayer.stop();
}
});
}
@Override
public void onUserNoActions(QBRTCSession qbrtcSession, Integer integer) {
startIncomeCallTimer(0);
}
@Override
public void onStartConnectToUser(QBRTCSession session, Integer userID) {
}
@Override
public void onCallAcceptByUser(QBRTCSession session, Integer userId, Map<String, String> userInfo) {
if (!session.equals(getCurrentSession())) {
return;
}
if (sessionUserCallback != null) {
sessionUserCallback.onCallAcceptByUser(session, userId, userInfo);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ringtonePlayer.stop();
}
});
}
@Override
public void onCallRejectByUser(QBRTCSession session, Integer userID, Map<String, String> userInfo) {
if (!session.equals(getCurrentSession())) {
return;
}
if (sessionUserCallback != null) {
sessionUserCallback.onCallRejectByUser(session, userID, userInfo);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ringtonePlayer.stop();
}
});
}
@Override
public void onConnectionClosedForUser(QBRTCSession session, Integer userID) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Close app after session close of network was disabled
if (hangUpReason != null && hangUpReason.equals(Consts.WIFI_DISABLED)) {
Intent returnIntent = new Intent();
setResult(Consts.CALL_ACTIVITY_CLOSE_WIFI_DISABLED, returnIntent);
finish();
}
}
});
}
@Override
public void onConnectedToUser(QBRTCSession session, final Integer userID) {
callStarted = true;
notifyCallStateListenersCallStarted();
forbiddenCloseByWifiState();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (isInCommingCall) {
stopIncomeCallTimer();
}
Log.d(TAG, "onConnectedToUser() is started");
}
});
}
@Override
public void onDisconnectedTimeoutFromUser(QBRTCSession session, Integer userID) {
}
@Override
public void onConnectionFailedWithUser(QBRTCSession session, Integer userID) {
}
@Override
public void onError(QBRTCSession qbrtcSession, QBRTCException e) {
}
@Override
public void onSessionClosed(final QBRTCSession session) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Session " + session.getSessionID() + " start stop session");
if (session.equals(getCurrentSession())) {
Log.d(TAG, "Stop session");
if (audioManager != null) {
audioManager.close();
}
releaseCurrentSession();
closeByWifiStateAllow = true;
finish();
}
}
});
}
@Override
public void onSessionStartClose(final QBRTCSession session) {
if (session.equals(getCurrentSession())) {
session.removeSessionCallbacksListener(CallActivity.this);
notifyCallStateListenersCallStopped();
}
}
@Override
public void onDisconnectedFromUser(QBRTCSession session, Integer userID) {
}
private void showToast(final int message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toaster.shortToast(message);
}
});
}
private void showToast(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toaster.shortToast(message);
}
});
}
@Override
public void onReceiveHangUpFromUser(final QBRTCSession session, final Integer userID, Map<String, String> map) {
if (session.equals(getCurrentSession())) {
if (sessionUserCallback != null) {
sessionUserCallback.onReceiveHangUpFromUser(session, userID);
}
QBUser participant = dbManager.getUserById(userID);
final String participantName = participant != null ? participant.getFullName() : String.valueOf(userID);
runOnUiThread(new Runnable() {
@Override
public void run() {
showToast("User " + participantName + " " + getString(R.string.text_status_hang_up) + " conversation");
}
});
}
}
private Fragment getCurrentFragment() {
return getFragmentManager().findFragmentById(R.id.fragment_container);
}
private void addIncomeCallFragment() {
Log.d(TAG, "QBRTCSession in addIncomeCallFragment is " + currentSession);
if (currentSession != null) {
IncomeCallFragment fragment = new IncomeCallFragment();
FragmentExecuotr.addFragment(getFragmentManager(), R.id.fragment_container, fragment, INCOME_CALL_FRAGMENT);
} else {
Log.d(TAG, "SKIP addIncomeCallFragment method");
}
}
private void addConversationFragment(boolean isIncomingCall) {
boolean isVideoCall = QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO.equals(currentSession.getConferenceType());
BaseConversationFragment conversationFragment = BaseConversationFragment.newInstance(
isVideoCall
? new VideoConversationFragment()
: new AudioConversationFragment(),
isIncomingCall);
FragmentExecuotr.addFragment(getFragmentManager(), R.id.fragment_container, conversationFragment, CONVERSATION_CALL_FRAGMENT);
}
public SharedPreferences getDefaultSharedPrefs() {
return sharedPref;
}
@Override
public void onSuccessSendingPacket(QBSignalingSpec.QBSignalCMD qbSignalCMD, Integer integer) {
}
@Override
public void onErrorSendingPacket(QBSignalingSpec.QBSignalCMD qbSignalCMD, Integer userId, QBRTCSignalException e) {
showToast(R.string.dlg_signal_error);
}
public void onUseHeadSet(boolean use) {
audioManager.setManageHeadsetByDefault(use);
}
////////////////////////////// IncomeCallFragmentCallbackListener ////////////////////////////
@Override
public void onAcceptCurrentSession() {
addConversationFragment(true);
}
@Override
public void onRejectCurrentSession() {
rejectCurrentSession();
}
////////////////////////////////////////// end /////////////////////////////////////////////
@Override
public void onBackPressed() {
}
@Override
protected void onDestroy() {
super.onDestroy();
}
////////////////////////////// ConversationFragmentCallbackListener ////////////////////////////
@Override
public void addTCClientConnectionCallback(QBRTCSessionConnectionCallbacks clientConnectionCallbacks) {
if (currentSession != null) {
currentSession.addSessionCallbacksListener(clientConnectionCallbacks);
}
}
@Override
public void addRTCSessionUserCallback(QBRTCSessionUserCallback sessionUserCallback) {
this.sessionUserCallback = sessionUserCallback;
}
@Override
public void onSetAudioEnabled(boolean isAudioEnabled) {
setAudioEnabled(isAudioEnabled);
}
@Override
public void onHangUpCurrentSession() {
hangUpCurrentSession();
}
@Override
public void onSetVideoEnabled(boolean isNeedEnableCam) {
setVideoEnabled(isNeedEnableCam);
}
@Override
public void onSwitchAudio() {
if (audioManager.getSelectedAudioDevice() == AppRTCAudioManager.AudioDevice.WIRED_HEADSET
|| audioManager.getSelectedAudioDevice() == AppRTCAudioManager.AudioDevice.EARPIECE) {
audioManager.setAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
} else {
audioManager.setAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
}
}
@Override
public void removeRTCClientConnectionCallback(QBRTCSessionConnectionCallbacks clientConnectionCallbacks) {
if (currentSession != null) {
currentSession.removeSessionCallbacksListener(clientConnectionCallbacks);
}
}
@Override
public void removeRTCSessionUserCallback(QBRTCSessionUserCallback sessionUserCallback) {
this.sessionUserCallback = null;
}
@Override
public void addCurrentCallStateCallback(CurrentCallStateCallback currentCallStateCallback) {
currentCallStateCallbackList.add(currentCallStateCallback);
}
@Override
public void removeCurrentCallStateCallback(CurrentCallStateCallback currentCallStateCallback) {
currentCallStateCallbackList.remove(currentCallStateCallback);
}
////////////////////////////////////////// end /////////////////////////////////////////////
public interface QBRTCSessionUserCallback {
void enableDynamicToggle(boolean plugged);
void onUserNotAnswer(QBRTCSession session, Integer userId);
void onCallRejectByUser(QBRTCSession session, Integer userId, Map<String, String> userInfo);
void onCallAcceptByUser(QBRTCSession session, Integer userId, Map<String, String> userInfo);
void onReceiveHangUpFromUser(QBRTCSession session, Integer userId);
}
public interface CurrentCallStateCallback {
void onCallStarted();
void onCallStopped();
void onOpponentsListUpdated(ArrayList<QBUser> newUsers);
}
private void notifyCallStateListenersCallStarted() {
runOnUiThread(new Runnable() {
@Override
public void run() {
for (CurrentCallStateCallback callback : currentCallStateCallbackList) {
callback.onCallStarted();
}
}
});
}
private void notifyCallStateListenersCallStopped() {
runOnUiThread(new Runnable() {
@Override
public void run() {
for (CurrentCallStateCallback callback : currentCallStateCallbackList) {
callback.onCallStopped();
}
}
});
}
private void notifyCallStateListenersNeedUpdateOpponentsList(final ArrayList<QBUser> newUsers) {
runOnUiThread(new Runnable() {
@Override
public void run() {
for (CurrentCallStateCallback callback : currentCallStateCallbackList) {
callback.onOpponentsListUpdated(newUsers);
}
}
});
}
}
|
package org.sakai.search.index.impl.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.sakaiproject.search.index.impl.ClusterFSIndexStorage;
import org.sakaiproject.search.index.impl.JDBCClusterIndexStore;
import org.sakaiproject.search.index.impl.SnowballAnalyzerFactory;
public class ClusterFSIndexStorageEclipsetest extends TestCase
{
private static final Log log = LogFactory
.getLog(ClusterFSIndexStorageEclipsetest.class);
ClusterFSIndexStorage cfs = null;
JDBCClusterIndexStore cis = null;
BasicDataSource dataSource;
private String dbtype = "hsqldb";
private int docnum = 0;
protected void setUp() throws Exception
{
super.setUp();
if (dbtype.equals("hsqldb"))
{
Properties properties = new Properties();
properties.setProperty("driverClassName", "org.hsqldb.jdbcDriver");
properties.setProperty("url", "jdbc:hsqldb:mem:search-test");
properties.setProperty("maxActive", "10");
properties.setProperty("maxWait", "500");
properties.setProperty("defaultAutoCommit", "false");
properties.setProperty("defaultReadOnly", "false");
properties.setProperty("username", "sa");
properties.setProperty("password", "");
properties.setProperty("validationQuery",
"select 1 from SYSTEM_USERS");
dataSource = (BasicDataSource) BasicDataSourceFactory
.createDataSource(properties);
cis = new JDBCClusterIndexStore();
cis.setDataSource(dataSource);
Connection c = dataSource.getConnection();
Statement s = c.createStatement();
try
{
s.execute("CREATE TABLE search_segments " + "("
+ " name_ varchar(255) not null,"
+ " version_ BIGINT not null,"
+ " size_ BIGINT not null"
+ " packet_ BINARY,"
+ " CONSTRAINT search_segments_index UNIQUE (name_)"
+ "); ");
}
catch (Exception ex)
{
ex.printStackTrace();
}
s.close();
c.close();
}
if (dbtype.equals("mysql"))
{
Properties properties = new Properties();
properties.setProperty("driverClassName", "com.mysql.jdbc.Driver");
properties
.setProperty("url",
"jdbc:mysql://127.0.0.1:3306/sakai22?useUnicode=true&characterEncoding=UTF-8");
properties.setProperty("maxActive", "10");
properties.setProperty("maxWait", "500");
properties.setProperty("defaultAutoCommit", "false");
properties.setProperty("defaultReadOnly", "false");
properties.setProperty("defaultTransactionIsolation",
"READ_COMMITTED");
properties.setProperty("username", "sakai22");
properties.setProperty("password", "sakai22");
properties.setProperty("validationQuery", "select 1 from DUAL");
dataSource = (BasicDataSource) BasicDataSourceFactory
.createDataSource(properties);
cis = new JDBCClusterIndexStore();
cis.setDataSource(dataSource);
Connection c = dataSource.getConnection();
Statement s = c.createStatement();
try
{
s.execute("CREATE TABLE search_segments" + " ("
+ " name_ varchar(255) not null,"
+ " version_ BIGINT not null,"
+ " size_ BIGINT not null,"
+ " packet_ LONGBLOB" + " );");
s
.execute("CREATE UNIQUE INDEX search_segments_index ON search_segments"
+ " (" + " name_" + " );");
}
catch (Exception ex)
{
}
s.close();
c.close();
}
cfs = new ClusterFSIndexStorage();
cfs.setAnalyzerFactory(new SnowballAnalyzerFactory());
cfs.setClusterFS(cis);
cfs.setLocation("tmpindexstore");
}
protected void tearDown() throws Exception
{
dataSource.close();
super.tearDown();
}
public void disabled_testAAASaveAllSegments() throws Exception
{
cis.saveAllSegments();
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.getIndexReader()'
*/
public void testGetIndexReader() throws Exception
{
IndexReader ir = cfs.getIndexReader();
assertNotNull(ir);
ir.numDocs();
ir.close();
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.getIndexWriter(boolean)'
*/
public void testGetIndexWriter() throws Exception
{
cfs.doPreIndexUpdate();
IndexWriter iw = cfs.getIndexWriter(false);
assertNotNull(iw);
Document doc = new Document();
doc.add(new Field("id", String.valueOf(System.currentTimeMillis()),
Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.add(new Field("contents", "some content about something",
Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("name", "AName", Field.Store.YES,
Field.Index.UN_TOKENIZED));
iw.addDocument(doc);
iw.close();
cfs.doPostIndexUpdate();
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.getIndexSearcher()'
*/
public void testGetIndexSearcher() throws Exception
{
IndexSearcher is = cfs.getIndexSearcher();
assertNotNull(is);
BooleanQuery query = new BooleanQuery();
QueryParser qp = new QueryParser("contents", cfs.getAnalyzer());
Query textQuery = qp.parse("about");
query.add(textQuery, BooleanClause.Occur.MUST);
log.info("Query is " + query.toString());
Hits h = is.search(query);
log.info("Got " + h.length() + " hits");
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.indexExists()'
*/
public void testIndexExists()
{
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.getAnalyzer()'
*/
public void testGetAnalyzer()
{
assertNotNull(cfs.getAnalyzer());
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.doPreIndexUpdate()'
*/
public void testDoPreIndexUpdate()
{
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.doPostIndexUpdate()'
*/
public void testDoPostIndexUpdate()
{
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.getAnalyzerFactory()'
*/
public void testGetAnalyzerFactory()
{
assertNotNull(cfs.getAnalyzerFactory());
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.setAnalyzerFactory(AnalyzerFactory)'
*/
public void testSetAnalyzerFactory()
{
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.setRecoverCorruptedIndex(boolean)'
*/
public void testSetRecoverCorruptedIndex()
{
}
/*
* Test method for
* 'org.sakaiproject.search.index.impl.ClusterFSIndexStorage.setClusterFS(ClusterFilesystem)'
*/
public void testSetClusterFS()
{
}
public void testXBigTest() throws Exception
{
docnum = 0;
cfs.doPreIndexUpdate();
IndexWriter iw = cfs.getIndexWriter(false);
File f = new File("testcontent");
iw = loadDocuments(f, iw);
iw.close();
cfs.doPostIndexUpdate();
}
private IndexWriter reopen(IndexWriter iw) throws IOException, ParseException {
log.info("Optimize===============");
iw.optimize();
iw.close();
iw = null;
cfs.doPostIndexUpdate();
log.info("Query==================");
long start = System.currentTimeMillis();
IndexSearcher is = cfs.getIndexSearcher();
log.info("----Open took "+(System.currentTimeMillis()-start));
start = System.currentTimeMillis();
BooleanQuery query = new BooleanQuery();
QueryParser qp = new QueryParser("contents", cfs.getAnalyzer());
Query textQuery = qp.parse("sakai");
query.add(textQuery, BooleanClause.Occur.MUST);
log.info("Query is " + query.toString());
Hits h = is.search(query);
log.info("Got " + h.length() + " hits in "+(System.currentTimeMillis()-start)+" ms");
log.info("Reopen=================");
cfs.doPreIndexUpdate();
iw = cfs.getIndexWriter(false);
log.info("Indexing===============");
return iw;
}
private IndexWriter loadDocuments(File f, IndexWriter iw) throws IOException, ParseException
{
if (f.isDirectory())
{
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
{
iw = loadDocuments(files[i], iw);
}
else
{
iw = loadDocument(files[i], iw);
}
}
}
else
{
iw = loadDocument(f, iw);
}
return iw;
}
private IndexWriter loadDocument(File file, IndexWriter iw) throws IOException, ParseException
{
docnum++;
if ( (docnum%20) == 0 ) {
iw = reopen(iw);
}
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuffer sb = new StringBuffer();
String s = null;
while ((sb.length() < 1000000) && (s = br.readLine()) != null )
{
sb.append(s).append("\n");
}
Document doc = new Document();
doc.add(new Field("name", file.getAbsolutePath(), Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field("contents", sb.toString(), Field.Store.YES,
Field.Index.TOKENIZED));
iw.addDocument(doc);
return iw;
}
}
|
package com.lackbeard.capn.ish;
import android.text.format.Time;
import android.util.Log;
import java.util.Random;
public class RoughTimeConverter {
public RoughTimeConverter() {
}
private String[] hourWords = {"twelve", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"};
private String[] minuteWords = {"", "ten past", "twenty", "thirty", "twenty to", "ten to"};
private String[] beforeWords = {"almost", "nearly"};
private String[] afterWords = {"just gone"};
private String convertHourToWord(int src) {
if (src == 0) {
//TODO: special 'noon' and 'midnight' stuff?
return "twelve";
} else {
return hourWords[(src % 12)];
}
}
//NB: assumes you've already rounded the minutea to nearest ten - likely to change
private String convertMinuteToWord(int src) {
return minuteWords[src / 10];
}
private String getRandomStringFromArray(String[] array) {
Random rng = new Random();
return array[rng.nextInt(array.length)];
}
private boolean isAlmostSpecial(int hour, int minute) {
if ((hour % 12 == 0 && minute < 5)
|| (hour % 12 == 11 && minute > 55)) {
return true;
}
return false;
}
private String getIshString(int minutesSinceLastMarker) {
if (minutesSinceLastMarker == 0) {
return "";
} else if (minutesSinceLastMarker < 5) {
return getRandomStringFromArray(afterWords);
} else /*if (minutesSinceLastMarker >= 5)*/ {
return getRandomStringFromArray(beforeWords);
}
}
public RoughTime convertToRoughTime(Time exact) {
RoughTime ret = new RoughTime();
int hourToUse = exact.hour;
//make sure to use next hour if using a 'to'
if (exact.minute >= 35) {
hourToUse++;
}
//work out whether to display 'almost' or 'just gone'
int minutesSincePreviousMarker = exact.minute % 10;
Log.i("minuteConversion", "minutes since: " + minutesSincePreviousMarker);
//deal with special cases - noon and midnight
if (isAlmostSpecial(exact.hour, exact.minute)) {
Log.i("roughTime", "special time found");
if (hourToUse % 12 == 0) {
ret.setHourString("midnight");
} else {
ret.setHourString("noon");
};
ret.setMinuteString("");
ret.setIshString(getIshString(minutesSincePreviousMarker));
return ret;
}
//if minutes >= 3, then the minutes go BEFORE the words
// i.e. "nearly twenty to ten" (not "nearly ten twenty to"!)
if (exact.minute >= 35 ||
(exact.minute >= 5 && exact.minute < 15)) {
ret.setMinutesBeforeHours(true);
}
if (minutesSincePreviousMarker == 0) {
ret.setMinuteString(convertMinuteToWord(exact.minute));
ret.setHourString(convertHourToWord(hourToUse));
ret.setIshString(getIshString(minutesSincePreviousMarker));
} else if (minutesSincePreviousMarker < 5) {
ret.setMinuteString(convertMinuteToWord(10 * (exact.minute / 10)));
ret.setHourString(convertHourToWord(hourToUse));
ret.setIshString(getIshString(minutesSincePreviousMarker));
} else /*if (minutesSincePreviousMarker >= 5)*/ {
//special case to deal with mins > 55 i.e. need to display next hour - "nearly 12" at 11:55
int tensOfMinutesElapsed = 1 + (exact.minute / 10);
// if (tensOfMinutesElapsed == 6) {
// ret.setHourString(convertHourToWord(hourToUse));
// ret.setMinuteString(convertMinuteToWord((10 * tensOfMinutesElapsed) % 60));
// } else {
ret.setHourString(convertHourToWord(hourToUse));
ret.setMinuteString(convertMinuteToWord((10 * (exact.minute / 10))));
ret.setIshString(getIshString(minutesSincePreviousMarker));
}
//should probably throw an exception if something goes wrong, //TODO
return ret;
}
}
|
package com.atlassian.jira.ext.commitacceptance.server.evaluator.predicate;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.user.preferences.PreferenceKeys;
import com.atlassian.jira.user.preferences.JiraUserPreferences;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.web.bean.I18nBean;
import com.atlassian.jira.web.util.JiraLocaleUtils;
import com.opensymphony.user.User;
import java.util.ResourceBundle;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
public abstract class AbstractPredicate implements JiraPredicate {
private I18nBean i18nBean;
protected JiraAuthenticationContext getJiraAuthenticationContext() {
return ComponentManager.getInstance().getJiraAuthenticationContext();
}
protected I18nBean getI18nBean() {
if (null == i18nBean) {
i18nBean = new I18nBean(getJiraAuthenticationContext().getUser());
i18nBean.addBundle(
ResourceBundle.getBundle(
"templates.commitacceptance-plugin",
getLocaleFromUser(getJiraAuthenticationContext().getUser())
)
);
}
return i18nBean;
}
private Locale getLocaleFromUser(final User user)
{
if (user != null)
{
final JiraUserPreferences userPrefs = new JiraUserPreferences(user, false);
final String localeStr = userPrefs.getString(PreferenceKeys.USER_LOCALE);
if (!StringUtils.isBlank(localeStr))
{
return JiraLocaleUtils.parseLocale(localeStr);
}
}
return ComponentManager.getInstance().getApplicationProperties().getDefaultLocale();
}
}
|
package me.ferrybig.javacoding.teamspeakconnector.internal.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import me.ferrybig.javacoding.teamspeakconnector.RateLimit;
import me.ferrybig.javacoding.teamspeakconnector.internal.packets.ComplexRequest;
/**
* Handler to rate limit the maximum packets per second
* @author Fernando
*/
public class PacketRateLimitingHandler extends ChannelTrafficShapingHandler {
private final RateLimit rateLimit;
public PacketRateLimitingHandler(RateLimit rateLimit) {
super(0, 0, 1000);
this.rateLimit = rateLimit;
}
@Override
protected long calculateSize(Object msg) {
// Assume size of 1000 B for all packets so this handler can use a
// max "packet" per seconds instead
return msg instanceof ComplexRequest ? 1000 : 0;
}
private void adjustRateLimits(ChannelHandlerContext ctx) {
this.setPacketsPerSeconds(rateLimit
.maxPacketsPerSecond(ctx.channel().remoteAddress()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
super.handlerAdded(ctx);
if (ctx.channel().isActive()) {
adjustRateLimits(ctx);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
adjustRateLimits(ctx);
}
public void setPacketsPerSeconds(double packetsPerMiliseconds) {
this.setWriteLimit((int) (packetsPerMiliseconds * 1000));
}
}
|
package com.blogspot.mydailyjava.bytebuddy.method.bytecode.bind;
import org.hamcrest.BaseMatcher;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.mockito.Mockito.*;
public class MostSpecificTypeResolverTest extends AbstractAmbiguityResolverTest {
private static class IndexTokenMatcher extends BaseMatcher<MostSpecificTypeResolver.ParameterIndexToken> {
private final int index;
private IndexTokenMatcher(int index) {
assert index >= 0;
this.index = index;
}
@Override
public boolean matches(Object item) {
return new MostSpecificTypeResolver.ParameterIndexToken(index).equals(item);
}
@Override
public void describeTo(Description description) {
description.appendText("Expected matching token for parameter index ").appendValue(index);
}
}
private static Matcher<? super MostSpecificTypeResolver.ParameterIndexToken> describesArgument(int... index) {
Matcher<? super MostSpecificTypeResolver.ParameterIndexToken> token = CoreMatchers.anything();
for (int anIndex : index) {
token = anyOf(new IndexTokenMatcher(anIndex), token);
}
return token;
}
private static class TokenAnswer implements Answer<Integer> {
private final Map<MostSpecificTypeResolver.ParameterIndexToken, Integer> indexMapping;
private TokenAnswer(int[][] mapping) {
Map<MostSpecificTypeResolver.ParameterIndexToken, Integer> indexMapping = new HashMap<MostSpecificTypeResolver.ParameterIndexToken, Integer>();
for (int[] entry : mapping) {
assert entry.length == 2;
assert entry[0] >= 0;
assert entry[1] >= 0;
Object override = indexMapping.put(new MostSpecificTypeResolver.ParameterIndexToken(entry[0]), entry[1]);
assert override == null;
}
this.indexMapping = Collections.unmodifiableMap(indexMapping);
}
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
assert invocation.getArguments().length == 1;
return indexMapping.get(invocation.getArguments()[0]);
}
}
@Test
public void testMethodWithoutArguments() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[0]);
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution.isUnresolved(), is(true));
verify(source, atLeast(1)).getParameterTypes();
verifyZeroInteractions(left);
verifyZeroInteractions(right);
}
@Test
public void testMethodWithoutSeveralUnmappedArguments() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Void.class, Void.class, Void.class});
when(left.getBindingIndex(any())).thenReturn(null);
when(right.getBindingIndex(any())).thenReturn(null);
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.AMBIGUOUS));
verify(source, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(2)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0, 1, 2))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(2)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0, 1, 2))));
}
@Test
public void testMethodWithoutMappedArguments() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Number.class});
when(left.getBindingIndex(argThat(describesArgument(0)))).thenReturn(null);
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{Object.class});
when(right.getBindingIndex(argThat(describesArgument(0)))).thenReturn(null);
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.AMBIGUOUS));
verify(source, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0))));
}
@Test
public void testLeftMethodDominantByType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Number.class, null});
when(left.getBindingIndex(any())).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{null, Object.class});
when(right.getBindingIndex(any())).thenAnswer(new TokenAnswer(new int[][]{{0, 1}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.LEFT));
verify(source, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0))));
}
@Test
public void testRightMethodDominantByType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Object.class, null});
when(left.getBindingIndex(any())).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{null, Number.class});
when(right.getBindingIndex(any())).thenAnswer(new TokenAnswer(new int[][]{{0, 1}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.RIGHT));
verify(source, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0))));
}
@Test
public void testAmbiguousByCrossAssignableType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Number.class});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{Number.class});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.AMBIGUOUS));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0))));
}
@Test
public void testAmbiguousByNonCrossAssignableType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Class.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{GenericDeclaration.class});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{Type.class});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.AMBIGUOUS));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0))));
}
@Test
public void testAmbiguousByDifferentIndexedAssignableType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, Object.class});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}, {1, 1}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{Object.class, Integer.class});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}, {1, 1}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.AMBIGUOUS));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
}
@Test
public void testLeftMethodDominantByScore() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, Integer.class});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}, {1, 1}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, null});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.LEFT));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
}
@Test
public void testRightMethodDominantByScore() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, Integer.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, null});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{Integer.class, Integer.class});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}, {1, 1}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.RIGHT));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
}
@Test
public void testLeftMethodDominantForPrimitiveType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{int.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{int.class});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{long.class});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.LEFT));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
}
@Test
public void testRightMethodDominantForPrimitiveType() throws Exception {
when(source.getParameterTypes()).thenReturn(new Class<?>[]{int.class});
when(leftMethod.getParameterTypes()).thenReturn(new Class<?>[]{long.class});
when(left.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
when(rightMethod.getParameterTypes()).thenReturn(new Class<?>[]{int.class});
when(right.getBindingIndex(any(MostSpecificTypeResolver.ParameterIndexToken.class))).thenAnswer(new TokenAnswer(new int[][]{{0, 0}}));
MethodDelegationBinder.AmbiguityResolver.Resolution resolution = MostSpecificTypeResolver.INSTANCE.resolve(source, left, right);
assertThat(resolution, is(MethodDelegationBinder.AmbiguityResolver.Resolution.RIGHT));
verify(source, atLeast(1)).getParameterTypes();
verify(leftMethod, atLeast(1)).getParameterTypes();
verify(rightMethod, atLeast(1)).getParameterTypes();
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(left, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(left, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(0)));
verify(right, atLeast(1)).getBindingIndex(argThat(describesArgument(1)));
verify(right, never()).getBindingIndex(argThat(not(describesArgument(0, 1))));
}
}
|
package gtd.grammar.symbols;
public class Choice extends AbstractSymbol{
public final AbstractSymbol[] symbols;
public Choice(AbstractSymbol... symbols){
super(generateName(symbols));
this.symbols = symbols;
}
private static String generateName(AbstractSymbol[] symbols){
StringBuilder nameBuilder = new StringBuilder();
nameBuilder.append("choice(");
nameBuilder.append(symbols[0].name);
for(int i = 1; i < symbols.length; ++i){
nameBuilder.append(',');
nameBuilder.append(symbols[i].name);
}
nameBuilder.append(')');
return nameBuilder.toString();
}
public int hashCode(){
int hashCode = 7;
for(int i = symbols.length - 1; i >= 0; --i){
int symbolHashCode = symbols.hashCode();
hashCode ^= symbolHashCode << 15 | symbolHashCode >>> 17;
}
return hashCode;
}
public boolean equals(Object other){
if(other == this) return true;
if(other == null) return false;
if(other instanceof Choice){
Choice otherChoice = (Choice) other;
int numberOfSymbols = symbols.length;
if(numberOfSymbols != otherChoice.symbols.length) return false;
for(int i = otherChoice.symbols.length - 1; i >= 0; --i){
if(!symbols[i].equals(otherChoice.symbols[i])) return false;
}
return true;
}
return false;
}
}
|
package eg;
//--Eadgyth--//
import eg.ui.MainWin;
import eg.ui.ViewSettingWin;
/**
* The view settings in the main window that are set in
* <code>ViewSettingWin</code> except for showing/hiding line numbers
*/
public class ViewSetter {
private final MainWin mw;
private final ViewSettingWin viewSetWin;
private final Preferences prefs = new Preferences();
private boolean isShowToolbar;
private boolean isShowStatusbar;
private int selectedIconSizeInd;
private int selectedLafInd;
/**
* @param viewSetWin the reference to <code>ViewSettingWin</code>
* @param mw the reference to <code>MainWin</code>
*/
public ViewSetter(ViewSettingWin viewSetWin, MainWin mw) {
this.viewSetWin = viewSetWin;
this.mw = mw;
isShowStatusbar = viewSetWin.isShowStatusbar();
mw.showStatusbar(isShowStatusbar);
isShowToolbar = viewSetWin.isShowToolbar();
mw.showToolbar(isShowToolbar);
selectedIconSizeInd = viewSetWin.selectedIconSize();
selectedLafInd = viewSetWin.selectedLaf();
}
/**
* Applies the selections made in {@link ViewSettingWin}
*/
public void applySetWinOk() {
boolean show;
int index;
String state;
show = viewSetWin.isShowToolbar();
if (show != isShowToolbar) {
mw.showToolbar(show);
isShowToolbar = show;
state = isShowToolbar ? "show" : "hide";
prefs.storePrefs("toolbar", state);
}
show = viewSetWin.isShowStatusbar();
if (show != isShowStatusbar) {
mw.showStatusbar(show);
isShowStatusbar = show;
state = isShowStatusbar ? "show" : "hide";
prefs.storePrefs("statusbar", state);
}
index = viewSetWin.selectedIconSize();
if (index != selectedIconSizeInd) {
selectedIconSizeInd = index;
prefs.storePrefs("iconSize", ViewSettingWin.ICON_SIZES[selectedIconSizeInd]);
}
index = viewSetWin.selectedLaf();
if (index != selectedLafInd) {
selectedLafInd = index;
prefs.storePrefs("LaF", ViewSettingWin.LAF_OPT[selectedLafInd]);
}
}
}
|
package mujina.idp;
import mujina.api.IdpConfiguration;
import mujina.saml.SAMLAttribute;
import mujina.saml.SAMLPrincipal;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.saml2.core.NameIDType;
import org.opensaml.saml2.metadata.provider.MetadataProviderException;
import org.opensaml.ws.message.decoder.MessageDecodingException;
import org.opensaml.ws.message.encoder.MessageEncodingException;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.signature.SignatureException;
import org.opensaml.xml.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
@Controller
public class SsoController {
@Autowired
private SAMLMessageHandler samlMessageHandler;
@Autowired
private IdpConfiguration idpConfiguration;
@GetMapping("/SingleSignOnService")
public void singleSignOnServiceGet(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, MarshallingException, SignatureException, MessageEncodingException, ValidationException, SecurityException, MessageDecodingException, MetadataProviderException {
doSSO(request, response, authentication, false);
}
@PostMapping("/SingleSignOnService")
public void singleSignOnServicePost(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, MarshallingException, SignatureException, MessageEncodingException, ValidationException, SecurityException, MessageDecodingException, MetadataProviderException {
doSSO(request, response, authentication, true);
}
private void doSSO(HttpServletRequest request, HttpServletResponse response, Authentication authentication, boolean postRequest) throws ValidationException, SecurityException, MessageDecodingException, MarshallingException, SignatureException, MessageEncodingException, MetadataProviderException {
SAMLMessageContext messageContext = samlMessageHandler.extractSAMLMessageContext(request, response, postRequest);
AuthnRequest authnRequest = (AuthnRequest) messageContext.getInboundSAMLMessage();
String assertionConsumerServiceURL = idpConfiguration.getAcsEndpoint() != null ? idpConfiguration.getAcsEndpoint() : authnRequest.getAssertionConsumerServiceURL();
List<SAMLAttribute> attributes = attributes(authentication.getName());
SAMLPrincipal principal = new SAMLPrincipal(
authentication.getName(),
attributes.stream().filter(attr -> "urn:oasis:names:tc:SAML:1.1:nameid-format".equals(attr.getName()))
.findFirst().map(attr -> attr.getValue()).orElse(NameIDType.UNSPECIFIED),
attributes,
authnRequest.getIssuer().getValue(),
authnRequest.getID(),
assertionConsumerServiceURL,
messageContext.getRelayState());
samlMessageHandler.sendAuthnResponse(principal, response);
}
private List<SAMLAttribute> attributes(String uid) {
Map<String, List<String>> result = new HashMap<>();
result.putAll(idpConfiguration.getAttributes());
Optional<Map<String, List<String>>> optionalMap = idpConfiguration.getUsers().stream().filter(user -> user
.getPrincipal()
.equals(uid)).findAny().map(user -> user.getAttributes());
optionalMap.ifPresent(map -> result.putAll(map));
return result.entrySet().stream()
.map(entry -> entry.getKey().equals("urn:mace:dir:attribute-def:uid") ?
new SAMLAttribute(entry.getKey(), singletonList(uid)) :
new SAMLAttribute(entry.getKey(), entry.getValue()))
.collect(toList());
}
}
|
package entity;
import interfaces.Collidable;
import interfaces.Interactable;
import level.Area;
import main.Keys;
import resources.Art;
import screen.BaseScreen;
import abstracts.*;
public class Player extends Entity implements Collidable, Interactable {
private final int UP = 2;
private final int DOWN = 0;
private final int LEFT = 1;
private final int RIGHT = 3;
public Keys keys;
byte animationTick = 0;
byte animationPointer = 0;
int collidableId = 1;
int interactableId = 1;
public enum AnimationType {
WALKING
};
AnimationType animationType;
public Inventory inventory;
//These are based on the art sprite in the resource folder. The numbers are used to get elements from a 2D array.
int facing = 0;
int lastFacing = 0;
int walking = 0;
int xAccel;
int yAccel;
int oldXPosition;
int oldYPosition;
boolean lockWalking;
boolean[] facingsBlocked = new boolean[4];
public Player(Keys keys) {
this.keys = keys;
}
public void setCenterCamPosition(BaseScreen screen) {
this.setRenderOffset(screen.getWidth() / 2 - Tile.WIDTH, (screen.getHeight() - Tile.HEIGHT) / 2);
}
public void setRenderOffset(int x, int y) {
this.xOffset = x;
this.yOffset = y;
}
public void bang() {
}
public int getXInArea() {
//Returns area position X.
//if (!this.lockWalking)
int result = (xPosition / Tile.WIDTH);
if (this.lockWalking)
switch (facing) {
case LEFT:
break;
case RIGHT:
result += 1;
break;
}
//System.out.println("" + result);
return result;
//return this.oldXPosition / Tile.WIDTH;
}
public int getYInArea() {
//Returns area position Y.
//if (!this.lockWalking)
int result = (yPosition / Tile.HEIGHT);
if (this.lockWalking)
switch (facing) {
case UP:
break;
case DOWN:
result += 1;
break;
}
return result;
//return this.oldYPosition / Tile.HEIGHT;
}
@Override
public int getX() {
return this.xPosition;
}
@Override
public int getY() {
return this.yPosition;
}
@Override
public void initialize(BaseWorld world) {
}
public void initialize(Area area) {
area.setPlayerX(this.getXInArea());
area.setPlayerY(this.getYInArea());
}
@Override
public void tick() {
//Tile object = this.world.getTile(nextX, nextY);
//if (!facingObstacle(object)){
walk();
//else {
// bang();
}
public void tapped() {
animationTick = 0;
animationPointer = 0;
if (keys.up.isTappedDown || keys.W.isTappedDown) {
if (facing != UP) {
facing = UP;
}
}
else if (keys.down.isTappedDown || keys.S.isTappedDown) {
if (facing != DOWN) {
facing = DOWN;
}
}
else if (keys.left.isTappedDown || keys.A.isTappedDown) {
if (facing != LEFT) {
facing = LEFT;
}
}
else if (keys.right.isTappedDown || keys.D.isTappedDown) {
if (facing != RIGHT) {
facing = RIGHT;
}
}
}
public void pressed() {
xAccel = yAccel = 0;
if (keys.up.isPressedDown || keys.W.isPressedDown) {
if (facing != UP) {
facing = UP;
}
if (!this.facingsBlocked[UP]) {
this.lockWalking = true;
yAccel
}
}
else if (keys.down.isPressedDown || keys.S.isPressedDown) {
if (facing != DOWN) {
facing = DOWN;
}
if (!this.facingsBlocked[DOWN]) {
this.lockWalking = true;
yAccel++;
}
}
else if (keys.left.isPressedDown || keys.A.isPressedDown) {
if (facing != LEFT) {
facing = LEFT;
}
if (!this.facingsBlocked[LEFT]) {
this.lockWalking = true;
xAccel
}
}
else if (keys.right.isPressedDown || keys.D.isPressedDown) {
if (facing != RIGHT) {
facing = RIGHT;
}
if (!this.facingsBlocked[RIGHT]) {
this.lockWalking = true;
xAccel++;
}
}
}
public void walk() {
if (!this.lockWalking) {
if (!this.facingsBlocked[UP]) {
if (keys.up.isTappedDown || keys.W.isTappedDown)
tapped();
else if (keys.up.isPressedDown || keys.W.isPressedDown)
pressed();
}
if (!this.facingsBlocked[DOWN]) {
if (keys.down.isTappedDown || keys.S.isTappedDown)
tapped();
else if (keys.down.isPressedDown || keys.S.isPressedDown)
pressed();
}
if (!this.facingsBlocked[LEFT]) {
if (keys.left.isTappedDown || keys.A.isTappedDown)
tapped();
else if (keys.left.isPressedDown || keys.A.isPressedDown)
pressed();
}
if (!this.facingsBlocked[RIGHT]) {
if (keys.right.isTappedDown || keys.D.isTappedDown)
tapped();
else if (keys.right.isPressedDown || keys.D.isPressedDown)
pressed();
}
// if (!this.isBlocked) {
// if (keys.up.isTappedDown || keys.down.isTappedDown || keys.left.isTappedDown || keys.right.isTappedDown || keys.W.isTappedDown || keys.S.isTappedDown || keys.A.isTappedDown || keys.D.isTappedDown)
// tapped();
// else if (keys.up.isPressedDown || keys.down.isPressedDown || keys.left.isPressedDown || keys.right.isPressedDown || keys.W.isPressedDown || keys.S.isPressedDown || keys.A.isPressedDown || keys.D.isPressedDown)
// pressed();
}
handleMovementCheck();
controlTick();
}
public void collide(Tile tile) {
xPosition += (-xAccel);
yPosition += (-yAccel);
}
@Override
public void render(BaseScreen screen) {
/*//Blits the entity onto the screen, being offsetted to the left, which fits snugly in the world grids.
if (lockWalking) {
//screen.blit(Art.player[walking][animationPointer], (screen.getWidth() - Tile.WIDTH * 2) / 2 + xPosition, (screen.getHeight() - Tile.HEIGHT) / 2 + yPosition, Tile.WIDTH, Tile.HEIGHT);
screen.blit(Art.player[walking][animationPointer], xPosition - Tile.WIDTH, yPosition - Tile.HEIGHT / 2);
}
else
//screen.blit(Art.player[facing][0], (screen.getWidth() - Tile.WIDTH * 2) / 2 + xPosition, (screen.getHeight() - Tile.HEIGHT) / 2 + yPosition, Tile.WIDTH, Tile.HEIGHT);
screen.blit(Art.player[facing][0], xPosition - Tile.WIDTH, yPosition - Tile.HEIGHT / 2);*/
}
public void render(BaseScreen output, int x, int y) {
//render(BaseScreen output, int x, int y)
//output: where to blit the bitmap
//x: Pixel X offset
//y: Pixel Y offset
if (this.lockWalking) {
output.blit(Art.player[walking][animationPointer], this.xOffset + x, this.yOffset + y);
}
else {
if (keys.down.isPressedDown || keys.up.isPressedDown || keys.left.isPressedDown || keys.right.isPressedDown
|| keys.S.isPressedDown || keys.W.isPressedDown || keys.A.isPressedDown || keys.D.isPressedDown)
output.blit(Art.player[facing][animationPointer], this.xOffset + x, this.yOffset + y);
else
output.blit(Art.player[facing][0], this.xOffset + x, this.yOffset + y);
}
}
// @Override
// public void handleCollision(Tile tile, int xAcceleration, int yAcceleration) {
// int a = this.xPosition + Tile.WIDTH;
// int b = this.xPosition - Tile.WIDTH;
// int c = this.yPosition + Tile.HEIGHT;
// int d = this.yPosition - Tile.HEIGHT;
// if (tile == null)
// return;
// switch (tile.getType()) {
// case Entity.PLAYER:
// default:
// break;
// case Entity.TREE:
// this.collide(tile);
// isBlocked = true;
// break;
public int getFacing() {
return facing;
}
public int getLastFacing() {
return lastFacing;
}
@Override
public void interact(Interactable object) {
}
@Override
public int getInteractableId() {
return this.interactableId;
}
@Override
public int getCollidableId() {
return this.collidableId;
}
// public void blockPath(boolean value) {
// this.isBlocked = value;
public boolean isNotLockedWalking() {
return !this.lockWalking;
}
public void setAllBlockingDirections(boolean up, boolean down, boolean left, boolean right) {
this.facingsBlocked[UP] = up;
this.facingsBlocked[DOWN] = down;
this.facingsBlocked[LEFT] = left;
this.facingsBlocked[RIGHT] = right;
}
//Private methods
private void handleMovementCheck() {
//Check if player is currently locked to walking.
if (this.lockWalking) {
//When being locked to walking, facing must stay constant.
if (this.walking != this.facing)
this.walking = this.facing;
//Makes sure the acceleration stays limited to 1 pixel/tick.
if (xAccel > 1) xAccel = 1;
if (xAccel < -1) xAccel = -1;
if (yAccel > 1) yAccel = 1;
if (yAccel < -1) yAccel = -1;
xPosition += xAccel;
yPosition += yAccel;
//Needs to get out of being locked to walking.
//Note that we cannot compare using ||, what if the player is moving in one direction? What about the other axis?
if ((xPosition % Tile.WIDTH == 0 && yPosition % Tile.HEIGHT == 0)) {
this.lockWalking = false;
}
}
else {
//Before we walk, check to see if the oldX and oldY are up-to-date with the latest X and Y.
if (this.oldXPosition != this.xPosition) this.oldXPosition = this.xPosition;
if (this.oldYPosition != this.yPosition) this.oldYPosition = this.yPosition;
//Reset the acceleration values, since we're not really walking.
xAccel = 0;
yAccel = 0;
//Check for inputs the player wants to face. Tapping in a direction turns the player around.
checkFacing();
//checkFacingObstacles();
//Now about to walk. First, check to see if there's an obstacle blocking the path.
if (this.facingsBlocked[UP] || this.facingsBlocked[DOWN] || this.facingsBlocked[LEFT] || this.facingsBlocked[RIGHT]) {
this.lockWalking = false;
}
// if (this.isBlocked) {
// this.lockWalking = false;
}
// if (xPosition % Tile.WIDTH == 0 && yPosition % Tile.HEIGHT == 0) {
// if (this.isBlocked) {
// xAccel = 0;
// yAccel = 0;
// walking = facing;
// this.lockWalking = false;
// return;
// if (this.lockWalking) {
// if (xAccel > 1)
// xAccel = 1;
// else if (xAccel < -1)
// xAccel = -1;
// else if (yAccel > 1)
// yAccel = 1;
// else if (yAccel < -1)
// yAccel = -1;
// xPosition += xAccel;
// yPosition += yAccel;
// checkFacing();
// if (xPosition % Tile.WIDTH == 0 && yPosition % Tile.HEIGHT == 0) {
// xAccel = 0;
// yAccel = 0;
// this.lockWalking = false;
// walking = facing;
// if (Math.abs(xPosition - oldXPosition) == Tile.WIDTH || Math.abs(yPosition - oldYPosition) == Tile.HEIGHT) {
// oldXPosition = xPosition;
// oldYPosition = yPosition;
}
// private void checkFacingObstacles() {
// this.isBlocked = false;
// if (this.facing == UP) {
// if (this.facingsBlocked[UP])
// this.isBlocked = true;
// else if (this.facing == DOWN) {
// if (this.facingsBlocked[DOWN])
// this.isBlocked = true;
// else if (this.facing == LEFT) {
// if (this.facingsBlocked[LEFT])
// this.isBlocked = true;
// else if (this.facing == RIGHT) {
// if (this.facingsBlocked[RIGHT])
// this.isBlocked = true;
// private boolean checkObstacles() {
// //Something something
// return isBlocked;
// private boolean facingObstacle(Tile object) {
// this.handleCollision(object, 0, 0);
// return isBlocked;
private void checkFacing() {
if (keys.up.isTappedDown || keys.up.isPressedDown || keys.W.isTappedDown || keys.W.isPressedDown) {
facing = UP;
}
else if (keys.down.isTappedDown || keys.down.isPressedDown || keys.S.isTappedDown || keys.S.isPressedDown) {
facing = DOWN;
}
else if (keys.left.isTappedDown || keys.left.isPressedDown || keys.A.isTappedDown || keys.A.isPressedDown) {
facing = LEFT;
}
else if (keys.right.isTappedDown || keys.right.isPressedDown || keys.D.isTappedDown || keys.D.isPressedDown) {
facing = RIGHT;
}
}
private void controlTick() {
animationTick++;
//if (this.isBlocked) {
if ((this.facing == UP && this.facingsBlocked[UP])) {
if (animationTick >= 20) {
animationTick = 0;
}
}
else if ((this.facing == DOWN && this.facingsBlocked[DOWN])) {
if (animationTick >= 20) {
animationTick = 0;
}
}
else if ((this.facing == LEFT && this.facingsBlocked[LEFT])) {
if (animationTick >= 20) {
animationTick = 0;
}
}
else if ((this.facing == RIGHT && this.facingsBlocked[RIGHT])) {
if (animationTick >= 20) {
animationTick = 0;
}
}
else {
if (animationTick >= 8)
animationTick = 0;
}
if (animationTick == 0) {
animationPointer++;
if (animationPointer > 3)
animationPointer = 0;
}
}
public void setAreaPosition(int x, int y) {
this.setPosition(x * Tile.WIDTH, y * Tile.HEIGHT);
}
public boolean hasChangedFacing() {
//True, if current facing has been changed.
return this.lastFacing != this.facing;
}
@Override
public void handleCollision(Tile tile, int xAcceleration, int yAcceleration) {
}
}
|
package com.winterwell.web.app;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jetty.util.ajax.JSON;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.sort.SortOrder;
import com.winterwell.data.AThing;
import com.winterwell.data.KStatus;
import com.winterwell.depot.IInit;
import com.winterwell.es.ESPath;
import com.winterwell.es.IESRouter;
import com.winterwell.es.client.DeleteRequestBuilder;
import com.winterwell.es.client.ESHttpClient;
import com.winterwell.es.client.IESResponse;
import com.winterwell.es.client.KRefresh;
import com.winterwell.es.client.SearchRequestBuilder;
import com.winterwell.es.client.SearchResponse;
import com.winterwell.es.client.query.ESQueryBuilder;
import com.winterwell.es.client.query.ESQueryBuilders;
import com.winterwell.gson.Gson;
import com.winterwell.utils.Dep;
import com.winterwell.utils.ReflectionUtils;
import com.winterwell.utils.StrUtils;
import com.winterwell.utils.Utils;
import com.winterwell.utils.containers.ArrayMap;
import com.winterwell.utils.containers.Containers;
import com.winterwell.utils.io.CSVSpec;
import com.winterwell.utils.io.CSVWriter;
import com.winterwell.utils.log.Log;
import com.winterwell.utils.web.SimpleJson;
import com.winterwell.utils.web.WebUtils;
import com.winterwell.utils.web.WebUtils2;
import com.winterwell.web.WebEx;
import com.winterwell.web.ajax.JThing;
import com.winterwell.web.ajax.JsonResponse;
import com.winterwell.web.app.WebRequest.KResponseType;
import com.winterwell.web.data.XId;
import com.winterwell.web.fields.SField;
import com.winterwell.youagain.client.AuthToken;
import com.winterwell.youagain.client.NoAuthException;
import com.winterwell.youagain.client.YouAgainClient;
/**
* TODO security checks
*
* @author daniel
*
* @param <T>
*/
public abstract class CrudServlet<T> implements IServlet {
public static final String ACTION_PUBLISH = "publish";
private static final String ACTION_NEW = "new";
public CrudServlet(Class<T> type) {
this(type, Dep.get(IESRouter.class));
}
public CrudServlet(Class<T> type, IESRouter esRouter) {
this.type = type;
this.esRouter = esRouter;
Utils.check4null(type, esRouter);
}
protected JThing<T> doDiscardEdits(WebRequest state) {
ESPath path = esRouter.getPath(dataspace,type, getId(state), KStatus.DRAFT);
DeleteRequestBuilder del = es.prepareDelete(path.index(), path.type, path.id);
IESResponse ok = del.get().check();
getThing(state);
return jthing;
}
public void process(WebRequest state) throws Exception {
// CORS??
WebUtils2.CORS(state, false);
doSecurityCheck(state);
// list?
String slug = state.getSlug();
if (slug.endsWith("/_list") || LIST_SLUG.equals(slug)) {
doList(state);
return;
}
// crud?
if (state.getAction() != null) {
// do it
doAction(state);
}
// return json?
getThing(state);
if (jthing==null) jthing = getThingFromDB(state);
if (jthing != null) {
String json = jthing.string();
// TODO privacy: potentially filter some stuff from the json!
JsonResponse output = new JsonResponse(state).setCargoJson(json);
WebUtils2.sendJson(output, state);
return;
}
// return blank / messages
if (state.getAction()==null) {
// no thing?
throw new WebEx.E404(state.getRequestUrl());
}
JsonResponse output = new JsonResponse(state);
WebUtils2.sendJson(output, state);
}
protected void doSecurityCheck(WebRequest state) throws SecurityException {
YouAgainClient ya = Dep.get(YouAgainClient.class);
ReflectionUtils.setPrivateField(state, "debug", true); // FIXME
List<AuthToken> tokens = ya.getAuthTokens(state);
if (state.getAction() == null) {
return;
}
// logged in?
if (Utils.isEmpty(tokens)) {
Log.w("crud", "No auth tokens for "+this+" "+state);
throw new NoAuthException(state);
}
}
protected void doAction(WebRequest state) {
// make a new thing?
if (state.actionIs(ACTION_NEW)) {
// add is "special" as the only request that doesn't need an id
String id = getId(state);
jthing = doNew(state, id);
jthing.setType(type);
}
// save?
if (state.actionIs("save") || state.actionIs(ACTION_NEW)) {
doSave(state);
}
if (state.actionIs("discard-edits") || state.actionIs("discardEdits")) {
jthing = doDiscardEdits(state);
}
if (state.actionIs("delete")) {
jthing = doDelete(state);
}
// publish?
if (state.actionIs(ACTION_PUBLISH)) {
jthing = doPublish(state);
assert jthing.string().contains(KStatus.PUBLISHED.toString()) : jthing;
}
if (state.actionIs("unpublish")) {
jthing = doUnPublish(state);
}
}
/**
* Delete from draft and published!!
* @param state
* @return
*/
protected JThing<T> doDelete(WebRequest state) {
String id = getId(state);
// try to copy to trash
try {
JThing<T> thing = getThingFromDB(state);
if (thing != null) {
ESPath path = esRouter.getPath(dataspace, type, id, KStatus.TRASH);
AppUtils.doSaveEdit2(path, thing, state, false);
}
} catch(Throwable ex) {
Log.e(LOGTAG(), "copy to trash failed: "+state+" -> "+ex);
}
for(KStatus s : KStatus.main()) {
if (s==KStatus.TRASH) continue;
try {
ESPath path = esRouter.getPath(dataspace,type, id, s);
DeleteRequestBuilder del = es.prepareDelete(path.index(), path.type, path.id);
del.setRefresh("wait_for");
IESResponse ok = del.get().check();
} catch(WebEx.E404 e404) {
// gone already
}
}
return null;
}
/**
*
* @param state
* @return thing or null
*/
protected JThing<T> getThingFromDB(WebRequest state) {
ESPath path = getPath(state);
KStatus status = state.get(AppUtils.STATUS);
// fetch from DB
T obj = AppUtils.get(path, type);
if (obj!=null) {
JThing thing = new JThing().setType(type).setJava(obj);
return thing;
}
// Not found :(
// was version=draft?
if (status == KStatus.DRAFT) {
// Try for the published version
// NB: all published should be in draft, so this should be redundant
WebRequest state2 = new WebRequest(state.request, state.response);
state2.put(AppUtils.STATUS, KStatus.PUBLISHED);
JThing<T> pubThing = getThingFromDB(state2);
return pubThing;
}
return null;
}
/**
* Use getId() to make an ESPath
* @param state
* @return
*/
protected ESPath getPath(WebRequest state) {
assert state != null;
String id = getId(state);
if ("list".equals(id)) {
throw new WebEx.E400(
state.getRequestUrl(),
"Bad input: 'list' was interpreted as an ID -- use /_list.json to retrieve a list.");
}
ESPath path = esRouter.getPath(dataspace,type, id, state.get(AppUtils.STATUS, KStatus.PUBLISHED));
return path;
}
/**
* Make a new thing. The state will often contain json info for this.
* @param state
* @param id Can be null ??It may be best for the front-end to normally provide IDs.
* @return
*/
protected JThing<T> doNew(WebRequest state, String id) {
String json = getJson(state);
T item;
if (json == null) {
try {
item = type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw Utils.runtime(e);
}
} else {
// from front end json
item = Dep.get(Gson.class).fromJson(json, type);
// TODO safety check ID! Otherwise someone could hack your object with a new object
// idFromJson = AppUtils.getItemId(item);
}
if (id != null) {
if (item instanceof AThing) {
((AThing) item).setId(id);
}
// else ??
}
if (item instanceof IInit) {
((IInit) item).init();
}
return new JThing().setJava(item);
}
protected ESHttpClient es = Dep.get(ESHttpClient.class);
protected final Class<T> type;
protected JThing<T> jthing;
protected final IESRouter esRouter;
/**
* The focal thing's ID.
* This might be newly minted for a new thing
*/
private String _id;
/**
* Optional support for dataspace based data access.
*/
// NB: the Dataspace class is not in the scope of this project, hence the super-class CharSequence
protected CharSequence dataspace = null;
public CrudServlet setDataspace(CharSequence dataspace) {
this.dataspace = dataspace;
return this;
}
/**
* suggested: date-desc
*/
protected String defaultSort;
public static final SField SORT = new SField("sort");
public static final String LIST_SLUG = "_list";
protected final JThing<T> doPublish(WebRequest state) {
// wait 1 second??
return doPublish(state, KRefresh.WAIT_FOR, false);
}
protected JThing<T> doPublish(WebRequest state, KRefresh forceRefresh, boolean deleteDraft) {
String id = getId(state);
Log.d("crud", "doPublish "+id+" by "+state.getUserId()+" "+state+" deleteDraft: "+deleteDraft);
Utils.check4null(id);
// load (if not loaded)
getThing(state);
if (jthing==null) {
jthing = getThingFromDB(state);
}
return doPublish2(dataspace, jthing, forceRefresh, deleteDraft, id);
}
/**
* @param _jthing
* @param forceRefresh
* @param deleteDraft
* @param id
* @return
*/
protected JThing<T> doPublish2(CharSequence dataspace, JThing<T> _jthing, KRefresh forceRefresh, boolean deleteDraft, String id) {
ESPath draftPath = esRouter.getPath(dataspace,type, id, KStatus.DRAFT);
ESPath publishPath = esRouter.getPath(dataspace,type, id, KStatus.PUBLISHED);
// id must match
if (_jthing.java() instanceof AThing) {
String thingId = ((AThing) _jthing.java()).getId();
if (thingId==null || ACTION_NEW.equals(thingId)) {
_jthing.put("id", id);
} else if ( ! thingId.equals(id)) {
throw new IllegalStateException("ID mismatch "+thingId+" vs "+id);
}
}
JThing obj = AppUtils.doPublish(_jthing, draftPath, publishPath, forceRefresh, deleteDraft);
return obj.setType(type);
}
protected JThing<T> doUnPublish(WebRequest state) {
String id = getId(state);
Log.d("crud", "doUnPublish "+id+" by "+state.getUserId()+" "+state);
Utils.check4null(id);
// load (if not loaded)
getThing(state);
if (jthing==null) {
jthing = getThingFromDB(state);
}
ESPath draftPath = esRouter.getPath(dataspace,type, id, KStatus.DRAFT);
ESPath publishPath = esRouter.getPath(dataspace,type, id, KStatus.PUBLISHED);
// set state to draft
AppUtils.setStatus(jthing, KStatus.DRAFT);
AppUtils.doSaveEdit(draftPath, jthing, state);
Log.d("crud", "unpublish doSave "+draftPath+" by "+state.getUserId()+" "+state+" "+jthing.string());
AppUtils.doDelete(publishPath);
state.addMessage(id+" has been moved from published to draft");
return jthing;
}
protected String getId(WebRequest state) {
if (_id!=null) return _id;
// Beware if ID can have a / in it!
String[] slugBits = state.getSlugBits();
String sid = slugBits[slugBits.length - 1]; // NB: slug-bit-0 is the servlet
_id = getId2(state, sid);
return _id;
}
protected String getId2(WebRequest state, String sid) {
if (ACTION_NEW.equals(sid)) {
String nicestart = StrUtils.toCanonical(
Utils.or(state.getUserId(), state.get("name"), type.getSimpleName()).toString()
).replace(' ', '_');
sid = nicestart+"_"+Utils.getRandomString(8);
// avoid ad, 'cos adblockers dont like it!
if (sid.startsWith("ad")) {
sid = sid.substring(2, sid.length());
}
}
return sid;
}
protected void doList(WebRequest state) throws IOException {
// copied from SoGive SearchServlet
// TODO refactor to use makeESFilterFromSearchQuery
SearchRequestBuilder s = new SearchRequestBuilder(es);
/// which index? draft (which should include copies of published) by default
KStatus status = state.get(AppUtils.STATUS, KStatus.DRAFT);
if (status!=null && status != KStatus.ALL_BAR_TRASH) {
s.setIndex(
esRouter.getPath(dataspace, type, null, status).index()
);
} else {
s.setIndices(
esRouter.getPath(dataspace, type, null, KStatus.PUBLISHED).index(),
esRouter.getPath(dataspace, type, null, KStatus.DRAFT).index()
);
}
// query
String q = state.get("q");
ESQueryBuilder qb = null;
if ( q != null) {
// convert "me" to specific IDs
if (Pattern.compile("\\bme\\b").matcher(q).find()) {
YouAgainClient ya = Dep.get(YouAgainClient.class);
List<AuthToken> tokens = ya.getAuthTokens(state);
StringBuilder mes = new StringBuilder();
for (AuthToken authToken : tokens) {
mes.append(authToken.xid+" OR ");
}
if (mes.length()==0) {
Log.w("crud", "No mes "+q+" "+state);
mes.append("ANON OR " ); // fail - WTF? How come no logins?!
}
StrUtils.pop(mes, 4);
q = q.replaceAll("\\bme\\b", mes.toString());
}
// TODO match on all?
// HACK strip out unset
if (q.contains(":unset")) {
Matcher m = Pattern.compile("(\\w+):unset").matcher(q);
m.find();
String prop = m.group(1);
String q2 = m.replaceAll("").trim();
q = q2;
ESQueryBuilder setFilter = ESQueryBuilders.existsQuery(prop);
qb = ESQueryBuilders.boolQuery().mustNot(setFilter);
}
if ( ! Utils.isBlank(q) && ! "ALL".equals(q)) {
QueryStringQueryBuilder qsq = new QueryStringQueryBuilder(q); // QueryBuilders.queryStringQuery(q); // version incompatabilities in ES code :(
qb = ESQueryBuilders.must(qb, qsq);
}
}
// NB: exq can be null for ALL
ESQueryBuilder exq = doList2_query(state);
qb = ESQueryBuilders.must(qb, exq);
if (qb!=null) s.setQuery(qb);
// Sort e.g. sort=date-desc for most recent first
String sort = state.get(SORT, defaultSort);
if (sort!=null) {
// HACK: order?
SortOrder order = SortOrder.ASC;
if (sort.endsWith("-desc")) {
sort = sort.substring(0, sort.length()-5);
order = SortOrder.DESC;
} else if (sort.endsWith("-asc")) {
sort = sort.substring(0, sort.length()-4);
}
s.addSort(sort, order);
}
// TODO paging!
s.setSize(10000);
s.setDebug(true);
SearchResponse sr = s.get();
Map<String, Object> jobj = sr.getParsedJson();
List<Map> hits = sr.getHits();
// If user requests ALL_BAR_TRASH, they want to see draft versions of items which have been edited
// So when de-duping, give priority to entries from .draft indices where the object is status: DRAFT
List hits2 = new ArrayList<Map>();
if (status == KStatus.ALL_BAR_TRASH) {
List<Object> idOrder = new ArrayList<Object>(); // original ordering
Map<Object, Object> things = new HashMap<Object, Object>(); // to hold "expected" version of each hit
for (Map h : hits) {
// pull out the actual object from the hit (NB: may be Map or AThing)
Object hit = h.get("_source");
if (hit == null) continue;
Object id = getIdFromHit(hit);
// First time we've seen this object? Save it.
if (!things.containsKey(id)) {
idOrder.add(id);
things.put(id, hit);
continue;
}
// Is this an object from .draft with non-published status? Overwrite the previous entry.
Object index = h.get("_index");
if (index != null && index.toString().contains(".draft")) {
KStatus hitStatus = KStatus.valueOf(getStatus(hit));
if (KStatus.DRAFT.equals(hitStatus) || KStatus.MODIFIED.equals(hitStatus)) {
things.put(id, hit);
}
}
}
// Put the deduped hits in the list in their original order.
for (Object id : idOrder) {
if (things.containsKey(id)) hits2.add(things.get(id));
}
} else {
// One index = no deduping necessary.
hits2 = Containers.apply(hits, h -> h.get("_source"));
}
// sanitise for privacy
hits2 = cleanse(hits2, state);
// HACK: send back csv?
if (state.getResponseType() == KResponseType.csv) {
doSendCsv(state, hits2);
return;
}
long total = sr.getTotal();
String json = Dep.get(Gson.class).toJson(
new ArrayMap(
"hits", hits2,
"total", total
));
JsonResponse output = new JsonResponse(state).setCargoJson(json);
WebUtils2.sendJson(output, state);
}
/**
* TODO remove sensitive details for privacy
* @param hits2
* @param state
* @return
*/
protected List<Map> cleanse(List<Map> hits2, WebRequest state) {
return hits2;
}
private String getStatus(Object h) {
Object s;
if (h instanceof Map) s = ((Map)h).get("status");
else s = ((AThing)h).getStatus();
return String.valueOf(s);
}
/**
*
* @param hit Map from ES, or AThing
* @return
*/
private Object getIdFromHit(Object hit) {
Object id;
if (hit instanceof Map) id = ((Map)hit).get("id");
else id = ((AThing)hit).getId();
return id;
}
protected void doSendCsv(WebRequest state, List<Map> hits2) {
// ?? maybe refactor and move into a default method in IServlet?
StringWriter sout = new StringWriter();
CSVWriter w = new CSVWriter(sout, new CSVSpec());
// what headers??
ArrayMap<String, String> hs = doSendCsv2_getHeaders(state, hits2);
// write
w.write(hs.values());
for (Map hit : hits2) {
List<Object> line = Containers.apply(hs, h -> {
String[] p = h.split("\\.");
return SimpleJson.get(hit, p);
});
w.write(line);
}
w.close();
// send
String csv = sout.toString();
state.getResponse().setContentType(WebUtils.MIME_TYPE_CSV); // + utf8??
WebUtils2.sendText(csv, state.getResponse());
}
/**
*
* @param state
* @param hits2
* @return
*/
protected ArrayMap<String,String> doSendCsv2_getHeaders(WebRequest state, List<Map> hits2) {
if (hits2.isEmpty()) return new ArrayMap();
Map hit = hits2.get(0);
ArrayMap map = new ArrayMap();
for(Object k : hit.keySet()) {
map.put(""+k, ""+k);
}
return map;
// // TODO proper recursive
// ObjectDistribution<String> headers = new ObjectDistribution();
// for (Map<String,Object> hit : hits2) {
// getHeaders(hit, new ArrayList(), headers);
// // prune
// if (hits2.size() >= 1) {
// int min = (int) (hits2.size() * 0.2);
// if (min>0) headers.pruneBelow(min);
// // sort
// ArrayList<String> hs = new ArrayList(headers.keySet());
// // all the level 1 headers
// List<String> level1 = Containers.filter(hs, h -> ! h.contains("."));
// hs.removeAll(level1);
// Collections.sort(hs);
// Collections.sort(level1);
// // start with ID, name
// level1.remove("name");
// level1.remove("@id");
// Collections.reverse(level1);
// level1.add("name");
// level1.add("@id");
// level1.forEach(h -> hs.add(0, h));
// hs.removeIf(h -> h.contains("@type") || h.contains("value100"));
}
/**
*
* @param state
* @return null or a query
*/
protected ESQueryBuilder doList2_query(WebRequest state) {
return null;
}
/**
* NB: Uses AppUtils#doSaveEdit2(ESPath, JThing, WebRequest, boolean) to do a *merge* into ES.
* So this will not remove parts of a document (unless you provide an over-write value).
*
* Why use merge?
* This allows for partial editors (e.g. edit the budget of an advert), and reduces the collision
* issues with multiple online editors.
*
*
* @param state
*/
protected void doSave(WebRequest state) {
// debug FIXME
String json = getJson(state);
Object jobj = JSON.parse(json);
Object start = SimpleJson.get(jobj, "projects", 0, "start");
XId user = state.getUserId(); // TODO save who did the edit + audit trail
T thing = getThing(state);
assert thing != null : state;
// HACK set modified = true on maps
if (thing instanceof Map) {
((Map) thing).put("modified", true);
} else {
// should we have an interface for this??
// ReflectionUtils.setPrivateField(thing, fieldName, value);
// NB: avoiding jthing.put() as that re-makes the java object, which is wasteful and confusing
// jthing.put("modified", true);
}
// This has probably been done already in getThing(), but harmless to repeat
// run the object through Java, to trigger IInit
jthing.java();
// FIXME debug
Object start2 = SimpleJson.get(jthing.map(), "projects", 0, "start");
Object startraw = SimpleJson.get(jthing.map(), "projects", 0, "start_raw");
T ngo = jthing.java();
{ // update
String id = getId(state);
assert id != null : "No id? cant save! "+state;
ESPath path = esRouter.getPath(dataspace,type, id, KStatus.DRAFT);
AppUtils.doSaveEdit(path, jthing, state);
Log.d("crud", "doSave "+path+" by "+state.getUserId()+" "+state+" "+jthing.string());
}
}
/**
* Get from field or state. Does NOT call the database.
* @param state
* @return
*/
protected T getThing(WebRequest state) {
if (jthing!=null) {
return jthing.java();
}
String json = getJson(state);
if (json==null) {
return null;
}
jthing = new JThing(json).setType(type);
return jthing.java();
}
protected String getJson(WebRequest state) {
return state.get(new SField(AppUtils.ITEM.getName()));
}
}
|
package org.knowm.xchange.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
/**
* <p>
* Utilities to provide the following to application:
* </p>
* <ul>
* <li>Provision of standard date and time handling</li>
* </ul>
*/
public class DateUtils {
/**
* private Constructor
*/
private DateUtils() {
}
/**
* Creates a date from a long representing milliseconds from epoch
*
* @param millisecondsFromEpoch
* @return the Date object
*/
public static Date fromMillisUtc(long millisecondsFromEpoch) {
return new Date(millisecondsFromEpoch);
}
/**
* Converts a date to a UTC String representation
*
* @param date
* @return the formatted date
*/
public static String toUTCString(Date date) {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
return sd.format(date);
}
/**
* Converts an ISO formatted Date String to a Java Date ISO format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
*
* @param isoFormattedDate
* @return Date
* @throws com.fasterxml.jackson.databind.exc.InvalidFormatException
*/
public static Date fromISODateString(String isoFormattedDate) throws com.fasterxml.jackson.databind.exc.InvalidFormatException {
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// set UTC time zone - 'Z' indicates it
isoDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return isoDateFormat.parse(isoFormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", isoFormattedDate, Date.class);
}
}
/**
* Converts an ISO 8601 formatted Date String to a Java Date ISO 8601 format: yyyy-MM-dd'T'HH:mm:ss
*
* @param iso8601FormattedDate
* @return Date
* @throws com.fasterxml.jackson.databind.exc.InvalidFormatException
*/
public static Date fromISO8601DateString(String iso8601FormattedDate) throws com.fasterxml.jackson.databind.exc.InvalidFormatException {
SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// set UTC time zone
iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return iso8601Format.parse(iso8601FormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", iso8601FormattedDate, Date.class);
}
}
/**
* Converts an rfc1123 formatted Date String to a Java Date rfc1123 format: EEE, dd MMM yyyy HH:mm:ss zzz
*
* @param rfc1123FormattedDate
* @return Date
* @throws com.fasterxml.jackson.databind.exc.InvalidFormatException
*/
public static Date fromRfc1123DateString(String rfc1123FormattedDate, Locale locale) throws com.fasterxml.jackson.databind.exc.InvalidFormatException {
SimpleDateFormat rfc1123DateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", locale);
try {
return rfc1123DateFormat.parse(rfc1123FormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", rfc1123FormattedDate, Date.class);
}
}
public static Date fromRfc3339DateString(String rfc3339FormattedDate) throws InvalidFormatException {
SimpleDateFormat rfc3339DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return rfc3339DateFormat.parse(rfc3339FormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", rfc3339FormattedDate, Date.class);
}
}
/**
* Convert java time long to unix time long, simply by dividing by 1000
*/
public static long toUnixTime(long javaTime) {
return javaTime / 1000;
}
/**
* Convert java time to unix time long, simply by dividing by the time 1000
*/
public static long toUnixTime(Date time) {
return time.getTime() / 1000;
}
/**
* Convert java time to unix time long, simply by dividing by the time 1000. Null safe
*/
public static Long toUnixTimeNullSafe(Date time) {
return time == null ? null : time.getTime() / 1000;
}
public static Long toMillisNullSafe(Date time) {
return time == null ? null : time.getTime();
}
/**
* Convert unix time to Java Date
*/
public static Date fromUnixTime(long unix) {
return new Date(unix * 1000);
}
}
|
import java.util.*;
public class FinalExam {
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.main(new String[]{});
}
}
class TestClass {
int field;
void field(int x) {
// method can have same name as field
System.out.println("field is " + x);
}
public static void main(String[] args) {
try {
int[][] a = null;
// int[][] a = new int[2]; // FinalExam.java:3: error: incompatible types
a[0] = new int[3]; // it will have NullPointerException, but will pass compile
a[1] = new int[6];
} catch(Exception e) {
System.out.println(e.getClass().getName());
}
float divFloat = 1.0f % 3.0f;
int divInt = 1 % 3;
System.out.println("divFloat : divInt = " + divFloat + " : " + divInt);
float checkFloat = (1334_5.0f > 1243_3.0f) ? 12_345 : 12_345.20f;
checkFloat += 1024;
System.out.println("checkFloat = " + checkFloat);
ArrayList<String> as = new ArrayList<String>(Arrays.asList("a", "b", "c", "d", "e"));
int counter = 0;
for (String str : as) {
switch(str) {
case "a":
continue;
case "b":
counter++;
break;
case "c":
counter++;
continue;
case "d":
counter++;
break;
}
}
System.out.println("The counter is " + counter);
char c[] = new char[]{97, '\t', 'e', '\n', 'i', '\t', 'o'};
for(char c1 : c) {
System.out.print(c1);
}
System.out.println();
System.out.println(c.length);
System.out.println("World");
}
}
|
package com.intellij.util.xml;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.ConstantFunction;
import com.intellij.util.NotNullFunction;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentInstanceMap;
import com.intellij.util.xml.highlighting.DomElementsAnnotator;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Use {@code com.intellij.dom.fileMetaData} extension point to register.
*
* @author peter
* @see MergingFileDescription
*/
public class DomFileDescription<T> {
/**
* @deprecated Register with {@code com.intellij.dom.fileMetaData} extension point instead.
*/
@Deprecated
public static final ExtensionPointName<DomFileDescription> EP_NAME = ExtensionPointName.create("com.intellij.dom.fileDescription");
private final Map<Class<? extends ScopeProvider>, ScopeProvider> myScopeProviders = ConcurrentInstanceMap.create();
protected final Class<T> myRootElementClass;
protected final String myRootTagName;
private final String[] myAllPossibleRootTagNamespaces;
private volatile boolean myInitialized;
private final Map<Class<? extends DomElement>,Class<? extends DomElement>> myImplementations = new HashMap<>();
private final TypeChooserManager myTypeChooserManager = new TypeChooserManager();
private final List<DomReferenceInjector> myInjectors = new SmartList<>();
private final Map<String, NotNullFunction<XmlTag, List<String>>> myNamespacePolicies =
new ConcurrentHashMap<>();
public DomFileDescription(final Class<T> rootElementClass, @NonNls final String rootTagName, @NonNls String @NotNull ... allPossibleRootTagNamespaces) {
myRootElementClass = rootElementClass;
myRootTagName = rootTagName;
myAllPossibleRootTagNamespaces = allPossibleRootTagNamespaces.length == 0 ? ArrayUtilRt.EMPTY_STRING_ARRAY
: allPossibleRootTagNamespaces;
}
public String @NotNull [] getAllPossibleRootTagNamespaces() {
return myAllPossibleRootTagNamespaces;
}
/**
* Register an implementation class to provide additional functionality for DOM elements.
*
* @param domElementClass interface class.
* @param implementationClass abstract implementation class.
* @see #initializeFileDescription()
* @deprecated use dom.implementation extension point instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public final <Dom extends DomElement> void registerImplementation(Class<Dom> domElementClass, Class<? extends Dom> implementationClass) {
myImplementations.put(domElementClass, implementationClass);
}
/**
* @param namespaceKey namespace identifier
* @see Namespace
* @param policy function that takes XML file root tag and returns (maybe empty) list of possible namespace URLs or DTD public ids. This
* function shouldn't use DOM since it may be not initialized for the file at the moment
* @deprecated use {@link #registerNamespacePolicy(String, String...)} or override {@link #getAllowedNamespaces(String, XmlFile)} instead
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
protected final void registerNamespacePolicy(String namespaceKey, NotNullFunction<XmlTag,List<String>> policy) {
myNamespacePolicies.put(namespaceKey, policy);
}
/**
* @param namespaceKey namespace identifier
* @see Namespace
* @param namespaces XML namespace or DTD public or system id value for the given namespaceKey
*/
public final void registerNamespacePolicy(String namespaceKey, final String... namespaces) {
registerNamespacePolicy(namespaceKey, new ConstantFunction<>(Arrays.asList(namespaces)));
}
/**
* Consider using {@link DomService#getXmlFileHeader(XmlFile)} when implementing this.
*/
public @NotNull List<String> getAllowedNamespaces(@NotNull String namespaceKey, @NotNull XmlFile file) {
final NotNullFunction<XmlTag, List<String>> function = myNamespacePolicies.get(namespaceKey);
if (function instanceof ConstantFunction) {
return function.fun(null);
}
if (function != null) {
final XmlDocument document = file.getDocument();
if (document != null) {
final XmlTag tag = document.getRootTag();
if (tag != null) {
return function.fun(tag);
}
}
} else {
return Collections.singletonList(namespaceKey);
}
return Collections.emptyList();
}
/**
* @return some version. Override and change (e.g. {@code super.getVersion()+1}) when after some changes some files stopped being
* described by this description or vice versa, so that the
* {@link DomService#getDomFileCandidates(Class, com.intellij.psi.search.GlobalSearchScope)}
* index is rebuilt correctly.
* @deprecated use "domVersion" attribute of {@code com.intellij.dom.fileMetaData} extension instead
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public int getVersion() {
return myRootTagName.hashCode();
}
protected final void registerTypeChooser(final Type aClass, final TypeChooser typeChooser) {
myTypeChooserManager.registerTypeChooser(aClass, typeChooser);
}
public final TypeChooserManager getTypeChooserManager() {
return myTypeChooserManager;
}
protected final void registerReferenceInjector(DomReferenceInjector injector) {
myInjectors.add(injector);
}
public List<DomReferenceInjector> getReferenceInjectors() {
return myInjectors;
}
public boolean isAutomaticHighlightingEnabled() {
return true;
}
public @Nullable Icon getFileIcon(@Iconable.IconFlags int flags) {
return null;
}
/**
* The right place to call
* <ul>
* <li>{@link #registerNamespacePolicy(String, String...)}</li>
* <li>{@link #registerTypeChooser(Type, TypeChooser)}</li>
* <li>{@link #registerReferenceInjector(DomReferenceInjector)}</li>
* </ul>
*/
protected void initializeFileDescription() {}
/**
* Create custom DOM annotator that will be used when error-highlighting DOM. The results will be collected to
* {@link com.intellij.util.xml.highlighting.DomElementsProblemsHolder}. The highlighting will be most probably done in an
* {@link com.intellij.util.xml.highlighting.BasicDomElementsInspection} instance.
* @return Annotator or null
*/
public @Nullable DomElementsAnnotator createAnnotator() {
return null;
}
public final Map<Class<? extends DomElement>,Class<? extends DomElement>> getImplementations() {
if (!myInitialized) {
initializeFileDescription();
myInitialized = true;
}
return myImplementations;
}
public final @NotNull Class<T> getRootElementClass() {
return myRootElementClass;
}
public final String getRootTagName() {
return myRootTagName;
}
public boolean isMyFile(@NotNull XmlFile file, final @Nullable Module module) {
final Namespace namespace = DomReflectionUtil.findAnnotationDFS(myRootElementClass, Namespace.class);
if (namespace != null) {
final String key = namespace.value();
Set<String> allNs = new HashSet<>(getAllowedNamespaces(key, file));
if (allNs.isEmpty()) {
return false;
}
XmlFileHeader header = DomService.getInstance().getXmlFileHeader(file);
return allNs.contains(header.getPublicId()) || allNs.contains(header.getSystemId()) || allNs.contains(header.getRootTagNamespace());
}
return true;
}
public boolean acceptsOtherRootTagNames() {
return false;
}
/**
* Get dependency items (the same, as in {@link com.intellij.psi.util.CachedValue}) for file. On any dependency item change, the
* {@link #isMyFile(XmlFile, Module)} method will be invoked once more to ensure that the file description still
* accepts this file.
*
* @param file XML file to get dependencies of
* @return dependency item set
*/
public @NotNull Set<?> getDependencyItems(XmlFile file) {
return Collections.emptySet();
}
/**
* @param reference DOM reference
* @return element, whose all children will be searched for declaration
*/
public @NotNull DomElement getResolveScope(GenericDomValue<?> reference) {
final DomElement annotation = getScopeFromAnnotation(reference);
if (annotation != null) return annotation;
return DomUtil.getRoot(reference);
}
/**
* @param element DOM element
* @return element, whose direct children names will be compared by name. Basically it's parameter element's parent (see {@link ParentScopeProvider}).
*/
public @NotNull DomElement getIdentityScope(DomElement element) {
final DomElement annotation = getScopeFromAnnotation(element);
if (annotation != null) return annotation;
return element.getParent();
}
protected final @Nullable DomElement getScopeFromAnnotation(final DomElement element) {
final Scope scope = element.getAnnotation(Scope.class);
if (scope != null) {
return myScopeProviders.get(scope.value()).getScope(element);
}
return null;
}
/**
* @see Stubbed
* @deprecated define "stubVersion" of {@code com.intellij.dom.fileMetaData} extension instead
*/
@Deprecated
public boolean hasStubs() {
return false;
}
/**
* @see Stubbed
* @deprecated define "stubVersion" of {@code com.intellij.dom.fileMetaData} extension instead
*/
@Deprecated
public int getStubVersion() {
throw new UnsupportedOperationException("define \"stubVersion\" of \"com.intellij.dom.fileMetaData\" extension instead");
}
@Override
public String toString() {
return getRootElementClass() + " <" + getRootTagName() + "> \n" + StringUtil.join(getAllPossibleRootTagNamespaces());
}
}
|
package smartsockets.direct;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import smartsockets.util.NetworkUtils;
/**
* This class implements a multi-SocketAddress (any number of IP addresses
* and port numbers).
*
* It provides an immutable object used by IbisSockets for binding, connecting,
* or as returned values.
*
* @author Jason Maassen
* @version 1.0 Dec 19, 2005
* @since 1.0
*/
public class SocketAddressSet extends SocketAddress implements Comparable {
private static final long serialVersionUID = -2662260670251814982L;
private static final char IP_PORT_SEPERATOR = '-';
private static final char ADDRESS_SEPERATOR = '/';
private final IPAddressSet address;
private final InetSocketAddress [] sas;
private String toStringCache = null;
private SocketAddressSet(IPAddressSet as, InetSocketAddress [] sas) {
this.address = as;
this.sas = sas;
toString();
}
/**
* Construct a new IbisSocketAddress, using InetAddress and a port number.
*
* a valid port value is between 0 and 65535. A port number of zero will
* let the system pick up an ephemeral port in a bind operation.
*
* A null address will assign the wildcard address.
*
* @param address The InetAddress.
* @param port The port number.
*/
public SocketAddressSet(InetAddress address, int port) {
this(IPAddressSet.getFromAddress(new InetAddress[] {address}), port);
}
/**
* Construct a new IbisSocketAddress, using InetSocketAddress
*
* @param address The InetSocketAddress.
*/
public SocketAddressSet(InetSocketAddress address) {
this(address.getAddress(), address.getPort());
}
/**
* Construct a new IbisSocketAddress, using an IbisInetAddress and a port
* number.
*
* a valid port value is between 0 and 65535. A port number of zero will
* let the system pick up an ephemeral port in a bind operation.
*
* A null address will assign the wildcard address.
*
* @param address The IbisInetAddress.
* @param port The port number.
*/
public SocketAddressSet(IPAddressSet address, int port) {
if (port < 0 || port > 65535) {
throw new IllegalArgumentException("Port out of range");
}
if (address == null) {
this.address = IPAddressSet.getLocalHost();
} else {
this.address = address;
}
int len = address.addresses.length;
sas = new InetSocketAddress[len];
for (int i=0;i<len;i++) {
sas[i] = new InetSocketAddress(address.addresses[i], port);
}
toString();
}
/**
* Construct a new IbisSocketAddress, using an IbisInetAddress and an array
* of ports.
*
* A valid port value is between 1 and 65535. A port number of zero is not
* allowed.
*
* A null address will assign the wildcard address.
*
* @param address The IbisInetAddress.
* @param port The port number.
*/
public SocketAddressSet(IPAddressSet address, int [] port) {
if (address == null) {
this.address = IPAddressSet.getLocalHost();
} else {
this.address = address;
}
if (port.length != address.addresses.length) {
throw new IllegalArgumentException("Number of ports does not match"
+ "number of addresses");
}
int len = address.addresses.length;
sas = new InetSocketAddress[len];
for (int i=0;i<len;i++) {
if (port[i] <= 0 || port[i] > 65535) {
throw new IllegalArgumentException("Port["+i+"] out of range");
}
sas[i] = new InetSocketAddress(address.addresses[i], port[i]);
}
toString();
}
/**
* Construct a new IbisSocketAddress from a String representation of an
* IPAddressSet and a port number.
*
* A valid port value is between 0 and 65535. A port number of zero will let
* the system pick up an ephemeral port in a bind operation.
*
* @param address The String representation of an IbisInetAddress.
* @param port The port number.
* @throws UnknownHostException
*/
public SocketAddressSet(String address, int port)
throws UnknownHostException {
this(IPAddressSet.getFromString(address), port);
}
/**
* Construct a new IbisSocketAddress from a String representation of a
* IbisSocketAddress.
*
* This representation contains any number of InetAddresses seperated by
* ADDRESS_SEPARATOR characters (usually defined as '/'), followed by a
* IP_PORT_SEPERATOR (usually '-') and a port number.
*
* This sequence may be repeated any number of times, separated by slashes.
*
* The following examples are valid IPv4 string representations:
*
* 192.168.1.35-1234
* 192.168.1.35/10.0.0.1-1234
* 192.168.1.35/10.0.0.1-1234/192.31.231.65-5678
* 192.168.1.35/10.0.0.1-1234/192.31.231.65/130.37.24.4-5678
*
* We can also handle IPv6:
*
* fe80:0:0:0:2e0:18ff:fe2c:a31%2-1234
*
* Or a mix of the two:
*
* fe80:0:0:0:2e0:18ff:fe2c:a31%2/169.254.207.84-1234
*
* @param addressPort The String representation of a IbisSocketAddress.
* @throws UnknownHostException
*/
public SocketAddressSet(String addressPort) throws UnknownHostException {
int start = 0;
boolean done = false;
IPAddressSet addr = null;
int [] ports = new int[0];
while (!done) {
// We start by selecting a single address and port number from the
// string, starting where we ended the last time.
int colon = addressPort.indexOf(IP_PORT_SEPERATOR, start);
int slash = addressPort.indexOf(ADDRESS_SEPERATOR, colon+1);
// We now seperate the 'address' and 'port' parts. If there is a '/'
// behind the port there is an other address following it. If not,
// this is the last time we go through the loop.
String a = addressPort.substring(start, colon);
String p;
if (slash == -1) {
p = addressPort.substring(colon+1);
done = true;
} else {
p = addressPort.substring(colon+1, slash);
start = slash+1;
}
// Now convert the address and port strings to real values ...
IPAddressSet tA = IPAddressSet.getFromString(a);
int tP = Integer.parseInt(p);
// ... do a sanity check on the port value ...
if (tP <= 0 || tP > 65535) {
throw new IllegalArgumentException("Port out of range: " + tP);
}
// ... and merge the result into what was already there.
addr = IPAddressSet.merge(addr, tA);
ports = add(ports, tP, tA.addresses.length);
}
// Finally, store the result in the object fields.
address = addr;
int len = addr.addresses.length;
sas = new InetSocketAddress[len];
for (int i=0;i<len;i++) {
sas[i] = new InetSocketAddress(addr.addresses[i], ports[i]);
}
toString();
}
/**
* This method appends a value a specified number of times to an existing
* int array. A new array is returned.
*
* @param orig the original array
* @param value the value to append
* @param repeat the number of times the value should be appended.
* @return a new array
*/
private int [] add(int [] orig, int value, int repeat) {
int [] result = new int[orig.length+repeat];
System.arraycopy(orig, 0, result, 0, orig.length);
Arrays.fill(result, orig.length, result.length, value);
return result;
}
/**
* Gets the InetAddressSet.
*
* @return the InetAddressSet.
*/
public IPAddressSet getAddressSet() {
return address;
}
/**
* Gets the SocketAddresses.
*
* @return the ports.
*/
public InetSocketAddress [] getSocketAddresses() {
return sas;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
// TODO: improve
return address.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
// Check pointers
if (this == other) {
return true;
}
// Check type
if (!(other instanceof SocketAddressSet)) {
return false;
}
SocketAddressSet tmp = (SocketAddressSet) other;
// System.out.println("SocketAdressSet.equals: ");
// System.out.println("arrays : " + Arrays.equals(sas, tmp.sas));
// System.out.println("address: " + address.equals(tmp.address));
// Finally, compare ports and addresses
// TODO: this is only correct if the addresses are exactly the same.
// So how do we handle partial addresses ?
for (int i=0;i<sas.length;i++) {
InetSocketAddress a = sas[i];
boolean found = false;
for (int j=0;j<tmp.sas.length;j++) {
if (a.equals(tmp.sas[j])) {
found = true;
break;
}
}
if (!found) {
// System.err.println("SAS: " + this + " != SAS: " + tmp);
return false;
}
}
// System.err.println("SAS: " + this + " == SAS: " + tmp);
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
if (toStringCache == null) {
StringBuffer b = new StringBuffer();
final int len = address.addresses.length;
for (int i=0;i<len;i++) {
b.append(NetworkUtils.ipToString(address.addresses[i]));
if (i < len-1) {
if (sas[i].getPort() != sas[i+1].getPort()) {
b.append(IP_PORT_SEPERATOR);
b.append(sas[i].getPort());
}
b.append(ADDRESS_SEPERATOR);
} else {
b.append(IP_PORT_SEPERATOR);
b.append(sas[i].getPort());
}
}
toStringCache = b.toString();
}
return toStringCache;
}
/**
* Merges two IbisSocketAddresses.
*
* @param s1 the first IbisSocketAddress
* @param s2 the second IbisSocketAddress
* @return a new SmartSocketAddress
*/
public static SocketAddressSet merge(SocketAddressSet s1,
SocketAddressSet s2) {
IPAddressSet as = IPAddressSet.merge(s1.address, s2.address);
InetSocketAddress [] sa =
new InetSocketAddress[s1.sas.length + s2.sas.length];
System.arraycopy(s1.sas, 0, sa, 0, s1.sas.length);
System.arraycopy(s2.sas, 0, sa, s1.sas.length, s2.sas.length);
Arrays.sort(sa, IPAddressSet.SORTER);
return new SocketAddressSet(as, sa);
}
/**
* Converts an array of SocketAddressSets to a String array.
*
* @param s the array of {@link SocketAddressSet}
* @return a new String array containing the {@link String} representations
* of the {@link SocketAddressSet}s, or <code>null</code> if
* s was <code>null</code>
*/
public static String [] convertToStrings(SocketAddressSet [] s) {
if (s == null) {
return null;
}
String [] result = new String[s.length];
for (int i=0;i<s.length;i++) {
if (s[i] != null) {
result[i] = s[i].toString();
}
}
return result;
}
/**
* Converts an array of Strings into an array of SocketAddressSets.
*
* @param s the array of {@link String} to convert
* @param ignoreProblems indicates if conversion problems should be silently
* ignored.
* @return a new array containing the {@link SocketAddressSet}s
* or <code>null</code> if s was <code>null</code>
* @throws UnknownHostException when any of the Strings cannot be converted
* and ignoreProblems is false
*/
public static SocketAddressSet [] convertToSocketAddressSet(String [] s,
boolean ignoreProblems) throws UnknownHostException {
if (s == null) {
return null;
}
SocketAddressSet [] result = new SocketAddressSet[s.length];
for (int i=0;i<s.length;i++) {
if (s[i] != null) {
if (ignoreProblems) {
try {
result[i] = new SocketAddressSet(s[i]);
} catch (UnknownHostException e) {
// ignore
}
} else {
result[i] = new SocketAddressSet(s[i]);
}
}
}
return result;
}
/**
* Converts an array of Strings into an array of SocketAddressSets.
*
* @param s the array of {@link String} to convert
* @return a new array containing the {@link SocketAddressSet}s
* or <code>null</code> if s was <code>null</code>
* @throws UnknownHostException when any of the Strings cannot be converted
*/
public static SocketAddressSet [] convertToSocketAddressSet(String [] s)
throws UnknownHostException {
return convertToSocketAddressSet(s, false);
}
/**
* Returns if the other SocketAddressSet represents the same machine as
* this one.
*
* @param other the SocketAddressSet to compare to
* @return if both SocketAddressSets represent the same machine
*/
public boolean sameMachine(SocketAddressSet other) {
return address.equals(other.address);
}
/**
* Returns if the other SocketAddressSet represents the same process as
* this one.
*
* @param other the SocketAddressSet to compare to
* @return if both SocketAddressSets represent the same process
*/
public boolean sameProcess(SocketAddressSet other) {
return equals(other);
}
/**
* Returns if the two SocketAddressSets represent the same machine.
*
*/
public static boolean sameMachine(SocketAddressSet a, SocketAddressSet b) {
return a.sameMachine(b);
}
/**
* Returns if the two SocketAddressSets represent the same process.
*
*/
public static boolean sameProcess(SocketAddressSet a, SocketAddressSet b) {
return a.sameProcess(b);
}
public int compareTo(Object other) {
if (this == other) {
return 0;
}
// Check type
if (!(other instanceof SocketAddressSet)) {
return 0;
}
SocketAddressSet tmp = (SocketAddressSet) other;
if (hashCode() < tmp.hashCode()) {
return -1;
} else {
return 1;
}
}
public boolean isCompatible(SocketAddressSet target) {
return equals(target);
}
}
|
package soot.jimple.infoflow;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import heros.flowfunc.KillAll;
import heros.solver.PathEdge;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Local;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.data.AbstractionWithPath;
import soot.jimple.infoflow.data.AccessPath;
import soot.jimple.infoflow.heros.InfoflowSolver;
import soot.jimple.infoflow.source.DefaultSourceSinkManager;
import soot.jimple.infoflow.source.ISourceSinkManager;
import soot.jimple.infoflow.util.BaseSelector;
import soot.jimple.toolkits.ide.icfg.JimpleBasedBiDiICFG;
public class InfoflowProblem extends AbstractInfoflowProblem {
private InfoflowSolver bSolver;
private final ISourceSinkManager sourceSinkManager;
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Computes the taints produced by a taint wrapper object
* @param iStmt The call statement the taint wrapper shall check for well-
* known methods that introduce black-box taint propagation
* @param source The taint source
* @return The taints computed by the wrapper
*/
private Set<Abstraction> computeWrapperTaints
(final Stmt iStmt,
Abstraction source) {
Set<Abstraction> res = new HashSet<Abstraction>();
if(taintWrapper == null)
return Collections.emptySet();
if (!source.getAccessPath().isStaticFieldRef())
if(iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
boolean found = iiExpr.getBase().equals(source.getAccessPath().getPlainValue());
if (!found)
for (Value param : iiExpr.getArgs())
if (source.getAccessPath().getPlainValue().equals(param)) {
found = true;
break;
}
if (!found)
return Collections.emptySet();
}
Set<AccessPath> vals = taintWrapper.getTaintsForMethod(iStmt, source.getAccessPath());
if(vals != null) {
for (AccessPath val : vals) {
Abstraction newAbs = source.deriveNewAbstraction(val);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) newAbs).addPathElement(iStmt);
res.add(newAbs);
// If the taint wrapper taints the base object (new taint), this must be propagated
// backwards as there might be aliases for the base object
if(iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if(iiExpr.getBase().equals(newAbs.getAccessPath().getPlainValue())
|| newAbs.getAccessPath().isStaticFieldRef()) {
Abstraction bwAbs = source.deriveNewAbstraction(val, false);
for (Unit predUnit : interproceduralCFG().getPredsOf(iStmt))
bSolver.processEdge(new PathEdge<Unit, Abstraction>(bwAbs, predUnit, bwAbs));
}
}
}
}
return res;
}
@Override
public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
/**
* Creates a new taint abstraction for the given value
* @param src The source statement from which the taint originated
* @param targetValue The target value that shall now be tainted
* @param source The incoming taint abstraction from the source
* @param taintSet The taint set to which to add all newly produced
* taints
*/
private void addTaintViaStmt
(final Unit src,
final Value targetValue,
Abstraction source,
Set<Abstraction> taintSet,
boolean cutFirstField) {
// Keep the original taint
taintSet.add(source);
// Strip array references to their respective base
Value baseTarget = targetValue;
if (targetValue instanceof ArrayRef)
baseTarget = ((ArrayRef) targetValue).getBase();
// also taint the target of the assignment
Abstraction newAbs = source.deriveNewAbstraction(baseTarget, cutFirstField, src);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) newAbs).addPathElement(src);
taintSet.add(newAbs);
// call backwards-check for heap-objects only
if (triggerInaktiveTaintOrReverseFlow(targetValue, source) && source.isAbstractionActive())
// If we overwrite the complete local, there is no need for
// a backwards analysis
if (!(targetValue.equals(newAbs.getAccessPath().getPlainValue())
&& newAbs.getAccessPath().isLocal())) {
Abstraction bwAbs = newAbs.deriveInactiveAbstraction();
for (Unit predUnit : interproceduralCFG().getPredsOf(src)) {
bSolver.processEdge(new PathEdge<Unit, Abstraction>(bwAbs.getAbstractionFromCallEdge(), predUnit, bwAbs));
}
}
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
// If we compute flows on parameters, we create the initial
// flow fact here
if (src instanceof IdentityStmt) {
final IdentityStmt is = (IdentityStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
boolean addOriginal = true;
if (is.getRightOp() instanceof CaughtExceptionRef) {
if (source.getExceptionThrown()) {
res.add(source.deriveNewAbstractionOnCatch(is.getLeftOp(), is));
addOriginal = false;
}
}
if (addOriginal)
res.add(source);
if (sourceSinkManager.isSource(is, interproceduralCFG())) {
Abstraction abs;
if (pathTracking != PathTrackingMethod.NoTracking)
abs = new AbstractionWithPath(is.getLeftOp(),
is.getRightOp(),
is, false, true, is).addPathElement(is);
else
abs = new Abstraction(is.getLeftOp(),
is.getRightOp(), is, false, true, is);
abs.setZeroAbstraction(source.getZeroAbstraction());
res.add(abs);
}
return res;
}
};
}
// taint is propagated with assignStmt
else if (src instanceof AssignStmt) {
final AssignStmt assignStmt = (AssignStmt) src;
Value right = assignStmt.getRightOp();
Value left = assignStmt.getLeftOp();
final Value leftValue = BaseSelector.selectBase(left, true);
final Set<Value> rightVals = BaseSelector.selectBaseList(right, true);
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
boolean addLeftValue = false;
boolean cutFirstField = false;
Set<Abstraction> res = new HashSet<Abstraction>();
// shortcuts:
// on NormalFlow taint cannot be created
if (source.equals(zeroValue)) {
return Collections.emptySet();
}
Abstraction newSource;
if (!source.isAbstractionActive() && (src.equals(source.getActivationUnit()) || src.equals(source.getActivationUnitOnCurrentLevel()))){
newSource = source.getActiveCopy(false);
}else{
newSource = source;
}
for (Value rightValue : rightVals) {
// check if static variable is tainted (same name, same class)
//y = X.f && X.f tainted --> y, X.f tainted
if (newSource.getAccessPath().isStaticFieldRef() && rightValue instanceof StaticFieldRef) {
StaticFieldRef rightRef = (StaticFieldRef) rightValue;
if (newSource.getAccessPath().getFirstField().equals(rightRef.getField())) {
addLeftValue = true;
cutFirstField = true;
}
}
// if both are fields, we have to compare their fieldName via equals and their bases
//y = x.f && x tainted --> y, x tainted
//y = x.f && x.f tainted --> y, x tainted
else if (rightValue instanceof InstanceFieldRef) {
InstanceFieldRef rightRef = (InstanceFieldRef) rightValue;
Local rightBase = (Local) rightRef.getBase();
Local sourceBase = newSource.getAccessPath().getPlainLocal();
if (rightBase.equals(sourceBase)) {
if (newSource.getAccessPath().isInstanceFieldRef()) {
if (rightRef.getField().equals(newSource.getAccessPath().getFirstField())) {
addLeftValue = true;
cutFirstField = true;
}
}
else
addLeftValue = true;
}
}
// indirect taint propagation:
// if rightvalue is local and source is instancefield of this local:
// y = x && x.f tainted --> y.f, x.f tainted
// y.g = x && x.f tainted --> y.g.f, x.f tainted
else if (rightValue instanceof Local && newSource.getAccessPath().isInstanceFieldRef()) {
Local base = newSource.getAccessPath().getPlainLocal();
if (rightValue.equals(base)) {
addLeftValue = true;
}
}
//y = x[i] && x tainted -> x, y tainted
else if (rightValue instanceof ArrayRef) {
Local rightBase = (Local) ((ArrayRef) rightValue).getBase();
if (rightBase.equals(newSource.getAccessPath().getPlainValue()))
addLeftValue = true;
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
//y = x && x tainted --> y, x tainted
else if (rightValue.equals(newSource.getAccessPath().getPlainValue())) {
addLeftValue = true;
}
}
// if one of them is true -> add leftValue
if (addLeftValue) {
if (sourceSinkManager.isSink(assignStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(leftValue, assignStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPath(),
assignStmt);
else
results.addResult(leftValue, assignStmt,
newSource.getSource(), newSource.getSourceContext());
}
if(triggerInaktiveTaintOrReverseFlow(leftValue, newSource) || newSource.isAbstractionActive())
addTaintViaStmt(src, leftValue, newSource, res, cutFirstField);
res.add(newSource);
return res;
}
// If we have propagated taint, we have returned from this method by now
//if leftvalue contains the tainted value -> it is overwritten - remove taint:
//but not for arrayRefs:
// x[i] = y --> taint is preserved since we do not distinguish between elements of collections
//because we do not use a MUST-Alias analysis, we cannot delete aliases of taints
if (assignStmt.getLeftOp() instanceof ArrayRef)
return Collections.singleton(newSource);
if(newSource.getAccessPath().isInstanceFieldRef()) {
//x.f = y && x.f tainted --> no taint propagated
if (leftValue instanceof InstanceFieldRef) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
if (leftRef.getBase().equals(newSource.getAccessPath().getPlainValue())) {
if (leftRef.getField().equals(newSource.getAccessPath().getFirstField())) {
return Collections.emptySet();
}
}
}
//x = y && x.f tainted -> no taint propagated
else if (leftValue instanceof Local){
if (leftValue.equals(newSource.getAccessPath().getPlainValue())) {
return Collections.emptySet();
}
}
}
//X.f = y && X.f tainted -> no taint propagated
else if(newSource.getAccessPath().isStaticFieldRef()){
if(leftValue instanceof StaticFieldRef && ((StaticFieldRef)leftValue).getField().equals(newSource.getAccessPath().getFirstField())){
return Collections.emptySet();
}
}
//when the fields of an object are tainted, but the base object is overwritten
// then the fields should not be tainted any more
//x = y && x.f tainted -> no taint propagated
else if(newSource.getAccessPath().isLocal() && leftValue.equals(newSource.getAccessPath().getPlainValue())){
return Collections.emptySet();
}
//nothing applies: z = y && x tainted -> taint is preserved
res.add(newSource);
return res;
}
};
}
// for unbalanced problems, return statements correspond to
// normal flows, not return flows, because there is no return
// site we could jump to
else if (src instanceof ReturnStmt) {
final ReturnStmt returnStmt = (ReturnStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (returnStmt.getOp().equals(source.getAccessPath().getPlainValue()) && sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPath(),
returnStmt);
else
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(), source.getSourceContext());
}
return Collections.singleton(source);
}
};
}
else if (src instanceof ThrowStmt) {
final ThrowStmt throwStmt = (ThrowStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (throwStmt.getOp().equals(source.getAccessPath().getPlainLocal()))
return Collections.singleton(source.deriveNewAbstractionOnThrow());
return Collections.singleton(source);
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
if (!dest.isConcrete()){
logger.debug("Call skipped because target has no body: {} -> {}", src, dest);
return KillAll.v();
}
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = stmt.getInvokeExpr();
final List<Value> callArgs = ie.getArgs();
final List<Value> paramLocals = new ArrayList<Value>();
for (int i = 0; i < dest.getParameterCount(); i++) {
paramLocals.add(dest.getActiveBody().getParameterLocal(i));
}
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
if(taintWrapper != null && taintWrapper.isExclusive(stmt, source.getAccessPath())) {
//taint is propagated in CallToReturnFunction, so we do not need any taint here:
return Collections.emptySet();
}
//if we do not have to look into sinks:
if (!inspectSinks && sourceSinkManager.isSink(stmt, interproceduralCFG())) {
return Collections.emptySet();
}
Set<Abstraction> res = new HashSet<Abstraction>();
// check if whole object is tainted (happens with strings, for example:)
if (!dest.isStatic() && ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
// this might be enough because every call must happen with a local variable which is tainted itself:
if (vie.getBase().equals(source.getAccessPath().getPlainValue())) {
Abstraction abs = source.deriveNewAbstraction(source.getAccessPath().copyWithNewValue
(dest.getActiveBody().getThisLocal()));
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(stmt);
//add new callArgs:
assert abs != source; // our source abstraction must be immutable
abs.setAbstractionFromCallEdge(abs.clone());
res.add(abs);
}
}
//special treatment for clinit methods - no param mapping possible
if(!dest.getName().equals("<clinit>")) {
assert dest.getParameterCount() == callArgs.size();
// check if param is tainted:
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(source.getAccessPath().getPlainLocal()) &&
(triggerInaktiveTaintOrReverseFlow(callArgs.get(i), source) || source.isAbstractionActive())) {
Abstraction abs = source.deriveNewAbstraction(source.getAccessPath().copyWithNewValue
(paramLocals.get(i)));
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(stmt);
assert abs != source; // our source abstraction must be immutable
abs.setAbstractionFromCallEdge(abs.clone());
res.add(abs);
}
}
}
// staticfieldRefs must be analyzed even if they are not part of the params:
if (source.getAccessPath().isStaticFieldRef()) {
Abstraction abs;
abs = source.clone();
assert (abs.equals(source) && abs.hashCode() == source.hashCode());
assert abs != source; // our source abstraction must be immutable
abs.setAbstractionFromCallEdge(abs.clone());
res.add(abs);
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(final Unit callSite, final SootMethod callee, final Unit exitStmt, final Unit retSite) {
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.emptySet();
}
//activate taint if necessary, but in any case we have to take the previous call edge abstraction
Abstraction newSource;
if(!source.isAbstractionActive()){
if(callSite != null
&& (callSite.equals(source.getActivationUnit()) || callSite.equals(source.getActivationUnitOnCurrentLevel())) ){
newSource = source.getActiveCopy(true);
}else{
newSource = source.cloneUsePredAbstractionOfCG();
}
}else{
newSource = source.cloneUsePredAbstractionOfCG();
}
//if abstraction is not active and activeStmt was in this method, it will not get activated = it can be removed:
if(!newSource.isAbstractionActive() && newSource.getActivationUnit() != null
&& interproceduralCFG().getMethodOf(newSource.getActivationUnit()).equals(callee))
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
// Check whether this return is treated as a sink
if (exitStmt instanceof ReturnStmt) {
ReturnStmt returnStmt = (ReturnStmt) exitStmt;
assert returnStmt.getOp() == null
|| returnStmt.getOp() instanceof Local
|| returnStmt.getOp() instanceof Constant;
if (returnStmt.getOp() != null
&& newSource.getAccessPath().isLocal()
&& newSource.getAccessPath().getPlainValue().equals(returnStmt.getOp())
&& sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPath(),
returnStmt);
else
results.addResult(returnStmt.getOp(), returnStmt,
newSource.getSource(), newSource.getSourceContext());
}
}
// If we have no caller, we have nowhere to propagate. This
// can happen when leaving the main method.
if (callSite == null)
return Collections.emptySet();
// if we have a returnStmt we have to look at the returned value:
if (exitStmt instanceof ReturnStmt) {
ReturnStmt returnStmt = (ReturnStmt) exitStmt;
Value retLocal = returnStmt.getOp();
if (callSite instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) callSite;
Value leftOp = defnStmt.getLeftOp();
if (retLocal.equals(newSource.getAccessPath().getPlainLocal()) &&
(triggerInaktiveTaintOrReverseFlow(leftOp, newSource) || newSource.isAbstractionActive())) {
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(leftOp), callSite);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(exitStmt);
assert abs != newSource; // our source abstraction must be immutable
res.add(abs);
//call backwards-solver:
if(triggerInaktiveTaintOrReverseFlow(leftOp, abs)){
Abstraction bwAbs = newSource.deriveNewAbstraction
(newSource.getAccessPath().copyWithNewValue(leftOp), false);
if (abs.isAbstractionActive())
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction>(bwAbs, predUnit, bwAbs));
}
}
}
}
// easy: static
if (newSource.getAccessPath().isStaticFieldRef()) {
// Simply pass on the taint
res.add(newSource);
// call backwards-check:
Abstraction bwAbs = newSource.deriveInactiveAbstraction();
if (newSource.isAbstractionActive())
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction>(bwAbs, predUnit, bwAbs));
}
// checks: this/params/fields
// check one of the call params are tainted (not if simple type)
Value sourceBase = newSource.getAccessPath().getPlainLocal();
Value originalCallArg = null;
for (int i = 0; i < callee.getParameterCount(); i++) {
if (callee.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
if (callSite instanceof Stmt) {
Stmt iStmt = (Stmt) callSite;
originalCallArg = iStmt.getInvokeExpr().getArg(i);
//either the param is a fieldref (not possible in jimple?) or an array Or one of its fields is tainted/all fields are tainted
if (triggerInaktiveTaintOrReverseFlow(originalCallArg, newSource)) {
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(originalCallArg), callSite);
if (pathTracking == PathTrackingMethod.ForwardTracking)
abs = ((AbstractionWithPath) abs).addPathElement(exitStmt);
res.add(abs);
if(triggerInaktiveTaintOrReverseFlow(originalCallArg, abs)){
// call backwards-check:
Abstraction bwAbs = abs.deriveInactiveAbstraction();
if (abs.isAbstractionActive())
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
if (!callee.isStatic()) {
Local thisL = callee.getActiveBody().getThisLocal();
if (thisL.equals(sourceBase)) {
boolean param = false;
// check if it is not one of the params (then we have already fixed it)
for (int i = 0; i < callee.getParameterCount(); i++) {
if (callee.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
param = true;
break;
}
}
if (!param) {
if (callSite instanceof Stmt) {
Stmt stmt = (Stmt) callSite;
if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(iIExpr.getBase()));
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(stmt);
res.add(abs);
if(triggerInaktiveTaintOrReverseFlow(iIExpr.getBase(), abs)){
Abstraction bwAbs = abs.deriveInactiveAbstraction();
if (abs.isAbstractionActive())
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
// special treatment for native methods:
if (call instanceof Stmt) {
final Stmt iStmt = (Stmt) call;
final InvokeExpr invExpr = iStmt.getInvokeExpr();
final List<Value> callArgs = iStmt.getInvokeExpr().getArgs();
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Abstraction newSource;
//check inactive elements:
if (!source.isAbstractionActive() && (call.equals(source.getActivationUnit()))|| call.equals(source.getActivationUnitOnCurrentLevel())){
newSource = source.getActiveCopy(false);
}else{
newSource = source;
}
Set<Abstraction> res = new HashSet<Abstraction>();
res.addAll(computeWrapperTaints(iStmt, newSource));
// We can only pass on a taint if it is neither a parameter nor the
// base object of the current call. If this call overwrites the left
// side, the taint is never passed on.
boolean passOn = !(call instanceof AssignStmt && ((AssignStmt) call).getLeftOp().equals
(newSource.getAccessPath().getPlainLocal()));
//we only can remove the taint if we step into the call/return edges
//otherwise we will loose taint - see ArrayTests/arrayCopyTest
if (passOn)
if(hasValidCallees(call) || (taintWrapper != null
&& taintWrapper.isExclusive(iStmt, newSource.getAccessPath()))) {
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr)
if (((InstanceInvokeExpr) iStmt.getInvokeExpr()).getBase().equals
(newSource.getAccessPath().getPlainLocal())) {
passOn = false;
}
if (passOn)
for (int i = 0; i < callArgs.size(); i++)
if (callArgs.get(i).equals(newSource.getAccessPath().getPlainLocal()) && isTransferableValue(callArgs.get(i))) {
passOn = false;
break;
}
//static variables are always propagated if they are not overwritten. So if we have at least one call/return edge pair,
//we can be sure that the value does not get "lost" if we do not pass it on:
if(newSource.getAccessPath().isStaticFieldRef()){
passOn = false;
}
}
if (passOn)
res.add(newSource);
if (iStmt.getInvokeExpr().getMethod().isNative()) {
if (callArgs.contains(newSource.getAccessPath().getPlainValue())) {
// java uses call by value, but fields of complex objects can be changed (and tainted), so use this conservative approach:
res.addAll(ncHandler.getTaintedValues(iStmt, newSource, callArgs));
}
}
// Sources can either be assignments like x = getSecret() or
// instance method calls like constructor invocations
if (source == zeroValue && (iStmt instanceof AssignStmt || invExpr instanceof InstanceInvokeExpr)) {
if (sourceSinkManager.isSource(iStmt, interproceduralCFG())) {
final Value target;
if (iStmt instanceof AssignStmt)
target = ((AssignStmt) iStmt).getLeftOp();
else {
target = ((InstanceInvokeExpr) invExpr).getBase();
}
final Abstraction abs;
if (pathTracking == PathTrackingMethod.ForwardTracking)
abs = new AbstractionWithPath(target,
iStmt.getInvokeExpr(),
iStmt, false, true, iStmt).addPathElement(call);
else
abs = new Abstraction(target,
iStmt.getInvokeExpr(), iStmt, false, true, iStmt);
abs.setZeroAbstraction(source.getZeroAbstraction());
res.add(abs);
res.remove(zeroValue);
}
}
// if we have called a sink we have to store the path from the source - in case one of the params is tainted!
if (sourceSinkManager.isSink(iStmt, interproceduralCFG())) {
boolean taintedParam = false;
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(newSource.getAccessPath().getPlainLocal())) {
taintedParam = true;
break;
}
}
if (taintedParam) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPath(),
call);
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(), newSource.getSourceContext());
}
// if the base object which executes the method is tainted the sink is reached, too.
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if (vie.getBase().equals(newSource.getAccessPath().getPlainValue())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPath(),
call);
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(), newSource.getSourceContext());
}
}
}
return res;
}
/**
* Checks whether the given call has at least one valid target,
* i.e. a callee with a body.
* @param call The call site to check
* @return True if there is at least one callee implementation
* for the given call, otherwise false
*/
private boolean hasValidCallees(Unit call) {
Set<SootMethod> callees = interproceduralCFG().getCalleesOfCallAt(call);
for (SootMethod callee : callees)
if (callee.isConcrete())
return true;
return false;
}
};
}
return Identity.v();
}
};
}
public InfoflowProblem(List<String> sourceList, List<String> sinkList) {
this(new JimpleBasedBiDiICFG(), new DefaultSourceSinkManager(sourceList, sinkList));
}
public InfoflowProblem(ISourceSinkManager sourceSinkManager) {
this(new JimpleBasedBiDiICFG(), sourceSinkManager);
}
public InfoflowProblem(InterproceduralCFG<Unit, SootMethod> icfg, List<String> sourceList, List<String> sinkList) {
this(icfg, new DefaultSourceSinkManager(sourceList, sinkList));
}
public InfoflowProblem(InterproceduralCFG<Unit, SootMethod> icfg, ISourceSinkManager sourceSinkManager) {
super(icfg);
this.sourceSinkManager = sourceSinkManager;
}
public InfoflowProblem(ISourceSinkManager mySourceSinkManager, Set<Unit> analysisSeeds) {
this(new JimpleBasedBiDiICFG(), mySourceSinkManager);
for (Unit u : analysisSeeds)
this.initialSeeds.put(u, Collections.singleton(zeroValue));
}
public void setBackwardSolver(InfoflowSolver backwardSolver){
bSolver = backwardSolver;
}
@Override
public boolean autoAddZero() {
return false;
}
}
|
package duro.runtime;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import duro.debugging.Debug;
import duro.transcriber.Journal;
public class CustomProcess extends Process implements Iterable<Object> {
private static final long serialVersionUID = 1L;
private static final Instruction[] FORWARD_CALL_INSTRUCTIONS = new Instruction[] {
new Instruction(Instruction.OPCODE_FORWARD_CALL),
new Instruction(Instruction.OPCODE_RET_FORWARD)
};
public static class Frame implements Serializable {
private static final long serialVersionUID = 1L;
public final Process self;
public Object[] arguments;
public Object[] variables;
public final Instruction[] instructions;
public int instructionPointer;
public Stack<Object> stack = new Stack<Object>();
public FrameProcess reification;
public Frame(Process self, Object[] arguments, int variableCount, Instruction[] instructions) {
this.self = self;
this.arguments = arguments;
variables = new Object[variableCount];
this.instructions = instructions;
}
public Frame(Process self, Object[] arguments, Object[] variables, Instruction[] instructions) {
this.self = self;
this.arguments = arguments;
this.variables = variables;
this.instructions = instructions;
}
}
private Frame currentFrame;
private Stack<Frame> frameStack = new Stack<Frame>();
private DictionaryProcess any;
public CustomProcess(int parameterCount, int variableCount, Instruction[] instructions) {
// TODO: Consider: Should the Any prototype be this? Should CustomProcess be a DictionaryProcess?
// Should CustomProcess not be a process at all? Should CustomProcess hold any and push it instead this? - Also at other locations, e.g. when loading.
// Add Any prototype
any = new DictionaryProcess();
any.defineShared("Any", any);
// Add Iterable prototype
DictionaryProcess iterable = any.clone();
any.defineShared("Iterable", iterable);
// Add Iterator prototype
any.defineShared("Iterator", any.clone());
// Add Array prototype
any.defineShared("Array", iterable.clone());
// Add String prototype
any.defineShared("String", any.clone());
// Add Integer prototype
any.defineShared("Integer", any.clone());
// Add Frame prototype
any.defineShared("Frame", any.clone());
currentFrame = new Frame(any, new Object[parameterCount], variableCount, instructions);
}
@Override
public void replay(List<Instruction> commands) {
Debug.println(Debug.LEVEL_HIGH, "replay");
for(Instruction instruction: commands) {
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "replay: " + instruction);
next(instruction);
}
if(currentFrame != null)
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "/replay");
}
private boolean stopRequested;
private void next(Instruction instruction) {
switch(instruction.opcode) {
case Instruction.OPCODE_PAUSE: {
stopRequested = true;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_INC_IP: {
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_FINISH: {
stopRequested = true;
currentFrame = null;
break;
} case Instruction.OPCODE_DUP: {
currentFrame.stack.push(currentFrame.stack.peek());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DUP1: {
int index = currentFrame.stack.size() - 2;
currentFrame.stack.add(index, currentFrame.stack.peek());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DUP2: {
int index = currentFrame.stack.size() - 3;
currentFrame.stack.add(index, currentFrame.stack.peek());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DUP_ANY: {
int sourceOffset = (int)instruction.operand1;
int insertionOffset = (int)instruction.operand2;
int top = currentFrame.stack.size() - 1;
Object sourceValue = currentFrame.stack.get(top - sourceOffset);
currentFrame.stack.add(top - insertionOffset, sourceValue);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_STORE_LOC: {
int ordinal = (int)instruction.operand1;
Object value = currentFrame.stack.pop();
currentFrame.variables[ordinal] = value;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_POP: {
currentFrame.stack.pop();
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SWAP: {
Object tmp = currentFrame.stack.get(currentFrame.stack.size() - 1);
currentFrame.stack.set(currentFrame.stack.size() - 1, currentFrame.stack.get(currentFrame.stack.size() - 2));
currentFrame.stack.set(currentFrame.stack.size() - 2, tmp);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SWAP1: {
Object tmp = currentFrame.stack.get(currentFrame.stack.size() - 2);
currentFrame.stack.set(currentFrame.stack.size() - 2, currentFrame.stack.get(currentFrame.stack.size() - 3));
currentFrame.stack.set(currentFrame.stack.size() - 3, tmp);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SWAP_ANY: {
int top = currentFrame.stack.size() - 1;
int index1 = top - (int)instruction.operand1; // operand1: offsetFromTop0 for first index
int index2 = top - (int)instruction.operand2; // operand2: offsetFromTop0 for second index
Object tmp = currentFrame.stack.get(index1);
currentFrame.stack.set(index1, currentFrame.stack.get(index2));
currentFrame.stack.set(index2, tmp);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SEND: {
String key = (String)instruction.operand1;
int argumentCount = (int)instruction.operand2;
Process receiver = (Process)currentFrame.stack.get(currentFrame.stack.size() - argumentCount - 1);
Object callable = receiver.getCallable(key);
if(callable instanceof CallFrameInfo) {
CallFrameInfo callFrameInfo = (CallFrameInfo)callable;
Object[] arguments = new Object[callFrameInfo.argumentCount];
for(int i = callFrameInfo.argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
currentFrame.stack.pop(); // Pop receiver
frameStack.push(currentFrame);
currentFrame = new Frame(receiver, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
} else {
Object[] arguments = new Object[argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
currentFrame.stack.pop(); // Pop receiver
Process process = (Process)callable;
frameStack.push(currentFrame);
currentFrame = new Frame(process, arguments, 0, FORWARD_CALL_INSTRUCTIONS);
}
break;
} case Instruction.OPCODE_CALL: {
int argumentCount = (int)instruction.operand1;
Object callable = currentFrame.stack.get(currentFrame.stack.size() - argumentCount - 1);
if(callable instanceof CallFrameInfo) {
CallFrameInfo callFrameInfo = (CallFrameInfo)callable;
Object[] arguments = new Object[callFrameInfo.argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
currentFrame.stack.pop(); // Pop receiver
frameStack.push(currentFrame);
currentFrame = new Frame(currentFrame.self, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
} else {
Object[] arguments = new Object[argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
currentFrame.stack.pop(); // Pop receiver
Process process = (Process)callable;
frameStack.push(currentFrame);
currentFrame = new Frame(process, arguments, 0, FORWARD_CALL_INSTRUCTIONS);
}
break;
} case Instruction.OPCODE_FORWARD_CALL: {
Object[] arguments = currentFrame.arguments;
Process proxyCallable = currentFrame.self;
Object callable = proxyCallable.getCallable("call");
if(callable instanceof CallFrameInfo) {
CallFrameInfo callFrameInfo = (CallFrameInfo)callable;
Object[] callArguments;
if(arguments.length < callFrameInfo.argumentCount) {
callArguments = new Object[callFrameInfo.argumentCount];
System.arraycopy(arguments, 0, callFrameInfo.argumentCount, 0, arguments.length);
} else
callArguments = arguments;
frameStack.push(currentFrame);
currentFrame = new Frame(currentFrame.self, callArguments, callFrameInfo.variableCount, callFrameInfo.instructions);
} else {
Process process = (Process)callable;
frameStack.push(currentFrame);
currentFrame = new Frame(process, arguments, 0, FORWARD_CALL_INSTRUCTIONS);
}
break;
} case Instruction.OPCODE_RESUME: {
Frame frame = (Frame)currentFrame.stack.pop();
frameStack.push(currentFrame);
currentFrame = frame;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_RET: {
int returnCount = (int)instruction.operand1;
Frame outerFrame = frameStack.pop();
for(int i = 0; i < returnCount; i++)
outerFrame.stack.push(currentFrame.stack.pop());
currentFrame = outerFrame;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_RET_THIS: {
Object result = currentFrame.self;
currentFrame = frameStack.pop();
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_RET_FORWARD: {
Frame outerFrame = frameStack.pop();
outerFrame.stack.addAll(currentFrame.stack);
currentFrame = outerFrame;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_IF_TRUE: {
boolean value = (boolean)currentFrame.stack.pop();
if(value) {
int jump = (int)instruction.operand1;
currentFrame.instructionPointer += jump;
} else
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_IF_FALSE: {
boolean value = (boolean)currentFrame.stack.pop();
if(!value) {
int jump = (int)instruction.operand1;
currentFrame.instructionPointer += jump;
} else
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_JUMP: {
int jump = (int)instruction.operand1;
currentFrame.instructionPointer += jump;
break;
} case Instruction.OPCODE_SET: {
Object value = currentFrame.stack.pop();
StringProcess key = (StringProcess)currentFrame.stack.pop(); // Assumed to be string only
Process receiver = (Process)currentFrame.stack.pop();
receiver.define(key.str, value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_GET: {
StringProcess key = (StringProcess)currentFrame.stack.pop(); // Assumed to be string only
Process receiver = (Process)currentFrame.stack.pop();
Object value = receiver.lookup(key.str);
currentFrame.stack.push(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_EXEC_ON_FRAME: {
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
Frame frame = (Frame)currentFrame.stack.pop();
// Move forward arguments
// Object[] arguments = new Object[frame.arguments.length + callFrameInfo.argumentCount];
int start = frame.arguments.length - currentFrame.arguments.length;
System.arraycopy(currentFrame.arguments, 0, frame.arguments, start, currentFrame.arguments.length);
frameStack.push(currentFrame);
currentFrame = new Frame(frame.self, frame.arguments, frame.variables, callFrameInfo.instructions);
break;
} case Instruction.OPCODE_LOAD_THIS: {
currentFrame.stack.push(currentFrame.self);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_NULL: {
currentFrame.stack.push(new NullProcess());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_LOC: {
int ordinal = (int)instruction.operand1;
Object value = currentFrame.variables[ordinal];
currentFrame.stack.push(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_ARG: {
int ordinal = (int)instruction.operand1;
Object value = currentFrame.arguments[ordinal];
currentFrame.stack.push(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_INT: {
int intValue = (int)instruction.operand1;
IntegerProcess integer = new IntegerProcess(intValue);
integer.defineProto("parent", any.lookup("Integer"));
currentFrame.stack.push(integer);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_FUNC: {
currentFrame.stack.push(instruction.operand1);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_TRUE: {
currentFrame.stack.push(true);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_FALSE: {
currentFrame.stack.push(false);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_STRING: {
String str = (String)instruction.operand1;
StringProcess string = new StringProcess(str);
string.defineProto("parent", any.lookup("String"));
currentFrame.stack.push(string);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_FRAME: {
Frame frame = (Frame)instruction.operand1;
currentFrame.stack.push(frame);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_ARRAY: {
Object[] array = (Object[])instruction.operand1;
currentFrame.stack.push(array);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_ANY: {
Process process = (Process)instruction.operand1;
currentFrame.stack.push(process);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_REIFIED_FRAME: {
if(currentFrame.reification == null) {
currentFrame.reification = new FrameProcess(currentFrame);
currentFrame.reification.defineProto("parent", any.lookup("Frame"));
}
currentFrame.stack.push(currentFrame.reification);
currentFrame.instructionPointer++;
break;
}
// Special opcodes
case Instruction.OPCODE_SP_OR: {
boolean rhs = (boolean)currentFrame.stack.pop();
boolean lhs = (boolean)currentFrame.stack.pop();
currentFrame.stack.push(lhs || rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_AND: {
boolean rhs = (boolean)currentFrame.stack.pop();
boolean lhs = (boolean)currentFrame.stack.pop();
currentFrame.stack.push(lhs && rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_EQUALS: {
Object rhs = (Object)currentFrame.stack.pop();
Object lhs = (Object)currentFrame.stack.pop();
currentFrame.stack.push(lhs.equals(rhs));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_GREATER: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
boolean result = lhs.compareTo(rhs) > 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_GREATER_EQUALS: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
int comparison = lhs.compareTo(rhs);
boolean result = comparison >= 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_LESS: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
boolean result = lhs.compareTo(rhs) < 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_LESS_EQUALS: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
int comparison = lhs.compareTo(rhs);
boolean result = comparison <= 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
}
case Instruction.OPCODE_SP_NOT: {
boolean b = (boolean)currentFrame.stack.pop();
currentFrame.stack.push(!b);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ADD: {
Object rhs = currentFrame.stack.pop();
Object lhs = currentFrame.stack.pop();
if(lhs instanceof Integer && rhs instanceof Integer)
currentFrame.stack.push((int)lhs + (int)rhs);
else if(lhs instanceof String || rhs instanceof String)
currentFrame.stack.push(lhs.toString() + rhs.toString());
else {
Debug.println(Debug.LEVEL_LOW, "Invalid add operation.");
}
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_SUB: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs - rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_MULT: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs * rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_DIV: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs / rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_REM: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs % rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ARRAY_GET: {
IntegerProcess index = (IntegerProcess)currentFrame.stack.pop();
ArrayProcess array = (ArrayProcess)currentFrame.stack.pop();
currentFrame.stack.push(array.get(index.intValue));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ARRAY_SET: {
Object value = currentFrame.stack.pop();
IntegerProcess index = (IntegerProcess)currentFrame.stack.pop();
ArrayProcess array = (ArrayProcess)currentFrame.stack.pop();
array.set(index.intValue, value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_STRING_CONCAT: {
StringProcess rhs = (StringProcess)currentFrame.stack.pop();
StringProcess lhs = (StringProcess)currentFrame.stack.pop();
StringProcess result = new StringProcess(lhs.str + rhs.str);
result.defineProto("parent", any.lookup("String"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_STRING_EQUAL: {
StringProcess rhs = (StringProcess)currentFrame.stack.pop();
StringProcess lhs = (StringProcess)currentFrame.stack.pop();
currentFrame.stack.push(lhs.str.equals(rhs.str));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_ADD: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess result = new IntegerProcess(lhs.intValue + rhs.intValue);
result.defineProto("parent", any.lookup("Integer"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
}case Instruction.OPCODE_SP_INT_SUB: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess result = new IntegerProcess(lhs.intValue - rhs.intValue);
result.defineProto("parent", any.lookup("Integer"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_MULT: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess result = new IntegerProcess(lhs.intValue * rhs.intValue);
result.defineProto("parent", any.lookup("Integer"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_DIV: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess result = new IntegerProcess(lhs.intValue / rhs.intValue);
result.defineProto("parent", any.lookup("Integer"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_REM: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess result = new IntegerProcess(lhs.intValue % rhs.intValue);
result.defineProto("parent", any.lookup("Integer"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_EQUAL: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
currentFrame.stack.push(lhs.intValue == rhs.intValue);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_GREATER: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
currentFrame.stack.push(lhs.intValue > rhs.intValue);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_LESS: {
IntegerProcess rhs = (IntegerProcess)currentFrame.stack.pop();
IntegerProcess lhs = (IntegerProcess)currentFrame.stack.pop();
currentFrame.stack.push(lhs.intValue < rhs.intValue);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_INT_TO_STRING: {
IntegerProcess integer = (IntegerProcess)currentFrame.stack.pop();
StringProcess result = new StringProcess(Integer.toString(integer.intValue));
result.defineProto("parent", any.lookup("String"));
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
}
case Instruction.OPCODE_SP_WRITE: {
StringProcess value = (StringProcess)currentFrame.stack.pop();
System.out.print(value.str);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEXT_LINE: {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
currentFrame.stack.push(line);
// Store the value for the replay instruction
lastReadLine = line;
} catch (IOException e) {
e.printStackTrace();
}
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_DICT: {
DictionaryProcess newDict = new DictionaryProcess();
newDict.defineProto("parent", any);
currentFrame.stack.push(newDict);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_ARRAY: {
IntegerProcess length = (IntegerProcess)currentFrame.stack.pop();
ArrayProcess newArray = new ArrayProcess(length.intValue);
newArray.defineProto("prototype", any.lookup("Array"));
currentFrame.stack.push(newArray);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ARRAY_LENGTH: {
ArrayProcess newArray = (ArrayProcess)currentFrame.stack.pop();
currentFrame.stack.push(newArray.length());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_LOAD: {
StringProcess pathSource = (StringProcess)currentFrame.stack.pop();
String path = pathSource.str;
try {
// What to do here during replay?
// or rather, what to replace this instruction with for replay?
path = "commons/gens/" + path;
Journal<duro.runtime.Process, Instruction> journal = Journal.read(path);
CustomProcess customProcess = (CustomProcess)journal.getRoot();
// Assumed to end with finish instruction. Replace finish with pop_frame.
customProcess.currentFrame.instructions[customProcess.currentFrame.instructions.length - 1] = new Instruction(Instruction.OPCODE_RET_THIS);
this.frameStack.push(currentFrame);
currentFrame = new Frame(any, customProcess.currentFrame.arguments, customProcess.currentFrame.variables.length, customProcess.currentFrame.instructions);
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
break;
} case Instruction.OPCODE_SP_NEW_GENERATOR: {
Object[] arguments = (Object[])currentFrame.stack.pop();
Process self = (Process)currentFrame.stack.pop();
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
Frame generatorFrame = new Frame(self, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
GeneratorProcess generator = new GeneratorProcess(generatorFrame);
DictionaryProcess iteratorPrototype = (DictionaryProcess)any.lookup("Iterator");
generator.defineProto("prototype", iteratorPrototype);
currentFrame.stack.push(generator);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_GENERATABLE: {
int argumentCount = (int)instruction.operand1;
Object[] arguments = new Object[argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
GeneratableProcess generatable = new GeneratableProcess(callFrameInfo, currentFrame.self, arguments);
DictionaryProcess iterablePrototype = (DictionaryProcess)any.lookup("Iterable");
generatable.defineProto("prototype", iterablePrototype);
currentFrame.stack.push(generatable);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_CLOSURE: {
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
currentFrame.stack.push(new ClosureProcess(currentFrame, callFrameInfo));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_CLONE: {
DictionaryProcess dict = (DictionaryProcess)currentFrame.stack.pop();
DictionaryProcess clone = dict.clone();
currentFrame.stack.push(clone);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_BREAK_POINT: {
new String();
currentFrame.instructionPointer++;
break;
}
}
}
private String lastReadLine;
@Override
public void resume(List<Instruction> playedInstructions) {
Debug.println(Debug.LEVEL_HIGH, "play");
if(currentFrame != null) {
while(!stopRequested) {
Instruction instruction = currentFrame.instructions[currentFrame.instructionPointer];
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "play: " + instruction);
next(instruction);
switch(instruction.opcode) {
case Instruction.OPCODE_PAUSE:
playedInstructions.add(new Instruction(Instruction.OPCODE_INC_IP));
break;
case Instruction.OPCODE_SP_WRITE:
// Don't manipulate peripherals on replay
break;
case Instruction.OPCODE_SP_NEXT_LINE:
// The replay instruction simply pushes the read key consistently
playedInstructions.add(new Instruction(Instruction.OPCODE_LOAD_STRING, lastReadLine));
// Don't manipulate peripherals on replay
break;
default:
playedInstructions.add(instruction);
break;
}
}
}
if(currentFrame != null && currentFrame.stack.size() > 0)
Debug.println(Debug.LEVEL_LOW, "stack isn't empty: " + currentFrame.stack);
if(currentFrame != null)
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "/play");
}
@Override
public Object getCallable(Object key) {
return null;
}
@Override
public void define(Object key, Object value) {
}
@Override
public Object lookup(Object key) {
return null;
}
@Override
public Iterator<Object> iterator() {
return null;
}
}
|
package com.rafkind.paintown;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.List;
import com.rafkind.paintown.exception.LoadException;
import com.rafkind.paintown.level.Level;
import com.rafkind.paintown.level.Block;
import com.rafkind.paintown.level.Thing;
import com.rafkind.paintown.level.Character;
import com.rafkind.paintown.level.Item;
import javax.swing.filechooser.FileFilter;
import org.swixml.SwingEngine;
public class Editor extends JFrame {
public Editor(){
this.setSize( 900, 500 );
JMenuBar menuBar = new JMenuBar();
JMenu menuProgram = new JMenu( "Program" );
menuBar.add( menuProgram );
JMenu menuLevel = new JMenu( "Level" );
menuBar.add( menuLevel );
JMenuItem quit = new JMenuItem( "Quit" );
menuProgram.add( quit );
final Lambda0 closeHook = new Lambda0(){
public Object invoke(){
System.exit( 0 );
return null;
}
};
JMenuItem loadLevel = new JMenuItem( "Open Level" );
menuLevel.add( loadLevel );
JMenuItem saveLevel = new JMenuItem( "Save Level" );
menuLevel.add( saveLevel );
menuLevel.setMnemonic( KeyEvent.VK_L );
saveLevel.setMnemonic( KeyEvent.VK_S );
loadLevel.setMnemonic( KeyEvent.VK_O );
/*
levelImage = new BufferedImage( 1000, 300, BufferedImage.TYPE_INT_RGB );
Graphics g = levelImage.getGraphics();
g.setColor( new Color( 64, 192, 54 ) );
g.fillRect( 10, 10, 200, 200 );
*/
quit.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event ){
closeHook.invoke_();
}
});
final SwingEngine engine = new SwingEngine( "main.xml" );
this.getContentPane().add( (JPanel) engine.getRootComponent() );
final Level level = new Level();
final JPanel viewContainer = (JPanel) engine.find( "view" );
final JScrollPane viewScroll = new JScrollPane( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
final JPanel view = new JPanel(){
public Dimension getPreferredSize(){
return level.getSize();
}
protected void paintComponent( Graphics g ){
// System.out.println( "Clear a rect from 0, " + level.getHeight() + " to " + level.getWidth() + ", " + (v.getVisibleAmount() - level.getHeight()) );
JScrollBar h = viewScroll.getHorizontalScrollBar();
JScrollBar v = viewScroll.getVerticalScrollBar();
g.setColor( new Color( 255, 255, 255 ) );
g.clearRect( 0, 0, (int) level.getWidth(), v.getVisibleAmount() );
level.render( (Graphics2D) g, h.getValue(), 0, h.getVisibleAmount(), v.getVisibleAmount() );
// System.out.println( "Visible vertical: " + v.getVisibleAmount() );
}
};
viewScroll.setPreferredSize( new Dimension( 200, 200 ) );
viewScroll.setViewportView( view );
viewScroll.getHorizontalScrollBar().setBackground( new Color( 128, 255, 0 ) );
final Lambda1 editSelected = new Lambda1(){
public Object invoke( Object t ){
Thing thing = (Thing) t;
final JDialog dialog = new JDialog( Editor.this, "Edit" );
dialog.setSize( 300, 300 );
PropertyEditor editor = thing.getEditor();
dialog.add( editor.createPane( level, new Lambda0(){
public Object invoke(){
dialog.setVisible( false );
viewScroll.repaint();
return null;
}
}) );
dialog.setVisible( true );
return null;
}
};
class Mouser extends MouseMotionAdapter implements MouseInputListener {
Thing selected = null;
double dx, dy;
double sx, sy;
Popup currentPopup;
public Thing getSelected(){
return selected;
}
public void setSelected( Thing t ){
selected = t;
}
public void mouseDragged( MouseEvent event ){
if ( selected != null ){
// System.out.println( "sx,sy: " + sx + ", " + sy + " ex,ey: " + (event.getX() / 2) + ", " + (event.getY() / 2) + " dx, dy: " + dx + ", " + dy );
level.moveThing( selected, (int)(sx + event.getX() / level.getScale() - dx), (int)(sy + event.getY() / level.getScale() - dy) );
viewScroll.repaint();
}
}
private boolean leftClick( MouseEvent event ){
return event.getButton() == MouseEvent.BUTTON1;
}
private boolean rightClick( MouseEvent event ){
return event.getButton() == MouseEvent.BUTTON3;
}
private void selectThing( MouseEvent event ){
Thing t = findThingAt( event );
Block has = null;
for ( Iterator it = level.getBlocks().iterator(); it.hasNext(); ){
Block b = (Block) it.next();
b.setHighlight( false );
if ( t != null && b.hasThing( t ) ){
has = b;
}
}
if ( has != null ){
has.setHighlight( true );
viewScroll.repaint();
}
if ( selected == null && t != null ){
// selected = findThingAt( event );
selected = t;
selected.setSelected( true );
sx = selected.getX();
sy = selected.getY() + level.getMinZ();
// System.out.println( "Y: " + selected.getY() + " minZ: " + level.getMinZ() );
dx = event.getX() / level.getScale();
dy = event.getY() / level.getScale();
// System.out.println( "Found: " + selected + " at " + event.getX() + " " + event.getY() );
}
if ( getSelected() != null && event.getClickCount() == 2 ){
editSelected.invoke_( getSelected() );
// System.out.println( "Properties of " + getSelected() );
}
}
private List findFiles( File dir, final String ending ){
File[] all = dir.listFiles( new java.io.FileFilter(){
public boolean accept( File path ){
return path.isDirectory() || path.getName().endsWith( ending );
}
});
List files = new ArrayList();
for ( int i = 0; i < all.length; i++ ){
if ( all[ i ].isDirectory() ){
files.addAll( findFiles( all[ i ], ending ) );
} else {
files.add( all[ i ] );
}
}
return files;
}
private Block findBlock( MouseEvent event ){
int x = (int)(event.getX() / level.getScale());
// System.out.println( event.getX() + " -> " + x );
int total = 0;
for ( Iterator it = level.getBlocks().iterator(); it.hasNext(); ){
Block b = (Block) it.next();
if ( b.isEnabled() ){
if ( x >= total && x <= total + b.getLength() ){
return b;
}
total += b.getLength();
}
}
return null;
}
private Thing makeThing( Token head, int x, int y, String path ) throws LoadException {
if ( head.getName().equals( "character" ) ){
Token temp = new Token();
temp.addToken( new Token( "character" ) );
temp.addToken( new String[]{ "name", "TempName" } );
temp.addToken( new String[]{ "coords", String.valueOf( x ), String.valueOf( y ) } );
temp.addToken( new String[]{ "health", "40" } );
temp.addToken( new String[]{ "path", path } );
return new Character( temp );
} else if ( head.getName().equals( "item" ) ){
Token temp = new Token();
temp.addToken( new Token( "item" ) );
temp.addToken( new String[]{ "coords", String.valueOf( x ), String.valueOf( y ) } );
temp.addToken( new String[]{ "path", path } );
System.out.println( "Make item from " + temp.toString() );
return new Item( temp );
}
throw new LoadException( "Unknown type: " + head.getName() );
}
/* TODO: change this to be more dynamic */
private Vector collectCharFiles(){
Vector v = new Vector();
/*
for ( Iterator it = findFiles( new File( "data/chars" ), ".txt" ).iterator(); it.hasNext(); ){
v.add( it.next() );
}
*/
v.add( new File( "data/chars/angel/angel.txt" ) );
v.add( new File( "data/chars/billy/billy.txt" ) );
v.add( new File( "data/chars/heavy/heavy.txt" ) );
v.add( new File( "data/chars/joe/joe.txt" ) );
v.add( new File( "data/chars/kula/kula.txt" ) );
v.add( new File( "data/chars/mandy/mandy.txt" ) );
v.add( new File( "data/chars/maxima/maxima.txt" ) );
v.add( new File( "data/chars/shermie/shermie.txt" ) );
v.add( new File( "data/chars/yashiro/yashiro.txt" ) );
v.add( new File( "data/misc/apple/apple.txt" ) );
return v;
}
private void showAddObjectPopup( final MouseEvent event ){
// JPanel panel = new JPanel();
final Vector files = collectCharFiles();
Box panel = Box.createVerticalBox();
final JList all = new JList( files );
panel.add( new JScrollPane( all ) );
JButton add = new JButton( "Add" );
JButton close = new JButton( "Close" );
Box buttons = Box.createHorizontalBox();
buttons.add( add );
buttons.add( close );
panel.add( buttons );
if ( currentPopup != null ){
currentPopup.hide();
}
// Point px = viewContainer.getLocationOnScreen();
final Popup p = PopupFactory.getSharedInstance().getPopup( Editor.this, panel, event.getX() - viewScroll.getHorizontalScrollBar().getValue(), event.getY() );
// final Popup p = PopupFactory.getSharedInstance().getPopup( Editor.this, panel, 100, 100 );
close.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
p.hide();
}
});
currentPopup = p;
p.show();
all.addMouseListener( new MouseAdapter() {
public void mouseClicked( MouseEvent clicked ){
if ( clicked.getClickCount() == 2 ){
int index = all.locationToIndex( clicked.getPoint() );
File f = (File) files.get( index );
try{
Block b = findBlock( event );
if ( b != null ){
TokenReader reader = new TokenReader( f );
Token head = reader.nextToken();
int x = (int)(event.getX() / level.getScale());
int y = (int)(event.getY() / level.getScale());
for ( Iterator it = level.getBlocks().iterator(); it.hasNext(); ){
Block b1 = (Block) it.next();
if ( b1 == b ){
break;
}
if ( b1.isEnabled() ){
x -= b1.getLength();
}
}
b.addThing( makeThing( head, x, y, f.getPath() ) );
/*
Character c = new Character( reader.nextToken() );
b.add( new Character( reader.nextToken() ) );
*/
viewScroll.repaint();
}
} catch ( LoadException e ){
System.out.println( "Could not load " + f );
e.printStackTrace();
}
p.hide();
}
}
});
}
public void mousePressed( MouseEvent event ){
if ( leftClick( event ) ){
if ( selected != null ){
selected.setSelected( false );
}
selected = null;
selectThing( event );
} else if ( rightClick( event ) ){
showAddObjectPopup( event );
}
}
public void mouseExited( MouseEvent event ){
if ( selected != null ){
// selected = null;
viewScroll.repaint();
}
}
private Thing findThingAt( MouseEvent event ){
return level.findThing( (int)(event.getX() / level.getScale()), (int)(event.getY() / level.getScale()) );
}
public void mouseClicked( MouseEvent event ){
}
public void mouseEntered( MouseEvent event ){
}
public void mouseReleased( MouseEvent event ){
if ( selected != null ){
// selected = null;
viewScroll.repaint();
}
}
}
final Mouser mousey = new Mouser();
view.addMouseMotionListener( mousey );
view.addMouseListener( mousey );
JTabbedPane tabbed = (JTabbedPane) engine.find( "tabbed" );
final Box holder = Box.createVerticalBox();
final Box blocks = Box.createVerticalBox();
holder.add( new JScrollPane( blocks ) );
holder.add( new JSeparator() );
class ObjectList implements ListModel {
private List listeners;
private List things;
public ObjectList(){
listeners = new ArrayList();
things = new ArrayList();
}
public void setBlock( Block b ){
this.things = b.getThings();
ListDataEvent event = new ListDataEvent( this, ListDataEvent.CONTENTS_CHANGED, 0, 999999 );
for ( Iterator it = listeners.iterator(); it.hasNext(); ){
ListDataListener l = (ListDataListener) it.next();
l.contentsChanged( event );
}
}
public void addListDataListener( ListDataListener l ){
listeners.add( l );
}
public Object getElementAt( int index ){
return this.things.get( index );
}
public int getSize(){
return this.things.size();
}
public void removeListDataListener( ListDataListener l ){
this.listeners.remove( l );
}
}
final ObjectList objectList = new ObjectList();
final JList currentObjects = new JList( objectList );
holder.add( new JLabel( "Objects" ) );
holder.add( new JScrollPane( currentObjects ) );
holder.add( Box.createVerticalGlue() );
currentObjects.addListSelectionListener( new ListSelectionListener(){
public void valueChanged( ListSelectionEvent e ){
Thing t = (Thing) currentObjects.getSelectedValue();
if ( mousey.getSelected() != null ){
Thing old = mousey.getSelected();
old.setSelected( false );
level.findBlock( old ).setHighlight( false );
}
t.setSelected( true );
mousey.setSelected( t );
/* the current X position within the world */
int currentX = 0;
Block b = level.findBlock( t );
b.setHighlight( true );
for ( Iterator it = level.getBlocks().iterator(); it.hasNext(); ){
Block next = (Block) it.next();
if ( next == b ){
break;
}
if ( next.isEnabled() ){
currentX += next.getLength();
}
}
currentX += t.getX() - t.getWidth();
viewScroll.getHorizontalScrollBar().setValue( (int)(currentX * level.getScale()) );
viewScroll.repaint();
}
});
currentObjects.addKeyListener( new KeyAdapter(){
public void keyTyped( KeyEvent e ){
if ( e.getKeyChar() == KeyEvent.VK_DELETE ){
Thing t = (Thing) currentObjects.getSelectedValue();
if ( t != null ){
mousey.setSelected( null );
Block b = level.findBlock( t );
b.removeThing( t );
objectList.setBlock( b );
viewScroll.repaint();
}
}
}
});
currentObjects.addMouseListener( new MouseAdapter() {
public void mouseClicked( MouseEvent clicked ){
if ( clicked.getClickCount() == 2 ){
Thing t = (Thing) currentObjects.getSelectedValue();
editSelected.invoke_( t );
}
}
});
viewScroll.setFocusable( true );
viewScroll.addKeyListener( new KeyAdapter(){
public void keyTyped( KeyEvent e ){
if ( e.getKeyChar() == KeyEvent.VK_DELETE ){
if ( mousey.getSelected() != null ){
level.findBlock( mousey.getSelected() ).removeThing( mousey.getSelected() );
viewScroll.repaint();
}
}
}
});
tabbed.add( "Blocks", holder );
final JList objects = new JList();
tabbed.add( "Objects", objects );
GridBagLayout layout = new GridBagLayout();
viewContainer.setLayout( layout );
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
constraints.weighty = 1;
layout.setConstraints( viewScroll, constraints );
view.setBorder( BorderFactory.createLineBorder( new Color( 255, 0, 0 ) ) );
viewContainer.add( viewScroll );
/*
final JList list = (JList) engine.find( "files" );
final DirectoryModel model = new DirectoryModel( "data" );
list.setModel( model );
*/
saveLevel.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
Token t = level.toToken();
System.out.println( t );
}
});
final Lambda2 setupBlocks = new Lambda2(){
public Object invoke( Object l, Object recur ){
final Lambda2 setupBlocksRecur = (Lambda2) recur;
final Level level = (Level) l;
blocks.removeAll();
int n = 1;
int total = 0;
for ( Iterator it = level.getBlocks().iterator(); it.hasNext(); ){
final Block block = (Block) it.next();
Box stuff = Box.createHorizontalBox();
JCheckBox check = new JCheckBox( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
JCheckBox c = (JCheckBox) event.getSource();
block.setEnabled( c.isSelected() );
view.revalidate();
viewScroll.repaint();
}
});
check.setSelected( true );
stuff.add( check );
JButton button = new JButton( "Block " + n + " : " + block.getLength() );
button.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
objectList.setBlock( block );
}
});
stuff.add( button );
stuff.add( Box.createHorizontalStrut( 3 ) );
JButton erase = new JButton( "Delete" );
erase.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
mousey.setSelected( null );
level.getBlocks().remove( block );
setupBlocksRecur.invoke_( level, setupBlocksRecur );
view.repaint();
}
});
stuff.add( erase );
stuff.add( Box.createHorizontalGlue() );
blocks.add( stuff );
total += block.getLength();
n += 1;
}
Box f = Box.createHorizontalBox();
f.add( new JLabel( "Total length " + total ) );
f.add( Box.createHorizontalGlue() );
blocks.add( f );
blocks.revalidate();
blocks.repaint();
return null;
}
};
loadLevel.addActionListener( new AbstractAction(){
public void actionPerformed( ActionEvent event ){
JFileChooser chooser = new JFileChooser( new File( "." ) );
chooser.setFileFilter( new FileFilter(){
public boolean accept( File f ){
return f.isDirectory() || f.getName().endsWith( ".txt" );
}
public String getDescription(){
return "Level files";
}
});
// chooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int returnVal = chooser.showOpenDialog( Editor.this );
if ( returnVal == JFileChooser.APPROVE_OPTION ){
final File f = chooser.getSelectedFile();
try{
level.load( f );
setupBlocks.invoke_( level, setupBlocks );
view.revalidate();
viewScroll.repaint();
} catch ( LoadException le ){
System.out.println( "Could not load " + f.getName() );
le.printStackTrace();
}
}
}
});
JPanel scroll = (JPanel) engine.find( "scroll" );
final JScrollBar scrolly = new JScrollBar( JScrollBar.HORIZONTAL, 10, 0, 1, 20 );
final JLabel scale = (JLabel) engine.find( "scale" );
scroll.add( scrolly );
scrolly.addAdjustmentListener( new AdjustmentListener(){
public void adjustmentValueChanged( AdjustmentEvent e ){
level.setScale( (double) e.getValue() * 2.0 / scrolly.getMaximum() );
scale.setText( "Scale: " + level.getScale() );
view.revalidate();
viewScroll.repaint();
}
});
this.setJMenuBar( menuBar );
this.addWindowListener( new CloseHook( closeHook ) );
}
public static void main( String[] args ){
final Editor editor = new Editor();
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
editor.setVisible( true );
}
}
);
}
}
|
package com.opengamma.financial.analytics.ircurve;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import java.util.TreeSet;
import javax.time.calendar.Period;
import org.junit.Test;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.position.PortfolioNodeImpl;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.financial.Currency;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.livedata.normalization.MarketDataRequirementNames;
import com.opengamma.math.interpolation.Interpolator1DFactory;
/**
* Test InterpolatedYieldAndDiscountCurveFunction.
*/
public class InterpolatedYieldAndDiscountCurveFunctionTest {
protected static InterpolatedYieldAndDiscountCurveDefinition constructDefinition() {
Currency currency = Currency.getInstance("USD");
String name = "Test Curve";
InterpolatedYieldAndDiscountCurveDefinition definition = new InterpolatedYieldAndDiscountCurveDefinition(currency, name, Interpolator1DFactory.LINEAR);
definition.addStrip(new FixedIncomeStrip(Period.ofYears(1), UniqueIdentifier.of("Test", "USSW1 Curncy"), StripInstrument.SWAP));
definition.addStrip(new FixedIncomeStrip(Period.ofYears(2), UniqueIdentifier.of("Test", "USSW2 Curncy"), StripInstrument.SWAP));
definition.addStrip(new FixedIncomeStrip(Period.ofYears(3), UniqueIdentifier.of("Test", "USSW3 Curncy"), StripInstrument.SWAP));
return definition;
}
@Test
public void discountCurveRequirements() {
InterpolatedYieldAndDiscountCurveDefinition definition = constructDefinition();
DefaultInterpolatedYieldAndDiscountCurveSource curveSource = new DefaultInterpolatedYieldAndDiscountCurveSource();
curveSource.addDefinition(Currency.getInstance("USD"), "DEFAULT", definition);
SimpleInterpolatedYieldAndDiscountCurveFunction function = new SimpleInterpolatedYieldAndDiscountCurveFunction(Currency
.getInstance("USD"), "DEFAULT", false);
function.setUniqueIdentifier("testId");
Set<ValueRequirement> requirements = null;
FunctionCompilationContext context = new FunctionCompilationContext();
context.put("discountCurveSource", curveSource);
function.init(context);
requirements = function.getRequirements(context, new ComputationTarget(ComputationTargetType.PRIMITIVE, Currency.getInstance("USD")));
assertNotNull(requirements);
assertEquals(3, requirements.size());
Set<UniqueIdentifier> foundKeys = new TreeSet<UniqueIdentifier>();
for (ValueRequirement requirement : requirements) {
assertNotNull(requirement);
assertEquals(MarketDataRequirementNames.MARKET_VALUE, requirement.getValueName());
assertNotNull(requirement.getTargetSpecification());
assertEquals(ComputationTargetType.PRIMITIVE, requirement.getTargetSpecification().getType());
foundKeys.add(requirement.getTargetSpecification().getUniqueIdentifier());
}
assertEquals(3, foundKeys.size());
for (FixedIncomeStrip strip : definition.getStrips()) {
assertTrue(foundKeys.contains(strip.getMarketDataKey()));
}
}
@Test
public void yieldCurveRequirements() {
InterpolatedYieldAndDiscountCurveDefinition definition = constructDefinition();
DefaultInterpolatedYieldAndDiscountCurveSource curveSource = new DefaultInterpolatedYieldAndDiscountCurveSource();
curveSource.addDefinition(Currency.getInstance("USD"), "DEFAULT", definition);
SimpleInterpolatedYieldAndDiscountCurveFunction function = new SimpleInterpolatedYieldAndDiscountCurveFunction(Currency
.getInstance("USD"), "DEFAULT", true);
function.setUniqueIdentifier("testId");
Set<ValueRequirement> requirements = null;
FunctionCompilationContext context = new FunctionCompilationContext();
context.put("discountCurveSource", curveSource);
function.init(context);
requirements = function.getRequirements(context, new ComputationTarget(ComputationTargetType.PRIMITIVE, Currency
.getInstance("USD")));
assertNotNull(requirements);
assertEquals(3, requirements.size());
Set<UniqueIdentifier> foundKeys = new TreeSet<UniqueIdentifier>();
for (ValueRequirement requirement : requirements) {
assertNotNull(requirement);
assertEquals(MarketDataRequirementNames.MARKET_VALUE, requirement.getValueName());
assertNotNull(requirement.getTargetSpecification());
assertEquals(ComputationTargetType.PRIMITIVE, requirement.getTargetSpecification().getType());
foundKeys.add(requirement.getTargetSpecification().getUniqueIdentifier());
}
assertEquals(3, foundKeys.size());
for (FixedIncomeStrip strip : definition.getStrips()) {
assertTrue(foundKeys.contains(strip.getMarketDataKey()));
}
}
@Test
public void discountCurveNotMatchingRequirements() {
InterpolatedYieldAndDiscountCurveDefinition definition = constructDefinition();
DefaultInterpolatedYieldAndDiscountCurveSource curveSource = new DefaultInterpolatedYieldAndDiscountCurveSource();
curveSource.addDefinition(Currency.getInstance("USD"), "DEFAULT", definition);
SimpleInterpolatedYieldAndDiscountCurveFunction function = new SimpleInterpolatedYieldAndDiscountCurveFunction(Currency
.getInstance("USD"), "DEFAULT", false);
function.setUniqueIdentifier("testId");
Set<ValueRequirement> requirements = null;
FunctionCompilationContext context = new FunctionCompilationContext();
context.put("discountCurveSource", curveSource);
function.init(context);
requirements = function.getRequirements(context, new ComputationTarget(ComputationTargetType.PRIMITIVE, Currency.getInstance("EUR")));
assertNull(requirements);
requirements = function.getRequirements(context, new ComputationTarget(ComputationTargetType.PORTFOLIO_NODE, new PortfolioNodeImpl()));
assertNull(requirements);
}
@Test
public void yieldCurveNotMatchingRequirements() {
InterpolatedYieldAndDiscountCurveDefinition definition = constructDefinition();
DefaultInterpolatedYieldAndDiscountCurveSource curveSource = new DefaultInterpolatedYieldAndDiscountCurveSource();
curveSource.addDefinition(Currency.getInstance("USD"), "DEFAULT", definition);
SimpleInterpolatedYieldAndDiscountCurveFunction function = new SimpleInterpolatedYieldAndDiscountCurveFunction(Currency
.getInstance("USD"), "DEFAULT", true);
function.setUniqueIdentifier("testId");
Set<ValueRequirement> requirements = null;
FunctionCompilationContext context = new FunctionCompilationContext();
context.put("discountCurveSource", curveSource);
function.init(context);
requirements = function.getRequirements(context, new ComputationTarget(ComputationTargetType.PRIMITIVE, Currency
.getInstance("EUR")));
assertNull(requirements);
requirements = function.getRequirements(context, new ComputationTarget(ComputationTargetType.PORTFOLIO_NODE,
new PortfolioNodeImpl()));
assertNull(requirements);
}
}
|
package Heap;
public class HandMadeHeap {
int[] a;
int size = 0;
public HandMadeHeap(int size) {
a = new int[size + 1];
}
public void insert(int element) {
if (size == a.length - 1) {
System.out.println("Heap overflow!");
return;
}
a[++size] = element;
siftUp(size);
}
public int minElement() {
if (size == 0) {
System.out.println("Heap underflow!");
return -1;
}
int retVal = a[1];
a[1] = a[size
siftDown(size);
return retVal;
}
private void siftDown(int n) {
int parent, child;
for (parent = 1; (child = 2 * parent) <= n; parent = child) {
if (child + 1 <= size && a[child + 1] < a[child]) {
++child;
}
if (a[parent] <= a[child]) {
break;
}
swap(a, parent, child);
}
}
private void siftUp(int n) {
int parent, child;
for (child = n; child > 1 && a[parent = child / 2] > a[child]; child = parent) {
swap(a, parent, child);
}
}
private void swap(int[] a, int idx1, int idx2) {
int tmp = a[idx1];
a[idx1] = a[idx2];
a[idx2] = tmp;
}
}
|
package agreementMaker.userInterface.vertex;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import agreementMaker.GSM;
import agreementMaker.mappingEngine.ContextMapping;
import agreementMaker.mappingEngine.DefnMapping;
import agreementMaker.mappingEngine.UserMapping;
import com.hp.hpl.jena.ontology.OntModel;
/**
* Vertex class contains all the information about the node or vertex of the XML tree.
* Some of the information include tbe name of the vertex, the location on the canvas,
* if the vertex is visible, if it is mapped, and the actual mapping.
*
* @author ADVIS Laboratory
* @version 11/27/2004
*/
public class Vertex extends DefaultMutableTreeNode implements Serializable
{
// instance variables
static int key =0; // unique number assigned by the program
static final long serialVersionUID = 1;
private int arcHeight; // arc height of the rectangular node
private int arcWidth; // arc width of the rectangular node
protected ContextMapping contextMapping; // context mapping
protected DefnMapping defnMapping = null;
private String description; // description of the vertex
private int height; // height of the node/vertex
private int id; // assign the unique number here
private OntModel ontModel;
private String uri;
private boolean isMapped; // is the vertex mapped by the user
private boolean isMappedByContext; // is the vertex mapped by context
private boolean isMappedByDef; // is the vertex mapped by definition
private boolean isSelected; // is the node or vertex selected
private boolean isVisible; // is the node/vertex visible
private String name; // name of the vertex (may not be unique)
private int nodeType; // the type of node (global or local)
//private VertexDescriptionPane vertexDescription; //stores the description of the OWL classes
private int ontNode; //the type of vertex; XML or OWL -> 0 for XML and 1 for OWL
private String parentsDesc=""; // String the stores the parentsDesList
private ArrayList parentsNameList; // stores the names of the parents and grand parents of the vertex
private ArrayList siblingsNameList; // stores the names of siblings of the vertex
private ArrayList parentsDescList; // stores the Discriptions of the parents and grand parents of the vertex
private ArrayList siblingsDescList; // stores the Discriptions of siblings of the vertex
private String parentsName= ""; // String the stores the parentsNameList
private boolean shouldCollapse; // keeps track if the node or vertex should collapse or not.
private String siblingsDesc = "";// String the stores the siblingsDescList
private String siblingsName =""; // String the stores the siblingsNameList
protected UserMapping userMapping; // user mapping class of this vertex
private int width; // width of the node/vertex
private int x; // coordinate x location on canvas
private int x2; // coordinate x2 = x+width location on canvas
private int y; // coordinate y location on canvas
private int y2; // coordinate y2 = y+width location on canvas
/**
* Constructor for objects of class Vertex
* @param name name of the vertex
*/
public Vertex(String name)
{
super(name);
// initialize instance variables
setID(key++);
setName(name);
setDesc("");
this.ontModel = null;
setIsMapped(false);
setIsMappedByContext(false);
setIsMappedByDef(false);
setX(-1);
setX2(-1);
setY(-1);
setY2(-1);
setWidth(-1);
setHeight(-1);
setArcWidth(-1);
setArcHeight(-1);
setIsVisible(true);
isSelected = false;
setNodeType(-1);
setOntNode(GSM.XMLFILE);
setShouldCollapse(false);
userMapping = new UserMapping();
//vertexDescription = (VertexDescriptionPane)jDescriptionPanel;
}
public Vertex(String name, String uri, OntModel m) {
super(name);
// initialize instance variables
setID(key++);
setName(name);
setDesc("");
this.ontModel = m;
this.uri = uri;
setIsMapped(false);
setIsMappedByContext(false);
setIsMappedByDef(false);
setX(-1);
setX2(-1);
setY(-1);
setY2(-1);
setWidth(-1);
setHeight(-1);
setArcWidth(-1);
setArcHeight(-1);
setIsVisible(true);
isSelected = false;
setNodeType(-1);
setOntNode(GSM.ONTFILE);
setShouldCollapse(false);
userMapping = new UserMapping();
//vertexDescription = (VertexDescriptionPane)jDescriptionPanel;
}
/**
* Accessor method which returns arcHeight of the node
*
* @return arcHeight arc height of the vertex
*/
public int getArcHeight()
{
return arcHeight;
}
/**
* Accessor method which returns arcWidth of the node
*
* @return arcWidth arc width of the vertex
*/
public int getArcWidth()
{
return arcWidth;
}
/**
* Accessor method which returns description
*
* @return description description of the vertex
*/
public String getDesc() {
return description;
}
/**
* Accessor method which returns height of the node
*
* @return height height of the vertex
*/
public int getHeight()
{
return height;
}
public String getHorizontalDescs(){
return siblingsDesc;
}
public String getHorizontalNames(){
return siblingsName;
}
/**
* Accessor method which returns key
*
* @return id unique identifier of the vertex
*/
public int getID()
{
return id;
}
/**
* Accessor method which returns true if vertex is mapped else false
*
* @return isMapped boolean value indicating if the vertex is mapped or not
*/
public boolean getIsMapped()
{
return isMapped;
}
/**
* Accessor method which returns true if vertex is mapped by context else false
*
* @return isMapped boolean value indicating if the vertex is mapped by context or not
*/
public boolean getIsMappedByContext()
{
return isMappedByContext;
}
/**
* Accessor method which returns true if vertex is mapped by defintion else false
*
* @return isMapped boolean value indicating if the vertex is mapped by definition or not
*/
public boolean getIsMappedByDef()
{
return isMappedByDef;
}
/**
* Accessor method which returns isSelected
*
* @return isSelected boolean value which indicates if the vertex is selected or not
*/
public boolean getIsSelected()
{
return isSelected;
}
/**
* Accessor method which returns name of the vertex
*
* @return name name of the vertex
*/
public String getName()
{
return name;
}
/**
* Accessor method which returns nodeType
*
* @return nodeType node type indicating if the node is global (1) or local (2)
*/
public int getNodeType()
{
return nodeType;
}
/**
* Accessor method which returns description for OWL Class vertices
*
* @return description description of the vertex
*/
public String getOWLDesc() {
return OntVertexDescription.getVertexDescription(this.name,this.ontModel);
}
/**
* Accessor method which returns OWLNode
*
* @return OWLNode indicating if the node is for XML file or OWL file
*/
public int getOntNode() {
return ontNode;
}
/**
* Accessor method which returns shouldCollapse
*
* @return shouldCollapse boolean value indicating if the vertex should collapse or not
*/
public boolean getShouldCollapse()
{
return shouldCollapse;
}
public String getVerticalDescs(){
return parentsDesc;
}
public String getVerticalNames(){
return parentsName;
}
/**
* Accessor method which returns width of the node
*
* @return width width of the vertex
*/
public int getWidth()
{
return width;
}
/**
* Accessor method which returns x value
*
* @return x x location of the top left corner of vertex
*/
public int getX()
{
return x;
}
/**
* Accessor method which returns x2 value
*
* @return x2 x location of the bottom right corner of vertex
*/
public int getX2()
{
return x2;
}
/**
* Accessor method which returns y value
*
* @return y y location of the top left corner of vertex
*/
public int getY()
{
return y;
}
/**
* Accessor method which returns y2 value
*
* @return y2 y location of the bottom right corner of vertex
*/
public int getY2()
{
return y2;
}
/**
* Accessor method which returns isVisible
*
* @return isVisible boolean value which indicates if the vertex if visible or not
*/
public boolean isVisible()
{
return isVisible;
}
/**
* Modifier method which sets archeight
*
* @param ah height of arc
*/
public void setArcHeight(int ah)
{
arcHeight = ah;
}
/**
* Modifier method which sets arcWidth
*
* @param aw width of the arc
*/
public void setArcWidth(int aw)
{
arcWidth= aw;
}
/**
* Modifier method which sets description of the vertex
*
* @param desc description of the vertex
*/
public void setDesc(String desc)
{
description = desc;
}
public OntModel getOntModel() {
return ontModel;
}
public void setOntModel(OntModel ontModel) {
this.ontModel = ontModel;
}
/**
* Modifier method which sets description of the vertex if it is for OWL class
*
* @param pCls the OWL named class
*/
/*public void setDesc(String name, OWLModel ontModel)
{
vertexDescription = new VertexDescriptionPane(name, ontModel);
} */
/**
* Modifier method which sets height
*
* @param h height of node
*/
public void setHeight(int h)
{
height = h;
}
/**
* Modifier method which sets unique id of vertex
*
* @param num unique identifier
*/
public void setID(int num)
{
id = num;
}
/**
* Modifier method which sets the boolean isMapped to true or false
*
* @param mapped boolean value which indicates if the vertex is mapped
*/
public void setIsMapped(boolean mapped)
{
isMapped = mapped;
}
/**
* Modifier method which sets the boolean isMappedByContext to true or false
*
* @param mapped boolean value which indicates if the vertex is mapped by context
*/
public void setIsMappedByContext(boolean mapped)
{
isMappedByContext = mapped;
}
/**
* Modifier method which sets the boolean isMappedByDef to true or false
*
* @param mapped boolean value which indicates if the vertex is mapped by definition
*/
public void setIsMappedByDef(boolean mapped)
{
isMappedByDef = mapped;
}
/**
* Modifier method which sets isSelected
*
* @param selected boolean value indicating if the vertex is selected
*/
public void setIsSelected(boolean selected)
{
isSelected = selected;
}
/**
* Modifier method which sets isVisible
*
* @param visible boolean value which indicates if the vertex is visible
*/
public void setIsVisible(boolean visible)
{
isVisible = visible;
}
/**
* Modifier method which sets name of vertex
*
* @param tempName name of the vertex
*/
public void setName(String tempName)
{
name = tempName;
}
/**
* Modifier method which sets nodeType
*
* @param type integer value indicating if the vertex is global (1) or local (2)
*/
public void setNodeType(int type)
{
nodeType = type;
}
/**
* Modifier method which set OWLNode
*
* @param type integer value indicating if the vertex is for XML file or OWL file
*/
public void setOntNode(int type)
{
ontNode = type;
}
/**
* Modifier method which sets shouldCollapse
*
* @param collapse boolean value indicating if the vertex should collapse
*/
public void setShouldCollapse(boolean collapse)
{
shouldCollapse = collapse;
}
/**
* Sets the parents and siblings variables
*
* @param num unique identifier
*/
public void setVerticalHorizontal()
{
TreeNode[] pathToRoot = this.getPath();
String[] parents;
String[] descs;
parents = new String[pathToRoot.length];
descs = new String[pathToRoot.length];
for(int i=pathToRoot.length-1; i>1; i--){ // from this node to the root, the node itself name is not added, and also the ontology name and the word "Source/Target ontology" are not considered
parents[i] = ((Vertex) pathToRoot[i]).getName();
descs[i] = ((Vertex) pathToRoot[i]).getDesc();
if(parents[i] != null && !getName().equals(parents[i])){
parentsName += parents[i] + " | ";
parentsDesc += descs[i] + " | ";
//JOptionPane.showMessageDialog(null, "Node name: " + getName() + "\n parentsName: " + parentsName);
}
}
// JOptionPane.showMessageDialog(null,parentsName + " \nDISC: " + parentsDesc);
// WGS
Vertex parent = (Vertex) getParent();
Vertex temp;
if(parent != null){
if(parent.getChildCount() != 0){
for (Enumeration e = parent.children() ; e.hasMoreElements(); ) {
temp = (Vertex)e.nextElement();
if(temp.getName() != getName()){
siblingsName += temp.getName() + " | ";
siblingsDesc += temp.getDesc() + " | ";
}
}
}
}
//JOptionPane.showMessageDialog(null,siblingsName + " \nDISC: " + siblingsDesc);
/*
parentsNameList = new ArrayList();
parentsDescList = new ArrayList();
Vertex temp = this;
do{
if(temp.getParent() == null ) break;
parentsNameList.add( (String) ((Vertex)(temp.getParent())).getName() );
parentsDescList.add( (String) ((Vertex)(temp.getParent())).getDesc() );
temp = (Vertex) temp.getParent();
} while (temp != null);
for(int i=0; i<parentsNameList.size();i++){
parentsName += (String)parentsNameList.get(i) +" ";
parentsDesc += (String)parentsDescList.get(i) +" ";
}
JOptionPane.showMessageDialog(null,parentsName + " \nDISC: " + parentsDesc);
*/
}
/**
* Modifier method which sets width
*
* @param w width of node
*/
public void setWidth(int w)
{
width = w;
}
/**
* Modifier method which sets x value
*
* @param xvalue x location of the top left corner
*/
public void setX(int xvalue)
{
x = xvalue;
}
/**
* Modifier method which sets x2 value
*
* @param x2value x location of the bottom right corner
*/
public void setX2(int x2value)
{
x2 = x2value;
}
/**
* Modifier method which sets y value
*
* @param yvalue y location of the top left corner
*/
public void setY(int yvalue)
{
y = yvalue;
}
/**
* Modifier method which sets y2 value
*
* @param y2value y location of the bottom right corner
*/
public void setY2(int y2value)
{
y2 = y2value;
}
/**
* @return Returns the contextMapping.
*/
public ContextMapping getContextMapping() {
return contextMapping;
}
/**
* @param contextMapping The contextMapping to set.
*/
public void setContextMapping(ContextMapping contextMapping) {
this.contextMapping = contextMapping;
}
/**
* @return Returns the defnMapping.
*/
public DefnMapping getDefnMapping() {
return defnMapping;
}
/**
* @author cosmin
* @date Oct 12, 2008
*/
public void clearDefnMapping() {
// set defnMapping = null, which will remove any references to the
// definition that was there before, and garbage collection will destroy it
// (hopefully (if there's no other references to it in the program))
defnMapping = null;
isMappedByDef = false; // this vertex is no longer mapped by definition
}
/**
* @author cosmin
* @date Oct 17, 2008
*/
public void clearContextMapping() {
contextMapping = null;
isMappedByContext = false;
}
/**
* @param defnMapping The defnMapping to set.
*/
public void setDefnMapping(DefnMapping defnMapping) {
this.defnMapping = defnMapping;
}
/**
* @return Returns the userMapping.
*/
public UserMapping getUserMapping() {
return userMapping;
}
/**
* @param userMapping The userMapping to set.
*/
public void setUserMapping(UserMapping userMapping) {
this.userMapping = userMapping;
}
/**
* @return Returns the uri.
*/
public String getUri() {
return this.uri;
}
}
|
package org.psem2m.sca.converter.core.resolver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.psem2m.sca.converter.core.SCAConstants;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
/**
* An LSResourceResolver that looks into the local JAR file to find schemas, if
* possible
*
* @author Thomas Calmant
*/
public class EmbeddedResourceResolver implements LSResourceResolver {
/** The current class loader */
private ClassLoader pLoader;
/** Known name spaces files */
private final Map<String, String> pNamespaces;
/**
* Default constructor
*/
public EmbeddedResourceResolver() {
pLoader = getClass().getClassLoader();
pNamespaces = new HashMap<String, String>();
pNamespaces.put(SCAConstants.SCA_NS, "sca-1.1-cd06.xsd");
pNamespaces.put(SCAConstants.PSEM2M_NS, "psem2m-sca.xsd");
pNamespaces.put("http://tuscany.apache.org/xmlns/sca/1.1",
"tuscany-sca-1.1.xsd");
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.ls.LSResourceResolver#resolveResource(java.lang.String,
* java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public LSInput resolveResource(final String aType,
final String aNamespaceURI, final String aPublicId,
final String aSystemId, final String aBaseURI) {
final String systemId;
if (aSystemId != null) {
// Given name space
systemId = aSystemId;
} else if (pNamespaces.containsKey(aNamespaceURI)) {
// Known name space
systemId = pNamespaces.get(aNamespaceURI);
} else {
// Unknown name space
System.err.println("Unknown XML NS : " + aNamespaceURI);
return null;
}
// Extract the file name from the URI
final StringBuilder fileName = new StringBuilder();
// Try to get the schema
fileName.append(EmbeddedResourceResolver.class.getPackage().getName()
.replace('.', '/'));
fileName.append("/schemas/");
final int lastSlash = systemId.lastIndexOf('/') + 1;
if (lastSlash == 0) {
fileName.append(systemId);
} else {
fileName.append(systemId.substring(lastSlash));
}
InputStream schemaStream = pLoader.getResourceAsStream(fileName
.toString());
if (schemaStream == null) {
// Not found in JAR
try {
// .. in the working directory
schemaStream = new FileInputStream(fileName.toString());
} catch (final FileNotFoundException e) {
// Not found
}
}
if (schemaStream != null) {
// Schema found
return new StreamInput(aPublicId, aSystemId, aBaseURI, schemaStream);
}
return null;
}
}
|
package plus1s.app.controllers;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import plus1s.app.R;
import plus1s.app.model.AccountType;
import plus1s.app.model.Administrator;
import plus1s.app.model.Item;
import plus1s.app.model.Manager;
import plus1s.app.model.User;
import plus1s.app.model.UserDetails;
public class RegisterActivity extends AppCompatActivity {
// controls the minimum length of password
private final int password_minimum_length = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_activity);
final EditText reg_name = (EditText) findViewById(R.id.reg_name);
final EditText reg_username = (EditText) findViewById(R.id.reg_user);
final EditText reg_email = (EditText) findViewById(R.id.reg_email);
final EditText reg_password = (EditText) findViewById(R.id.reg_password);
final EditText reg_password_confirm = (EditText) findViewById(R.id.reg_pass_confirm);
final Button reg_register = (Button) findViewById(R.id.reg_register);
final Button reg_cancel = (Button) findViewById(R.id.reg_cancel);
final Spinner reg_account_type = (Spinner) findViewById(R.id.reg_account_type);
ArrayAdapter<AccountType> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, User.legalAccountType);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reg_account_type.setAdapter(adapter);
reg_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = reg_name.getText().toString().trim();
String username = reg_username.getText().toString().trim();
String email = reg_email.getText().toString().trim();
String password_1 = reg_password_confirm.getText().toString();
String password_2 = reg_password.getText().toString();
String accountType = reg_account_type.getSelectedItem().toString();
boolean qualified = registerQualified(name, username, email, password_1, password_2);
if (qualified) {
//set up new user
User RegisteredUser;
switch (accountType) {
case "Administrator":
RegisteredUser = new Administrator();
break;
case "Manager":
RegisteredUser = new Manager();
break;
default:
RegisteredUser = new User();
break;
}
RegisteredUser.setUsername(username);
RegisteredUser.setName(name);
RegisteredUser.setEmail(email);
RegisteredUser.setPassword(password_1);
RegisteredUser.setIsLocked(false);
RegisteredUser.setItems(new HashMap<String, Item>());
// upload new user to database
UserDetails.register(RegisteredUser);
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("user").child(username);
dr.setValue(UserDetails.getRegisterUser());
Toast.makeText(RegisterActivity.this, "You have successfully registered", Toast.LENGTH_SHORT);
//come back to login page after register successfully
goToLogin();
} else {
AlertDialog.Builder dialog3 = new AlertDialog.Builder(RegisterActivity.this);
dialog3.setTitle("Password not confirmed");
dialog3.setMessage("Your passwords don't match")
.setNegativeButton("Retry", null)
.create()
.show();
reg_password_confirm.setText("");
}
}
});
reg_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToWelcome();
}
});
}
/**
* check whether the register's information is qualified
* @param name user's name
* @param username user's username
* @param email user's email
* @param password_1 user's first time typing password
* @param password_2 user's second time typing password
* @return whether the register's information is qualified
*/
private boolean registerQualified(String name, String username, String email, String password_1, String password_2) {
if (!name.trim().equals("")) {
if (!username.trim().equals("")) {
if (email.contains("@")) {
if ((password_2.length() >= password_minimum_length)) {
if ((password_2.equals(password_1))) {
return true;
}
}
}
}
}
return false;
}
/**
* go to login page
*/
private void goToLogin() {
RegisterActivity.this.startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
/**
* go to welcome page
*/
private void goToWelcome() {
RegisterActivity.this.startActivity(new Intent(RegisterActivity.this, WelcomeActivity.class));
}
}
|
package co.ian.kstool;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import static io.undertow.Handlers.path;
public class App {
private static boolean isEmpty(String s) {
return (s == null || s.isEmpty());
}
private static int getPort() {
String ENV_PORT = System.getenv("PORT");
String SYS_PORT = System.getProperty("server.port");
System.out.println("ENV_PORT: " + ENV_PORT);
System.out.println("SYS_PORT: " + SYS_PORT);
int port = (!isEmpty(SYS_PORT)) ?
Integer.parseInt(SYS_PORT) :
(!isEmpty(ENV_PORT)) ?
Integer.parseInt(ENV_PORT) :
8080;
return port;
}
private static String getHost() {
String ENV_HOSTNAME = System.getenv("HOSTNAME");
String SYS_HOSTNAME = System.getProperty("server.hostname");
System.out.println("ENV_HOSTNAME: " + ENV_HOSTNAME);
System.out.println("SYS_HOSTNAME: " + SYS_HOSTNAME);
String hostname = (!isEmpty(SYS_HOSTNAME)) ?
SYS_HOSTNAME :
(!isEmpty(ENV_HOSTNAME)) ?
ENV_HOSTNAME :
"0.0.0.0";
return hostname;
}
public static void main(final String[] args) {
int port = getPort();
String hostname = getHost();
System.out.println("Listening on port: " + port);
System.out.println("Listening on hostname: " + hostname);
Undertow server = Undertow.builder()
.addHttpListener(port, hostname)
.setHandler(
path()
.addPrefixPath(
"/",
new HttpHandler() {
public void handleRequest(final HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World");
}
}
)
.addPrefixPath(
"/bob",
new HttpHandler() {
public void handleRequest(final HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello BOB");
}
}
)
)
.build();
server.start();
}
}
|
package ts.eclipse.ide.angular2.internal.cli.wizards;
import org.eclipse.core.resources.IContainer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import ts.eclipse.ide.angular2.cli.NgBlueprint;
import ts.eclipse.ide.angular2.internal.cli.AngularCLIMessages;
import ts.eclipse.ide.angular2.internal.cli.json.AngularCLIJson;
/**
* Wizard page for Angular2 Module.
*
*/
public class NewNgModuleWizardPage extends NgGenerateBlueprintWizardPage {
private static final String PAGE_NAME = "ngModule";
private Button chkRouting;
private Button chkSpec;
protected NewNgModuleWizardPage(IContainer folder) {
super(PAGE_NAME, AngularCLIMessages.NewNgModuleWizardPage_title, null, NgBlueprint.MODULE, folder);
super.setDescription(AngularCLIMessages.NewNgModuleWizardPage_description);
}
@Override
public void createParamsControl(Composite parent) {
super.createParamsControl(parent);
Font font = parent.getFont();
// params group
Composite paramsGroup = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
paramsGroup.setLayout(layout);
paramsGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
paramsGroup.setFont(font);
// Checkbox for routing
chkRouting = new Button(paramsGroup, SWT.CHECK);
chkRouting.addListener(SWT.Selection, this);
chkRouting.setText(AngularCLIMessages.NewNgModuleWizardPage_routing);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
chkRouting.setLayoutData(data);
// Checkbox for spec
chkSpec = new Button(paramsGroup, SWT.CHECK);
chkSpec.addListener(SWT.Selection, this);
chkSpec.setText(AngularCLIMessages.NgGenerateBlueprintWizardPage_generate_spec);
data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
chkSpec.setLayoutData(data);
}
@Override
protected void initializePage() {
super.initializePage();
chkSpec.setSelection(getAngularCLIJson().isSpec(NgBlueprint.MODULE));
}
@Override
protected String[] getGeneratedFilesImpl() {
AngularCLIJson cliJson = getAngularCLIJson();
String name = getBlueprintName();
int cnt = isSpec() ? 2 : 1;
if (isRouting())
cnt ++;
String[] files = new String[cnt];
String folderName = cliJson.getFolderName(name);
int i = 0;
files[i++] = folderName.concat(cliJson.getModuleFileName(name));
if (isSpec())
files[i++] = folderName.concat(cliJson.getModuleSpecFileName(name));
if (isRouting())
files[i++] = folderName.concat(cliJson.getRoutingModuleFileName(name));
return files;
}
public boolean isRouting() {
return chkRouting.getSelection();
}
public boolean isSpec() {
return chkSpec.getSelection();
}
}
|
package com.jme3.input;
/**
* A specific API for interfacing with smartphone touch devices
*/
public interface TouchInput extends Input {
/**
* No filter, get all events
*/
public static final int ALL = 0x00;
/**
* Home key
*/
public static final int KEYCODE_HOME = 0x03;
/**
* Escape key.
*/
public static final int KEYCODE_BACK = 0x04;
/**
* Context Menu key.
*/
public static final int KEYCODE_MENU = 0x52;
/**
* Search key.
*/
public static final int KEYCODE_SEARCH = 0x54;
/**
* Volume up key.
*/
public static final int KEYCODE_VOLUME_UP = 0x18;
/**
* Volume down key.
*/
public static final int KEYCODE_VOLUME_DOWN = 0x19;
/**
* Set if mouse events should be generated
*
* @param simulate if mouse events should be generated
*/
public void setSimulateMouse(boolean simulate);
/**
* Set if keyboard events should be generated
*
* @param simulate if keyboard events should be generated
*/
public void setSimulateKeyboard(boolean simulate);
public void setOmitHistoricEvents(boolean dontSendHistory);
}
|
package uk.ac.bolton.archimate.editor.browser;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.browser.Browser;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPersistableElement;
/**
* Browser Editor Input
*
* @author Phillip Beauvoir
*/
public class BrowserEditorInput implements IBrowserEditorInput {
Browser browser;
private String url;
private String title;
/**
* Whether to save the Browser's current URL or the initial one provided
*/
private boolean fPersistBrowserURL;
/**
* @param url The Url to display
*/
public BrowserEditorInput(String url) {
this(url, null);
}
/**
* @param url The Url to display
* @param title The title to display in the title bar
*/
public BrowserEditorInput(String url, String title) {
this.url = url;
this.title = title;
}
@Override
public void setPersistBrowserURL(boolean value) {
fPersistBrowserURL = value;
}
@Override
public boolean exists() {
return getURL() != null;
}
@Override
public ImageDescriptor getImageDescriptor() {
return null;
}
@Override
public String getURL() {
return url;
}
@Override
public String getName() {
if(title != null) {
return title;
}
return getURL() == null ? "(unknown)" : getURL();
}
@Override
public String getToolTipText() {
return getName();
}
@SuppressWarnings("rawtypes")
public Object getAdapter(Class adapter) {
return null;
}
@Override
public IPersistableElement getPersistable() {
if(getURL() == null) {
return null;
}
// OK, we'll handle it
return this;
}
@Override
public void saveState(IMemento memento) {
String url;
if(fPersistBrowserURL && browser != null && !browser.isDisposed()) {
url = browser.getUrl();
}
else {
url = getURL();
}
if(url != null) {
memento.putString(BrowserEditorInputFactory.TAG_URL, url);
if(fPersistBrowserURL) { // don't save if not set
memento.putBoolean(BrowserEditorInputFactory.TAG_PERSIST_BROWSER_URL, fPersistBrowserURL);
}
}
}
@Override
public String getFactoryId() {
return BrowserEditorInputFactory.ID_FACTORY;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(!(obj instanceof BrowserEditorInput)) {
return false;
}
if(getURL() == null) {
return false;
}
return getURL().equalsIgnoreCase(((BrowserEditorInput)obj).getURL());
}
}
|
package com.jme3.util;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
/**
* <code>BufferUtils</code> is a helper class for generating nio buffers from
* jME data classes such as Vectors and ColorRGBA.
*
* @author Joshua Slack
* @version $Id: BufferUtils.java,v 1.16 2007/10/29 16:56:18 nca Exp $
*/
public final class BufferUtils {
private static final Map<Buffer, Object> trackingHash = Collections.synchronizedMap(new WeakHashMap<Buffer, Object>());
private static final Object ref = new Object();
// Note: a WeakHashMap is really bad here since the hashCode() and
// equals() behavior of buffers will vary based on their contents.
// As it stands, put()'ing an empty buffer will wipe out the last
// empty buffer with the same size. So any tracked memory calculations
// could be lying.
// Besides, the hashmap behavior isn't even being used here and
// yet the expense is still incurred. For example, a newly allocated
// 10,000 byte buffer will iterate through the whole buffer of 0's
// to calculate the hashCode and then potentially do it again to
// calculate the equals()... which by the way is guaranteed for
// every empty buffer of an existing size since they will always produce
// the same hashCode().
// It would be better to just keep a straight list of weak references
// and clean out the dead every time a new buffer is allocated.
// WeakHashMap is doing that anyway... so there is no extra expense
// incurred.
// Recommend a ConcurrentLinkedQueue of WeakReferences since it
// supports the threading semantics required with little extra overhead.
private static final boolean trackDirectMemory = false;
/**
* Creates a clone of the given buffer. The clone's capacity is
* equal to the given buffer's limit.
*
* @param buf The buffer to clone
* @return The cloned buffer
*/
public static Buffer clone(Buffer buf) {
if (buf instanceof FloatBuffer) {
return clone((FloatBuffer) buf);
} else if (buf instanceof ShortBuffer) {
return clone((ShortBuffer) buf);
} else if (buf instanceof ByteBuffer) {
return clone((ByteBuffer) buf);
} else if (buf instanceof IntBuffer) {
return clone((IntBuffer) buf);
} else if (buf instanceof DoubleBuffer) {
return clone((DoubleBuffer) buf);
} else {
throw new UnsupportedOperationException();
}
}
private static void onBufferAllocated(Buffer buffer){
/*
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
int initialIndex = 0;
for (int i = 0; i < stackTrace.length; i++){
if (!stackTrace[i].getClassName().equals(BufferUtils.class.getName())){
initialIndex = i;
break;
}
}
int allocated = buffer.capacity();
int size = 0;
if (buffer instanceof FloatBuffer){
size = 4;
}else if (buffer instanceof ShortBuffer){
size = 2;
}else if (buffer instanceof ByteBuffer){
size = 1;
}else if (buffer instanceof IntBuffer){
size = 4;
}else if (buffer instanceof DoubleBuffer){
size = 8;
}
allocated *= size;
for (int i = initialIndex; i < stackTrace.length; i++){
StackTraceElement element = stackTrace[i];
if (element.getClassName().startsWith("java")){
break;
}
try {
Class clazz = Class.forName(element.getClassName());
if (i == initialIndex){
System.out.println(clazz.getSimpleName()+"."+element.getMethodName()+"():" + element.getLineNumber() + " allocated " + allocated);
}else{
System.out.println(" at " + clazz.getSimpleName()+"."+element.getMethodName()+"()");
}
} catch (ClassNotFoundException ex) {
}
}*/
if (trackDirectMemory){
trackingHash.put(buffer, ref);
}
}
/**
* Generate a new FloatBuffer using the given array of Vector3f objects.
* The FloatBuffer will be 3 * data.length long and contain the vector data
* as data[0].x, data[0].y, data[0].z, data[1].x... etc.
*
* @param data array of Vector3f objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Vector3f... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(3 * data.length);
for (int x = 0; x < data.length; x++) {
if (data[x] != null) {
buff.put(data[x].x).put(data[x].y).put(data[x].z);
} else {
buff.put(0).put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Generate a new FloatBuffer using the given array of Quaternion objects.
* The FloatBuffer will be 4 * data.length long and contain the vector data.
*
* @param data array of Quaternion objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Quaternion... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(4 * data.length);
for (int x = 0; x < data.length; x++) {
if (data[x] != null) {
buff.put(data[x].getX()).put(data[x].getY()).put(data[x].getZ()).put(data[x].getW());
} else {
buff.put(0).put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Generate a new FloatBuffer using the given array of float primitives.
* @param data array of float primitives to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(float... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(data.length);
buff.clear();
buff.put(data);
buff.flip();
return buff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector3f object data.
*
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector3Buffer(int vertices) {
FloatBuffer vBuff = createFloatBuffer(3 * vertices);
return vBuff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector3f object data only if the given buffer if not already
* the right size.
*
* @param buf
* the buffer to first check and rewind
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector3Buffer(FloatBuffer buf, int vertices) {
if (buf != null && buf.limit() == 3 * vertices) {
buf.rewind();
return buf;
}
return createFloatBuffer(3 * vertices);
}
/**
* Sets the data contained in the given color into the FloatBuffer at the
* specified index.
*
* @param color
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of colors not floats
*/
public static void setInBuffer(ColorRGBA color, FloatBuffer buf,
int index) {
buf.position(index * 4);
buf.put(color.r);
buf.put(color.g);
buf.put(color.b);
buf.put(color.a);
}
/**
* Sets the data contained in the given quaternion into the FloatBuffer at the
* specified index.
*
* @param color
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of quaternions not floats
*/
public static void setInBuffer(Quaternion quat, FloatBuffer buf,
int index) {
buf.position(index * 4);
buf.put(quat.getX());
buf.put(quat.getY());
buf.put(quat.getZ());
buf.put(quat.getW());
}
/**
* Sets the data contained in the given Vector3F into the FloatBuffer at the
* specified index.
*
* @param vector
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of vectors not floats
*/
public static void setInBuffer(Vector3f vector, FloatBuffer buf, int index) {
if (buf == null) {
return;
}
if (vector == null) {
buf.put(index * 3, 0);
buf.put((index * 3) + 1, 0);
buf.put((index * 3) + 2, 0);
} else {
buf.put(index * 3, vector.x);
buf.put((index * 3) + 1, vector.y);
buf.put((index * 3) + 2, vector.z);
}
}
/**
* Updates the values of the given vector from the specified buffer at the
* index provided.
*
* @param vector
* the vector to set data on
* @param buf
* the buffer to read from
* @param index
* the position (in terms of vectors, not floats) to read from
* the buf
*/
public static void populateFromBuffer(Vector3f vector, FloatBuffer buf, int index) {
vector.x = buf.get(index * 3);
vector.y = buf.get(index * 3 + 1);
vector.z = buf.get(index * 3 + 2);
}
/**
* Generates a Vector3f array from the given FloatBuffer.
*
* @param buff
* the FloatBuffer to read from
* @return a newly generated array of Vector3f objects
*/
public static Vector3f[] getVector3Array(FloatBuffer buff) {
buff.clear();
Vector3f[] verts = new Vector3f[buff.limit() / 3];
for (int x = 0; x < verts.length; x++) {
Vector3f v = new Vector3f(buff.get(), buff.get(), buff.get());
verts[x] = v;
}
return verts;
}
/**
* Copies a Vector3f from one position in the buffer to another. The index
* values are in terms of vector number (eg, vector number 0 is postions 0-2
* in the FloatBuffer.)
*
* @param buf
* the buffer to copy from/to
* @param fromPos
* the index of the vector to copy
* @param toPos
* the index to copy the vector to
*/
public static void copyInternalVector3(FloatBuffer buf, int fromPos, int toPos) {
copyInternal(buf, fromPos * 3, toPos * 3, 3);
}
/**
* Normalize a Vector3f in-buffer.
*
* @param buf
* the buffer to find the Vector3f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to normalize
*/
public static void normalizeVector3(FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
tempVec3.normalizeLocal();
setInBuffer(tempVec3, buf, index);
vars.release();
}
/**
* Add to a Vector3f in-buffer.
*
* @param toAdd
* the vector to add from
* @param buf
* the buffer to find the Vector3f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to add to
*/
public static void addInBuffer(Vector3f toAdd, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
tempVec3.addLocal(toAdd);
setInBuffer(tempVec3, buf, index);
vars.release();
}
/**
* Multiply and store a Vector3f in-buffer.
*
* @param toMult
* the vector to multiply against
* @param buf
* the buffer to find the Vector3f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to multiply
*/
public static void multInBuffer(Vector3f toMult, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
tempVec3.multLocal(toMult);
setInBuffer(tempVec3, buf, index);
vars.release();
}
/**
* Checks to see if the given Vector3f is equals to the data stored in the
* buffer at the given data index.
*
* @param check
* the vector to check against - null will return false.
* @param buf
* the buffer to compare data with
* @param index
* the position (in terms of vectors, not floats) of the vector
* in the buffer to check against
* @return
*/
public static boolean equals(Vector3f check, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
boolean eq = tempVec3.equals(check);
vars.release();
return eq;
}
// // -- VECTOR2F METHODS -- ////
/**
* Generate a new FloatBuffer using the given array of Vector2f objects.
* The FloatBuffer will be 2 * data.length long and contain the vector data
* as data[0].x, data[0].y, data[1].x... etc.
*
* @param data array of Vector2f objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Vector2f... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(2 * data.length);
for (int x = 0; x < data.length; x++) {
if (data[x] != null) {
buff.put(data[x].x).put(data[x].y);
} else {
buff.put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector2f object data.
*
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector2Buffer(int vertices) {
FloatBuffer vBuff = createFloatBuffer(2 * vertices);
return vBuff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector2f object data only if the given buffer if not already
* the right size.
*
* @param buf
* the buffer to first check and rewind
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector2Buffer(FloatBuffer buf, int vertices) {
if (buf != null && buf.limit() == 2 * vertices) {
buf.rewind();
return buf;
}
return createFloatBuffer(2 * vertices);
}
/**
* Sets the data contained in the given Vector2F into the FloatBuffer at the
* specified index.
*
* @param vector
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of vectors not floats
*/
public static void setInBuffer(Vector2f vector, FloatBuffer buf, int index) {
buf.put(index * 2, vector.x);
buf.put((index * 2) + 1, vector.y);
}
/**
* Updates the values of the given vector from the specified buffer at the
* index provided.
*
* @param vector
* the vector to set data on
* @param buf
* the buffer to read from
* @param index
* the position (in terms of vectors, not floats) to read from
* the buf
*/
public static void populateFromBuffer(Vector2f vector, FloatBuffer buf, int index) {
vector.x = buf.get(index * 2);
vector.y = buf.get(index * 2 + 1);
}
/**
* Generates a Vector2f array from the given FloatBuffer.
*
* @param buff
* the FloatBuffer to read from
* @return a newly generated array of Vector2f objects
*/
public static Vector2f[] getVector2Array(FloatBuffer buff) {
buff.clear();
Vector2f[] verts = new Vector2f[buff.limit() / 2];
for (int x = 0; x < verts.length; x++) {
Vector2f v = new Vector2f(buff.get(), buff.get());
verts[x] = v;
}
return verts;
}
/**
* Copies a Vector2f from one position in the buffer to another. The index
* values are in terms of vector number (eg, vector number 0 is postions 0-1
* in the FloatBuffer.)
*
* @param buf
* the buffer to copy from/to
* @param fromPos
* the index of the vector to copy
* @param toPos
* the index to copy the vector to
*/
public static void copyInternalVector2(FloatBuffer buf, int fromPos, int toPos) {
copyInternal(buf, fromPos * 2, toPos * 2, 2);
}
/**
* Normalize a Vector2f in-buffer.
*
* @param buf
* the buffer to find the Vector2f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to normalize
*/
public static void normalizeVector2(FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
tempVec2.normalizeLocal();
setInBuffer(tempVec2, buf, index);
vars.release();
}
/**
* Add to a Vector2f in-buffer.
*
* @param toAdd
* the vector to add from
* @param buf
* the buffer to find the Vector2f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to add to
*/
public static void addInBuffer(Vector2f toAdd, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
tempVec2.addLocal(toAdd);
setInBuffer(tempVec2, buf, index);
vars.release();
}
/**
* Multiply and store a Vector2f in-buffer.
*
* @param toMult
* the vector to multiply against
* @param buf
* the buffer to find the Vector2f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to multiply
*/
public static void multInBuffer(Vector2f toMult, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
tempVec2.multLocal(toMult);
setInBuffer(tempVec2, buf, index);
vars.release();
}
/**
* Checks to see if the given Vector2f is equals to the data stored in the
* buffer at the given data index.
*
* @param check
* the vector to check against - null will return false.
* @param buf
* the buffer to compare data with
* @param index
* the position (in terms of vectors, not floats) of the vector
* in the buffer to check against
* @return
*/
public static boolean equals(Vector2f check, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
boolean eq = tempVec2.equals(check);
vars.release();
return eq;
}
//// -- INT METHODS -- ////
/**
* Generate a new IntBuffer using the given array of ints. The IntBuffer
* will be data.length long and contain the int data as data[0], data[1]...
* etc.
*
* @param data
* array of ints to place into a new IntBuffer
*/
public static IntBuffer createIntBuffer(int... data) {
if (data == null) {
return null;
}
IntBuffer buff = createIntBuffer(data.length);
buff.clear();
buff.put(data);
buff.flip();
return buff;
}
/**
* Create a new int[] array and populate it with the given IntBuffer's
* contents.
*
* @param buff
* the IntBuffer to read from
* @return a new int array populated from the IntBuffer
*/
public static int[] getIntArray(IntBuffer buff) {
if (buff == null) {
return null;
}
buff.clear();
int[] inds = new int[buff.limit()];
for (int x = 0; x < inds.length; x++) {
inds[x] = buff.get();
}
return inds;
}
/**
* Create a new float[] array and populate it with the given FloatBuffer's
* contents.
*
* @param buff
* the FloatBuffer to read from
* @return a new float array populated from the FloatBuffer
*/
public static float[] getFloatArray(FloatBuffer buff) {
if (buff == null) {
return null;
}
buff.clear();
float[] inds = new float[buff.limit()];
for (int x = 0; x < inds.length; x++) {
inds[x] = buff.get();
}
return inds;
}
//// -- GENERAL DOUBLE ROUTINES -- ////
/**
* Create a new DoubleBuffer of the specified size.
*
* @param size
* required number of double to store.
* @return the new DoubleBuffer
*/
public static DoubleBuffer createDoubleBuffer(int size) {
DoubleBuffer buf = ByteBuffer.allocateDirect(8 * size).order(ByteOrder.nativeOrder()).asDoubleBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new DoubleBuffer of an appropriate size to hold the specified
* number of doubles only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of doubles that need to be held by the newly created
* buffer
* @return the requested new DoubleBuffer
*/
public static DoubleBuffer createDoubleBuffer(DoubleBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createDoubleBuffer(size);
return buf;
}
/**
* Creates a new DoubleBuffer with the same contents as the given
* DoubleBuffer. The new DoubleBuffer is seperate from the old one and
* changes are not reflected across. If you want to reflect changes,
* consider using Buffer.duplicate().
*
* @param buf
* the DoubleBuffer to copy
* @return the copy
*/
public static DoubleBuffer clone(DoubleBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
DoubleBuffer copy;
if (buf.isDirect()) {
copy = createDoubleBuffer(buf.limit());
} else {
copy = DoubleBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL FLOAT ROUTINES -- ////
/**
* Create a new FloatBuffer of the specified size.
*
* @param size
* required number of floats to store.
* @return the new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(int size) {
FloatBuffer buf = ByteBuffer.allocateDirect(4 * size).order(ByteOrder.nativeOrder()).asFloatBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Copies floats from one position in the buffer to another.
*
* @param buf
* the buffer to copy from/to
* @param fromPos
* the starting point to copy from
* @param toPos
* the starting point to copy to
* @param length
* the number of floats to copy
*/
public static void copyInternal(FloatBuffer buf, int fromPos, int toPos, int length) {
float[] data = new float[length];
buf.position(fromPos);
buf.get(data);
buf.position(toPos);
buf.put(data);
}
/**
* Creates a new FloatBuffer with the same contents as the given
* FloatBuffer. The new FloatBuffer is seperate from the old one and changes
* are not reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the FloatBuffer to copy
* @return the copy
*/
public static FloatBuffer clone(FloatBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
FloatBuffer copy;
if (buf.isDirect()) {
copy = createFloatBuffer(buf.limit());
} else {
copy = FloatBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL INT ROUTINES -- ////
/**
* Create a new IntBuffer of the specified size.
*
* @param size
* required number of ints to store.
* @return the new IntBuffer
*/
public static IntBuffer createIntBuffer(int size) {
IntBuffer buf = ByteBuffer.allocateDirect(4 * size).order(ByteOrder.nativeOrder()).asIntBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new IntBuffer of an appropriate size to hold the specified
* number of ints only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of ints that need to be held by the newly created
* buffer
* @return the requested new IntBuffer
*/
public static IntBuffer createIntBuffer(IntBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createIntBuffer(size);
return buf;
}
/**
* Creates a new IntBuffer with the same contents as the given IntBuffer.
* The new IntBuffer is seperate from the old one and changes are not
* reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the IntBuffer to copy
* @return the copy
*/
public static IntBuffer clone(IntBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
IntBuffer copy;
if (buf.isDirect()) {
copy = createIntBuffer(buf.limit());
} else {
copy = IntBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL BYTE ROUTINES -- ////
/**
* Create a new ByteBuffer of the specified size.
*
* @param size
* required number of ints to store.
* @return the new IntBuffer
*/
public static ByteBuffer createByteBuffer(int size) {
ByteBuffer buf = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new ByteBuffer of an appropriate size to hold the specified
* number of ints only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of bytes that need to be held by the newly created
* buffer
* @return the requested new IntBuffer
*/
public static ByteBuffer createByteBuffer(ByteBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createByteBuffer(size);
return buf;
}
public static ByteBuffer createByteBuffer(byte... data) {
ByteBuffer bb = createByteBuffer(data.length);
bb.put(data);
bb.flip();
return bb;
}
public static ByteBuffer createByteBuffer(String data) {
byte[] bytes = data.getBytes();
ByteBuffer bb = createByteBuffer(bytes.length);
bb.put(bytes);
bb.flip();
return bb;
}
/**
* Creates a new ByteBuffer with the same contents as the given ByteBuffer.
* The new ByteBuffer is seperate from the old one and changes are not
* reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the ByteBuffer to copy
* @return the copy
*/
public static ByteBuffer clone(ByteBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
ByteBuffer copy;
if (buf.isDirect()) {
copy = createByteBuffer(buf.limit());
} else {
copy = ByteBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL SHORT ROUTINES -- ////
/**
* Create a new ShortBuffer of the specified size.
*
* @param size
* required number of shorts to store.
* @return the new ShortBuffer
*/
public static ShortBuffer createShortBuffer(int size) {
ShortBuffer buf = ByteBuffer.allocateDirect(2 * size).order(ByteOrder.nativeOrder()).asShortBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new ShortBuffer of an appropriate size to hold the specified
* number of shorts only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of shorts that need to be held by the newly created
* buffer
* @return the requested new ShortBuffer
*/
public static ShortBuffer createShortBuffer(ShortBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createShortBuffer(size);
return buf;
}
public static ShortBuffer createShortBuffer(short... data) {
if (data == null) {
return null;
}
ShortBuffer buff = createShortBuffer(data.length);
buff.clear();
buff.put(data);
buff.flip();
return buff;
}
/**
* Creates a new ShortBuffer with the same contents as the given ShortBuffer.
* The new ShortBuffer is seperate from the old one and changes are not
* reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the ShortBuffer to copy
* @return the copy
*/
public static ShortBuffer clone(ShortBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
ShortBuffer copy;
if (buf.isDirect()) {
copy = createShortBuffer(buf.limit());
} else {
copy = ShortBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
/**
* Ensures there is at least the <code>required</code> number of entries left after the current position of the
* buffer. If the buffer is too small a larger one is created and the old one copied to the new buffer.
* @param buffer buffer that should be checked/copied (may be null)
* @param required minimum number of elements that should be remaining in the returned buffer
* @return a buffer large enough to receive at least the <code>required</code> number of entries, same position as
* the input buffer, not null
*/
public static FloatBuffer ensureLargeEnough(FloatBuffer buffer, int required) {
if (buffer == null || (buffer.remaining() < required)) {
int position = (buffer != null ? buffer.position() : 0);
FloatBuffer newVerts = createFloatBuffer(position + required);
if (buffer != null) {
buffer.rewind();
newVerts.put(buffer);
newVerts.position(position);
}
buffer = newVerts;
}
return buffer;
}
public static ShortBuffer ensureLargeEnough(ShortBuffer buffer, int required) {
if (buffer == null || (buffer.remaining() < required)) {
int position = (buffer != null ? buffer.position() : 0);
ShortBuffer newVerts = createShortBuffer(position + required);
if (buffer != null) {
buffer.rewind();
newVerts.put(buffer);
newVerts.position(position);
}
buffer = newVerts;
}
return buffer;
}
public static ByteBuffer ensureLargeEnough(ByteBuffer buffer, int required) {
if (buffer == null || (buffer.remaining() < required)) {
int position = (buffer != null ? buffer.position() : 0);
ByteBuffer newVerts = createByteBuffer(position + required);
if (buffer != null) {
buffer.rewind();
newVerts.put(buffer);
newVerts.position(position);
}
buffer = newVerts;
}
return buffer;
}
public static void printCurrentDirectMemory(StringBuilder store) {
long totalHeld = 0;
// make a new set to hold the keys to prevent concurrency issues.
ArrayList<Buffer> bufs = new ArrayList<Buffer>(trackingHash.keySet());
int fBufs = 0, bBufs = 0, iBufs = 0, sBufs = 0, dBufs = 0;
int fBufsM = 0, bBufsM = 0, iBufsM = 0, sBufsM = 0, dBufsM = 0;
for (Buffer b : bufs) {
if (b instanceof ByteBuffer) {
totalHeld += b.capacity();
bBufsM += b.capacity();
bBufs++;
} else if (b instanceof FloatBuffer) {
totalHeld += b.capacity() * 4;
fBufsM += b.capacity() * 4;
fBufs++;
} else if (b instanceof IntBuffer) {
totalHeld += b.capacity() * 4;
iBufsM += b.capacity() * 4;
iBufs++;
} else if (b instanceof ShortBuffer) {
totalHeld += b.capacity() * 2;
sBufsM += b.capacity() * 2;
sBufs++;
} else if (b instanceof DoubleBuffer) {
totalHeld += b.capacity() * 8;
dBufsM += b.capacity() * 8;
dBufs++;
}
}
long heapMem = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
boolean printStout = store == null;
if (store == null) {
store = new StringBuilder();
}
store.append("Existing buffers: ").append(bufs.size()).append("\n");
store.append("(b: ").append(bBufs).append(" f: ").append(fBufs).append(" i: ").append(iBufs).append(" s: ").append(sBufs).append(" d: ").append(dBufs).append(")").append("\n");
store.append("Total heap memory held: ").append(heapMem / 1024).append("kb\n");
store.append("Total direct memory held: ").append(totalHeld / 1024).append("kb\n");
store.append("(b: ").append(bBufsM / 1024).append("kb f: ").append(fBufsM / 1024).append("kb i: ").append(iBufsM / 1024).append("kb s: ").append(sBufsM / 1024).append("kb d: ").append(dBufsM / 1024).append("kb)").append("\n");
if (printStout) {
System.out.println(store.toString());
}
}
}
|
package com.hubspot.blazar.data.dao;
import com.google.common.base.Optional;
import com.hubspot.blazar.base.Build;
import com.hubspot.blazar.base.Module;
import com.hubspot.blazar.base.ModuleBuild;
import com.hubspot.rosetta.jdbi.BindWithRosetta;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.SingleValueResult;
import java.util.List;
public interface BuildDao {
@SingleValueResult
@SqlQuery("" +
"SELECT gitInfo.*, module.*, build.* " +
"FROM builds AS build " +
"INNER JOIN modules AS module ON (build.moduleId = module.id) " +
"INNER JOIN branches AS gitInfo ON (module.branchId = gitInfo.id) " +
"WHERE build.id = :it")
Optional<ModuleBuild> get(@Bind long id);
@SqlQuery("SELECT * FROM builds WHERE moduleId = :id ORDER BY buildNumber DESC")
List<Build> getAllByModule(@BindWithRosetta Module module);
@SingleValueResult
@SqlQuery("SELECT * FROM builds WHERE moduleId = :id AND buildNumber = :buildNumber ORDER BY buildNumber DESC")
Optional<Build> getByModuleAndNumber(@BindWithRosetta Module module, @Bind("buildNumber") int buildNumber);
@GetGeneratedKeys
@SqlUpdate("INSERT INTO builds (moduleId, buildNumber, state) VALUES (:moduleId, :buildNumber, :state)")
long enqueue(@BindWithRosetta Build build);
@SqlUpdate("UPDATE builds SET startTimestamp = :startTimestamp, sha = :sha, state = :state, commitInfo = :commitInfo, buildConfig = :buildConfig, resolvedConfig = :resolvedConfig WHERE id = :id AND state = 'QUEUED'")
int begin(@BindWithRosetta Build build);
@SqlUpdate("UPDATE builds SET log = :log, taskId = :taskId, state = :state WHERE id = :id AND state IN ('LAUNCHING', 'IN_PROGRESS')")
int update(@BindWithRosetta Build build);
@SqlUpdate("UPDATE builds SET endTimestamp = :endTimestamp, log = :log, taskId = :taskId state = :state WHERE id = :id AND state IN ('QUEUED', 'LAUNCHING', 'IN_PROGRESS')")
int complete(@BindWithRosetta Build build);
}
|
package net.jueb.util4j.net.nettyImpl.handler.listenerHandler;
import java.io.IOException;
import java.util.Objects;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import net.jueb.util4j.net.JConnection;
import net.jueb.util4j.net.JConnectionListener;
import net.jueb.util4j.net.nettyImpl.NetLogFactory;
import net.jueb.util4j.net.nettyImpl.NettyConnection;
/**
* chanelJConnectionListener
* @author Administrator
* @param <M>
*/
abstract class AbstractListenerHandler<M,L extends JConnectionListener<M>> extends ChannelInboundHandlerAdapter{
protected final InternalLogger log = NetLogFactory.getLogger(getClass());
protected final L listener;
public AbstractListenerHandler(L listener) {
Objects.requireNonNull(listener);
this.listener=listener;
}
@Override
public final void channelRegistered(ChannelHandlerContext ctx)throws Exception {
//TODO ThreadDeathWatcher,,
ByteBuf initBuf=null;
initBuf=ctx.alloc().buffer(1);
// initBuf=PooledByteBufAllocator.DEFAULT.buffer(1);
ReferenceCountUtil.release(initBuf);
super.channelRegistered(ctx);
}
@Override
public final void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
}
/**
* handler
*/
@Override
public final void channelActive(ChannelHandlerContext ctx) throws Exception {
JConnection connection=buildConnection(ctx);
listener.connectionOpened(connection);
super.channelActive(ctx);
}
/**
* msg
*/
@Override
public final void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception
{
if (msg == null)
{
return;
}
boolean release = false;
try {
@SuppressWarnings("unchecked")
M imsg = (M) msg;
Channel channel=ctx.channel();
JConnection connection = findConnection(channel);
if (connection != null) {
listener.messageArrived(connection, imsg);
release = true;
} else {
log.error(ctx.channel() + ":not found NettyConnection Created.");
ctx.fireChannelRead(msg);// handler
release = false;
}
} catch (Exception e) {
log.error(e.getMessage(),e);
if(!release)
{
ctx.fireChannelRead(msg);// handler
}
} finally {
if (release) {
ReferenceCountUtil.release(msg);
}
}
}
@Override
public final void channelInactive(ChannelHandlerContext ctx)throws Exception
{
Channel channel=ctx.channel();
JConnection connection = findConnection(channel);
if (connection != null)
{
listener.connectionClosed(connection);
} else
{
log.error(ctx.channel() + ":not found NettyConnection Created.");
}
super.channelInactive(ctx);
}
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
if(cause instanceof IOException)
{
return;
}
log.error(ctx.channel() + ":"+cause.toString());
ctx.fireExceptionCaught(cause);
}
/**
*
* @return
*/
protected JConnection buildConnection(ChannelHandlerContext ctx){
JConnection connection=new NettyConnection(ctx);
return connection;
}
/**
*
* @param channel
* @return
*/
protected JConnection findConnection(Channel channel)
{
return NettyConnection.findConnection(channel);
}
}
|
package htmlflow;
import org.xmlet.htmlapifaster.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.function.Supplier;
import static java.util.stream.Collectors.joining;
public abstract class HtmlView<T> implements HtmlWriter<T>, Element<HtmlView, Element> {
static final String WRONG_USE_OF_PRINTSTREAM_ON_THREADSAFE_VIEWS =
"Cannot use PrintStream output for thread-safe views!";
static final String WRONG_USE_OF_THREADSAFE_ON_VIEWS_WITH_PRINTSTREAM =
"Cannot set thread-safety for views with PrintStream output!";
static final String WRONG_USE_OF_RENDER_WITH_PRINTSTREAM =
"Wrong use of render(). " +
"Use write() rather than render() to output to PrintStream. " +
"To get a String from render() you must use view() without a PrintStream ";
private static final String HEADER;
private static final String NEWLINE = System.getProperty("line.separator");
private static final String HEADER_TEMPLATE = "templates/HtmlView-Header.txt";
static {
try {
URL headerUrl = HtmlView.class
.getClassLoader()
.getResource(HEADER_TEMPLATE);
if(headerUrl == null)
throw new FileNotFoundException(HEADER_TEMPLATE);
InputStream headerStream = headerUrl.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(headerStream))) {
HEADER = reader.lines().collect(joining(NEWLINE));
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private HtmlVisitorCache visitor;
private ThreadLocal<HtmlVisitorCache> threadLocalVisitor;
private Supplier<HtmlVisitorCache> visitorSupplier;
private boolean threadSafe = false;
public Html<HtmlView> html() {
if (this.getVisitor().isWriting())
this.getVisitor().write(HEADER);
return new Html<>(this);
}
public Div<HtmlView> div() {
return new Div<>(this);
}
public Tr<HtmlView> tr() {
return new Tr<>(this);
}
public Root<HtmlView> defineRoot(){
return new Root<>(this);
}
@Override
public HtmlWriter<T> setPrintStream(PrintStream out) {
if(threadSafe)
throw new IllegalArgumentException(WRONG_USE_OF_PRINTSTREAM_ON_THREADSAFE_VIEWS);
Supplier<HtmlVisitorCache> v = out == null
? () -> new HtmlVisitorStringBuilder(getVisitor().isDynamic)
: () -> new HtmlVisitorPrintStream(out, getVisitor().isDynamic);
setVisitor(v);
return this;
}
@Override
public HtmlView<T> self() {
return this;
}
public HtmlView<T> threadSafe(){
/**
* I don't like this kind of verification.
* Yet, we need to keep backward compatibility with views based
* on PrintStream output, which are not viable in a multi-thread scenario.
*/
if(getVisitor() instanceof HtmlVisitorPrintStream) {
throw new IllegalStateException(WRONG_USE_OF_THREADSAFE_ON_VIEWS_WITH_PRINTSTREAM);
}
this.threadSafe = true;
setVisitor(visitorSupplier);
return this;
}
@Override
public HtmlVisitorCache getVisitor() {
return threadSafe
? threadLocalVisitor.get()
: visitor;
}
public void setVisitor(Supplier<HtmlVisitorCache> visitor) {
visitorSupplier = visitor;
if(threadSafe) {
this.visitor = null;
this.threadLocalVisitor = ThreadLocal.withInitial(visitor);
} else {
this.visitor = visitor.get();
this.threadLocalVisitor = null;
}
}
@Override
public String getName() {
return "HtmlView";
}
@Override
public Element __() {
throw new IllegalStateException("HtmlView is the root of Html tree and it has not any parent.");
}
@Override
public Element getParent() {
throw new IllegalStateException("HtmlView is the root of Html tree and it has not any parent.");
}
/**
* Adds a partial view to this view.
*
* @param partial inner view.
* @param model the domain object bound to the partial view.
* @param <U> the type of the domain model of the partial view.
*/
public final <U> void addPartial(HtmlView<U> partial, U model) {
getVisitor().closeBeginTag();
partial.getVisitor().depth = getVisitor().depth;
if (this.getVisitor().isWriting())
getVisitor().write(partial.render(model));
}
/**
* Adds a partial view to this view.
*
* @param partial inner view.
* @param <U> the type of the domain model of the partial view.
*/
public final <U> void addPartial(HtmlView<U> partial) {
getVisitor().closeBeginTag();
partial.getVisitor().depth = getVisitor().depth;
if (this.getVisitor().isWriting())
getVisitor().write(partial.render());
}
}
|
package eu.livotov.labs.android.camview;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.FrameLayout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class CAMView extends FrameLayout implements SurfaceHolder.Callback, Camera.PreviewCallback, Camera.ErrorCallback
{
private SurfaceHolder surfaceHolder;
private SurfaceView surface;
private Camera camera;
private int previewFormat = ImageFormat.NV21;
private int cameraId = -1;
private Camera.PreviewCallback previewCallback;
private AutoFocusManager autoFocusManager;
private CAMViewListener camViewListener;
private AtomicBoolean cameraIsLive = new AtomicBoolean(false);
private AtomicBoolean cameraIsStopping = new AtomicBoolean(false);
private AtomicBoolean cameraIsStarting = new AtomicBoolean(false);
private int lastUsedCameraId = -1;
private Camera.ErrorCallback errorCallback;
public CAMView(final Context context)
{
super(context);
initUI();
}
public CAMView(final Context context, final AttributeSet attrs)
{
super(context, attrs);
initUI();
}
public CAMView(final Context context, final AttributeSet attrs, final int defStyle)
{
super(context, attrs, defStyle);
}
private void initUI()
{
}
public void setCamViewListener(final CAMViewListener camViewListener)
{
this.camViewListener = camViewListener;
}
public void switchFlash(boolean on)
{
if (cameraIsLive.get() && camera != null)
{
final Camera camera = getCamera();
final Camera.Parameters parameters = camera.getParameters();
if (parameters != null && parameters.getSupportedFlashModes() != null && parameters.getFlashMode() != null && parameters.getSupportedFlashModes().size() > 0)
{
if (on)
{
if (!parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH))
{
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}
}
else
{
if (!parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF))
{
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
}
camera.setParameters(parameters);
}
}
else
{
throw new IllegalAccessError("switchFlash may only be used in a live mode. Please turn on camera with the start() method before using flash.");
}
}
@TargetApi(9)
public static int getNumberOfCameras()
{
return Camera.getNumberOfCameras();
}
@TargetApi(9)
public static Collection<CameraEnumeration> enumarateCameras()
{
if (Build.VERSION.SDK_INT < 9)
{
throw new UnsupportedOperationException("Camera enumeration is only available for Android SDK version 9 and above.");
}
List<CameraEnumeration> cameras = new ArrayList<CameraEnumeration>();
final int camerasCount = Camera.getNumberOfCameras();
for (int id = 0; id < camerasCount; id++)
{
final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(id, cameraInfo);
cameras.add(new CameraEnumeration(id, cameraInfo));
}
return cameras;
}
public static CameraEnumeration findFrontCamera()
{
Collection<CameraEnumeration> cams = enumarateCameras();
for (CameraEnumeration cam : cams)
{
if (cam.isFrontCamera())
{
return cam;
}
}
return null;
}
public synchronized void stop()
{
if (cameraIsStarting.get())
{
throw new RuntimeException("Cannot stop the camera while it is being started. Wait till start process completes, then stop it.");
}
if (!cameraIsStopping.compareAndSet(false, true))
{
return;
}
if (cameraIsLive.get())
{
switchFlash(false);
}
final Handler uiHandler = new Handler();
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (camera != null)
{
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
if (surfaceHolder != null)
{
surfaceHolder.removeCallback(CAMView.this);
}
} catch (Throwable err)
{
Log.e(CAMView.class.getSimpleName(),err.getMessage(),err);
} finally
{
cameraIsLive.set(false);
cameraIsStopping.set(false);
cameraIsStarting.set(false);
if (camViewListener!=null)
{
uiHandler.post(new Runnable()
{
@Override
public void run()
{
camViewListener.onCameraStopped();
}
});
}
}
}
}).start();
}
public synchronized void start()
{
start(findDefaultCameraId());
}
public synchronized void start(final int cameraId)
{
if (cameraIsLive.get())
{
if (cameraId!=lastUsedCameraId)
{
throw new RuntimeException("You cannot start a new camera while another camera is still running. Please stop your current camera first.");
}
}
if (cameraIsStopping.get())
{
throw new RuntimeException("Camera is stopping at the moment. Please wait until stop process is complete, then start it back.");
}
if (!cameraIsStarting.compareAndSet(false, true))
{
return;
}
this.cameraId = cameraId;
setupCamera(cameraId, new CameraOpenedCallback()
{
@Override
public void onCameraOpened(Camera camera)
{
attachToCamera(camera);
cameraIsStarting.set(false);
cameraIsStopping.set(false);
}
@Override
public void onCameraOpenError(Throwable error)
{
cameraIsLive.set(false);
cameraIsStarting.set(false);
cameraIsStopping.set(false);
if (camViewListener!=null)
{
camViewListener.onCameraOpenError(error);
}
}
});
}
private void attachToCamera(Camera cam)
{
previewCallback = this;
errorCallback = this;
this.camera = cam;
try
{
Camera.Parameters parameters = getMainCameraParameters();
parameters.setPreviewFormat(previewFormat);
camera.setParameters(parameters);
}
catch (Throwable err)
{
Log.e(getClass().getSimpleName(), "Master parameters set was rejected by a camera, trying failsafe one.", err);
try
{
Camera.Parameters parameters = getFailsafeCameraParameters();
parameters.setPreviewFormat(previewFormat);
camera.setParameters(parameters);
}
catch (Throwable err2)
{
Log.e(getClass().getSimpleName(), "Failsafe parameters set was rejected by a camera, trying to use it as is.", err2);
}
}
removeAllViews();
surface = new SurfaceView(getContext());
addView(surface);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) surface.getLayoutParams();
params.gravity = Gravity.CENTER;
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
surface.setLayoutParams(params);
surfaceHolder = surface.getHolder();
surfaceHolder.addCallback(this);
if (Build.VERSION.SDK_INT < 11)
{
try
{
// deprecated setting, but required on Android versions prior to 3.0
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch (Throwable err)
{
Log.e(getClass().getSimpleName(), "Failed to set surface holder to SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS, using it as is.", err);
}
}
lastUsedCameraId = cameraId;
}
public void surfaceCreated(SurfaceHolder holder)
{
try
{
camera.setPreviewDisplay(holder);
}
catch (Throwable e)
{
Log.d("DBG", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
if (surfaceHolder.getSurface() == null)
{
return;
}
stopPreview();
try
{
Camera.Parameters p = camera.getParameters();
int result = 90;
int outputResult = 90;
if (Build.VERSION.SDK_INT > 8)
{
int[] results = calculateResults(result, outputResult);
result = results[0];
outputResult = results[1];
}
if (Build.VERSION.SDK_INT > 7)
{
try
{
camera.setDisplayOrientation(result);
}
catch (Throwable err)
{
// very bad devices goes here
}
}
p.setRotation(outputResult);
camera.setPreviewDisplay(surfaceHolder);
camera.setPreviewCallback(previewCallback);
camera.setErrorCallback(errorCallback);
Camera.Size closestSize = findClosestPreviewSize(p.getSupportedPreviewSizes());
if (closestSize != null)
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) surface.getLayoutParams();
params.gravity = Gravity.CENTER;
params.width = (getWidth() > getHeight() ? closestSize.width : closestSize.height);
params.height = (getWidth() > getHeight() ? closestSize.height : closestSize.width);
surface.setLayoutParams(params);
if (params.width < getWidth() || params.height < getHeight())
{
final int extraPixels = Math.max(getWidth() - params.width, getHeight() - params.height);
params.width += extraPixels;
params.height += extraPixels;
}
p.setPreviewSize(closestSize.width, closestSize.height);
}
camera.setParameters(p);
startPreview();
}
catch (Exception e)
{
Log.d("DBG", "Error starting camera preview: " + e.getMessage());
}
}
public void stopPreview()
{
if (null != camera)
{
if (autoFocusManager != null)
{
autoFocusManager.stop();
autoFocusManager = null;
}
try
{
camera.stopPreview();
}
catch (Exception ignored)
{
}
}
}
private void startPreview()
{
if (null != camera)
{
camera.startPreview();
autoFocusManager = new AutoFocusManager(getContext(), camera);
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private int[] calculateResults(int _result, int _outputResult)
{
int result = _result;
int outputResult = _outputResult;
try
{
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation)
{
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
result = (info.orientation + degrees) % 360;
outputResult = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
}
else
{ // back-facing
result = (info.orientation - degrees + 360) % 360;
}
}
catch (Throwable err)
{
// very bad devices goes here
}
return new int[]{result, outputResult};
}
private Camera.Size findClosestPreviewSize(List<Camera.Size> sizes)
{
int best = -1;
int bestScore = Integer.MAX_VALUE;
for (int i = 0; i < sizes.size(); i++)
{
Camera.Size s = sizes.get(i);
int dx = s.width - surface.getWidth();
int dy = s.height - surface.getHeight();
int score = dx * dx + dy * dy;
if (score < bestScore)
{
best = i;
bestScore = score;
}
}
return best >= 0 ? sizes.get(best) : null;
}
protected void onConfigurationChanged(final Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (cameraIsLive.get() && !cameraIsStopping.get() && !cameraIsStarting.get())
{
restartCameraOnConfigurationChanged();
}
}
private void restartCameraOnConfigurationChanged()
{
if (cameraIsLive.get())
{
switchFlash(false);
}
final Handler uiHandler = new Handler();
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (camera != null)
{
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
if (surfaceHolder != null)
{
surfaceHolder.removeCallback(CAMView.this);
}
} catch (Throwable err)
{
// ignored
} finally
{
cameraIsLive.set(false);
cameraIsStopping.set(false);
cameraIsStarting.set(false);
uiHandler.post(new Runnable()
{
@Override
public void run()
{
if (camViewListener!=null)
{
camViewListener.onCameraStopped();
}
try
{
if (lastUsedCameraId >= 0)
{
start(lastUsedCameraId);
}
else
{
start();
}
}
catch (Throwable err)
{
Log.e(getClass().getSimpleName(), "Failed to re-open the camera after configuration change: " + err.getMessage(), err);
}
}
});
}
}
}).start();
}
public void onPreviewFrame(byte[] data, Camera camera)
{
if (cameraIsLive.compareAndSet(false,true))
{
if (camViewListener != null)
{
camViewListener.onCameraReady(camera);
}
}
if (!cameraIsStopping.get() && camViewListener != null)
{
try
{
camViewListener.onPreviewData(data, previewFormat, camera.getParameters().getPreviewSize());
}
catch (Throwable ignored)
{
}
}
}
//private static final long AUTO_FOCUS_INTERVAL_MS = 1000L;
//private static final long AUTO_FOCUS_INTERVAL_MS = 2000L;
protected int findDefaultCameraId()
{
if (Build.VERSION.SDK_INT < 9)
{
return 0;
}
else
{
return findCamera();
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private int findCamera()
{
final int camerasCount = Camera.getNumberOfCameras();
final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int id = 0; id < camerasCount; id++)
{
Camera.getCameraInfo(id, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
{
return id;
}
}
if (camerasCount > 0)
{
return 0;
}
//throw new RuntimeException("Did not find back camera on this device");
throw new RuntimeException("Did not find camera on this device");
}
protected void setupCamera(final int cameraId, final CameraOpenedCallback callback)
{
final Handler uiHandler = new Handler();
new Thread(new Runnable()
{
@Override
public void run()
{
Camera cam = null;
int retriesCount = 5;
Throwable lastError = null;
while (cam==null && retriesCount>0)
{
try
{
cam = Build.VERSION.SDK_INT < 9 ? Camera.open() : openCamera(cameraId);
}
catch (final Throwable e)
{
lastError = e;
retriesCount
try
{
Thread.sleep(1000);
}
catch (InterruptedException itre)
{
}
}
}
if (cam!=null)
{
camera = cam;
uiHandler.post(new Runnable()
{
@Override
public void run()
{
callback.onCameraOpened(camera);
}
});
} else
{
final Throwable lastOpenError = lastError;
uiHandler.post(new Runnable()
{
@Override
public void run()
{
callback.onCameraOpenError(lastOpenError);
}
});
}
}
}).start();
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private Camera openCamera(final int cameraId)
{
return Camera.open(cameraId);
}
private String findSettableValue(Collection<String> supportedValues, String... desiredValues)
{
//Log.i(TAG, "Supported values: " + supportedValues);
String result = null;
if (supportedValues != null)
{
for (String desiredValue : desiredValues)
{
if (supportedValues.contains(desiredValue))
{
result = desiredValue;
break;
}
}
}
return result;
}
private Camera.Parameters getMainCameraParameters()
{
Camera.Parameters parameters = camera.getParameters();
if (Build.VERSION.SDK_INT >= 9)
{
setFocusMode(parameters);
}
if (Build.VERSION.SDK_INT > 13)
{
setAutoExposureLock(parameters);
}
if (Build.VERSION.SDK_INT > 7)
{
try
{
if (parameters.getMaxExposureCompensation() != 0 || parameters.getMinExposureCompensation() != 0)
{
parameters.setExposureCompensation(0);
}
}
catch (Throwable ignored)
{
}
}
return parameters;
}
@TargetApi(14)
private String getFocusMode14(List<String> focusModes)
{
boolean safeMode = false;
if (safeMode
// || prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, true)
)
{
return findSettableValue(focusModes, Camera.Parameters.FOCUS_MODE_AUTO);
}
else
{
return findSettableValue(focusModes, Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE, Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, Camera.Parameters.FOCUS_MODE_AUTO);
}
}
@TargetApi(9)
private String getFocusMode9(List<String> focusModes)
{
return findSettableValue(focusModes, Camera.Parameters.FOCUS_MODE_AUTO);
}
@TargetApi(9)
private void setFocusMode(Camera.Parameters parameters)
{
String focusMode;
List<String> focusModes = parameters.getSupportedFocusModes();
if (Build.VERSION.SDK_INT >= 14)
{
focusMode = getFocusMode14(focusModes);
}
else
{
focusMode = getFocusMode9(focusModes);
}
if (null == focusMode)
{
focusMode = findSettableValue(focusModes, Camera.Parameters.FOCUS_MODE_MACRO, Camera.Parameters.FOCUS_MODE_EDOF);
}
if (null != focusMode)
{
parameters.setFocusMode(focusMode);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setAutoExposureLock(Camera.Parameters parameters)
{
try
{
if (parameters.isAutoExposureLockSupported())
{
parameters.setAutoExposureLock(false);
}
}
catch (Throwable ignored)
{
}
}
private Camera.Parameters getFailsafeCameraParameters()
{
Camera.Parameters parameters = camera.getParameters();
if (Build.VERSION.SDK_INT >= 9)
{
setFocusMode(parameters);
}
return parameters;
}
public boolean isStreaming()
{
return camera != null;
}
public Camera getCamera()
{
return camera;
}
@Override
public void onError(int i, Camera camera)
{
if (camViewListener != null)
{
camViewListener.onCameraError(i, camera);
}
}
protected interface CameraOpenedCallback
{
void onCameraOpened(Camera camera);
void onCameraOpenError(Throwable error);
}
protected interface CameraClosedCallback
{
void onCameraClosed();
}
public interface CAMViewListener
{
void onCameraReady(Camera camera);
void onCameraStopped();
void onCameraError(int i, Camera camera);
void onCameraOpenError(Throwable err);
void onPreviewData(byte[] data, int previewFormat, Camera.Size size);
}
}
|
package org.testng;
import org.testng.collections.Lists;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Assertion tool class. Presents assertion methods with a more natural parameter order.
* The order is always <B>actualValue</B>, <B>expectedValue</B> [, message].
*
* @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
*/
public class Assert {
/**
* Protect constructor since it is a static only class
*/
protected Assert() {
// hide constructor
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertTrue(boolean condition, String message) {
if(!condition) {
failNotEquals( Boolean.valueOf(condition), Boolean.TRUE, message);
}
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertTrue(boolean condition) {
assertTrue(condition, null);
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertFalse(boolean condition, String message) {
if(condition) {
failNotEquals( Boolean.valueOf(condition), Boolean.FALSE, message); // TESTNG-81
}
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertFalse(boolean condition) {
assertFalse(condition, null);
}
/**
* Fails a test with the given message and wrapping the original exception.
*
* @param message the assertion error message
* @param realCause the original exception
*/
static public void fail(String message, Throwable realCause) {
AssertionError ae = new AssertionError(message);
ae.initCause(realCause);
throw ae;
}
/**
* Fails a test with the given message.
* @param message the assertion error message
*/
static public void fail(String message) {
throw new AssertionError(message);
}
/**
* Fails a test with no message.
*/
static public void fail() {
fail(null);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object actual, Object expected, String message) {
if((expected == null) && (actual == null)) {
return;
}
if(expected != null) {
if (expected.getClass().isArray()) {
assertArrayEquals(actual, expected, message);
return;
} else if (expected.equals(actual)) {
return;
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. It they are not, an AssertionError,
* with given message, is thrown.
* @param actual the actual value
* @param expected the expected value (should be an non-null array value)
* @param message the assertion error message
*/
private static void assertArrayEquals(Object actual, Object expected, String message) {
//is called only when expected is an array
if (actual.getClass().isArray()) {
int expectedLength = Array.getLength(expected);
if (expectedLength == Array.getLength(actual)) {
for (int i = 0 ; i < expectedLength ; i++) {
Object _actual = Array.get(actual, i);
Object _expected = Array.get(expected, i);
try {
assertEquals(_actual, _expected);
} catch (AssertionError ae) {
failNotEquals(actual, expected, message == null ? "" : message
+ " (values as index " + i + " are not the same)");
}
}
//array values matched
return;
} else {
failNotEquals(Array.getLength(actual), expectedLength, message == null ? "" : message
+ " (Array lengths are not the same)");
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object actual, Object expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(String actual, String expected, String message) {
assertEquals((Object) actual, (Object) expected, message);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(String actual, String expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerate value value between the actual and expected value
* @param message the assertion error message
*/
static public void assertEquals(double actual, double expected, double delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Double.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(new Double(actual), new Double(expected), message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) { // Because comparison with NaN always returns false
failNotEquals(new Double(actual), new Double(expected), message);
}
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected value is infinity then the
* delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerate value value between the actual and expected value
*/
static public void assertEquals(double actual, double expected, double delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerate value value between the actual and expected value
* @param message the assertion error message
*/
static public void assertEquals(float actual, float expected, float delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Float.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(new Float(actual), new Float(expected), message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) {
failNotEquals(new Float(actual), new Float(expected), message);
}
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerate value value between the actual and expected value
*/
static public void assertEquals(float actual, float expected, float delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(long actual, long expected, String message) {
assertEquals(Long.valueOf(actual), Long.valueOf(expected), message);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(long actual, long expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(boolean actual, boolean expected, String message) {
assertEquals( Boolean.valueOf(actual), Boolean.valueOf(expected), message);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(boolean actual, boolean expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(byte actual, byte expected, String message) {
assertEquals(Byte.valueOf(actual), Byte.valueOf(expected), message);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(byte actual, byte expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(char actual, char expected, String message) {
assertEquals(Character.valueOf(actual), Character.valueOf(expected), message);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(char actual, char expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(short actual, short expected, String message) {
assertEquals(Short.valueOf(actual), Short.valueOf(expected), message);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(short actual, short expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(int actual, int expected, String message) {
assertEquals(Integer.valueOf(actual), Integer.valueOf(expected), message);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(int actual, int expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionError is thrown.
* @param object the assertion object
*/
static public void assertNotNull(Object object) {
assertNotNull(object, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNotNull(Object object, String message) {
assertTrue(object != null, message);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionError, with the given message, is thrown.
* @param object the assertion object
*/
static public void assertNull(Object object) {
assertNull(object, null);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNull(Object object, String message) {
assertTrue(object == null, message);
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertSame(Object actual, Object expected, String message) {
if(expected == actual) {
return;
}
failNotSame(actual, expected, message);
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertSame(Object actual, Object expected) {
assertSame(actual, expected, null);
}
/**
* Asserts that two objects do not refer to the same objects. If they do,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertNotSame(Object actual, Object expected, String message) {
if(expected == actual) {
failSame(actual, expected, message);
}
}
/**
* Asserts that two objects do not refer to the same object. If they do,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertNotSame(Object actual, Object expected) {
assertNotSame(actual, expected, null);
}
static private void failSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + "expected not same with:<" + expected +"> but was same:<" + actual + ">");
}
static private void failNotSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + "expected same with:<" + expected + "> but was:<" + actual + ">");
}
static private void failNotEquals(Object actual , Object expected, String message ) {
fail(format(actual, expected, message));
}
static String format(Object actual, Object expected, String message) {
String formatted = "";
if (null != message) {
formatted = message + " ";
}
return formatted + "expected:<" + expected + "> but was:<" + actual + ">";
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Collection actual, Collection expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Collection actual, Collection expected, String message) {
if(actual == expected) {
return;
}
if (actual == null || expected == null) {
if (message != null) {
fail(message);
} else {
fail("Collections not equal: expected: " + expected + " and actual: " + actual);
}
}
assertEquals(actual.size(), expected.size(), message + ": lists don't have the same size");
Iterator actIt = actual.iterator();
Iterator expIt = expected.iterator();
int i = -1;
while(actIt.hasNext() && expIt.hasNext()) {
i++;
Object e = expIt.next();
Object a = actIt.next();
String explanation = "Lists differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEquals(a, e, errorMessage);
}
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
if (message != null) {
fail(message);
} else {
fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual));
}
}
assertEquals(Arrays.asList(actual), Arrays.asList(expected), message);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
failAssertNoEqual(actual, expected,
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
if (actual.length != expected.length) {
failAssertNoEqual(actual, expected,
"Arrays do not have the same size:" + actual.length + " != " + expected.length,
message);
}
List actualCollection = Lists.newArrayList();
for (Object a : actual) {
actualCollection.add(a);
}
for (Object o : expected) {
actualCollection.remove(o);
}
if (actualCollection.size() != 0) {
failAssertNoEqual(actual, expected,
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
}
private static void failAssertNoEqual(Object[] actual, Object[] expected,
String message, String defaultMessage)
{
if (message != null) {
fail(message);
} else {
fail(defaultMessage);
}
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object[] actual, Object[] expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected) {
assertEqualsNoOrder(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(final byte[] actual, final byte[] expected) {
assertEquals(actual, expected, "");
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
*
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(final byte[] actual, final byte[] expected, final String message) {
if(expected == actual) {
return;
}
if(null == expected) {
fail("expected a null array, but not null found. " + message);
}
if(null == actual) {
fail("expected not null array, but null found. " + message);
}
assertEquals(actual.length, expected.length, "arrays don't have the same size. " + message);
for(int i= 0; i < expected.length; i++) {
if(expected[i] != actual[i]) {
fail("arrays differ firstly at element [" + i +"]; "
+ "expected value is <" + expected[i] +"> but was <"
+ actual[i] + ">. "
+ message);
}
}
}
/**
* Asserts that two sets are equal.
*/
static public void assertEquals(Set actual, Set expected) {
if(actual == expected) {
return;
}
if (actual == null || expected == null) {
fail("Sets not equal: expected: " + expected + " and actual: " + actual);
}
if (!actual.equals(expected)) {
fail("Sets differ: expected " + expected + " but got " + actual);
}
}
/**
* Asserts that two maps are equal.
*/
static public void assertEquals(Map actual, Map expected) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
fail("Maps not equal: expected: " + expected + " and actual: " + actual);
}
Set entrySet = actual.entrySet();
for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
Object expectedValue = expected.get(key);
assertEquals(value, expectedValue, "Maps do not match for key:" + key + " actual:" + value
+ " expected:" + expectedValue);
}
}
}
|
package org.testng;
import static org.testng.internal.EclipseInterface.ASSERT_LEFT;
import static org.testng.internal.EclipseInterface.ASSERT_LEFT2;
import static org.testng.internal.EclipseInterface.ASSERT_MIDDLE;
import static org.testng.internal.EclipseInterface.ASSERT_RIGHT;
import org.testng.collections.Lists;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Assertion tool class. Presents assertion methods with a more natural parameter order.
* The order is always <B>actualValue</B>, <B>expectedValue</B> [, message].
*
* @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
*/
public class Assert {
/**
* Protect constructor since it is a static only class
*/
protected Assert() {
// hide constructor
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertTrue(boolean condition, String message) {
if(!condition) {
failNotEquals(condition, Boolean.TRUE, message);
}
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertTrue(boolean condition) {
assertTrue(condition, null);
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertFalse(boolean condition, String message) {
if(condition) {
failNotEquals(condition, Boolean.FALSE, message); // TESTNG-81
}
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertFalse(boolean condition) {
assertFalse(condition, null);
}
/**
* Fails a test with the given message and wrapping the original exception.
*
* @param message the assertion error message
* @param realCause the original exception
*/
static public void fail(String message, Throwable realCause) {
AssertionError ae = new AssertionError(message);
ae.initCause(realCause);
throw ae;
}
/**
* Fails a test with the given message.
* @param message the assertion error message
*/
static public void fail(String message) {
throw new AssertionError(message);
}
/**
* Fails a test with no message.
*/
static public void fail() {
fail(null);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object actual, Object expected, String message) {
if (expected != null && expected.getClass().isArray()) {
assertArrayEquals(actual, expected, message);
return;
}
assertEqualsImpl(actual, expected, message);
}
/**
* Differs from {@link #assertEquals(Object, Object, String)} by not taking arrays into
* special consideration hence comparing them by reference. Intended to be called directly
* to test equality of collections content.
*/
private static void assertEqualsImpl(Object actual, Object expected,
String message) {
if((expected == null) && (actual == null)) {
return;
}
if(expected == null ^ actual == null) {
failNotEquals(actual, expected, message);
}
if (expected.equals(actual) && actual.equals(expected)) {
return;
}
failNotEquals(actual, expected, message);
}
private static void assertArrayEquals(Object actual, Object expected, String message) {
if (expected == actual) {
return;
}
if (null == expected) {
fail("expected a null array, but not null found. " + message);
}
if (null == actual) {
fail("expected not null array, but null found. " + message);
}
//is called only when expected is an array
if (actual.getClass().isArray()) {
int expectedLength = Array.getLength(expected);
if (expectedLength == Array.getLength(actual)) {
for (int i = 0 ; i < expectedLength ; i++) {
Object _actual = Array.get(actual, i);
Object _expected = Array.get(expected, i);
try {
assertEquals(_actual, _expected);
} catch (AssertionError ae) {
failNotEquals(actual, expected, message == null ? "" : message
+ " (values at index " + i + " are not the same)");
}
}
//array values matched
return;
} else {
failNotEquals(Array.getLength(actual), expectedLength, message == null ? "" : message
+ " (Array lengths are not the same)");
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object actual, Object expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(String actual, String expected, String message) {
assertEquals((Object) actual, (Object) expected, message);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(String actual, String expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
* @param message the assertion error message
*/
static public void assertEquals(double actual, double expected, double delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Double.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(actual, expected, message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) { // Because comparison with NaN always returns false
failNotEquals(actual, expected, message);
}
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected value is infinity then the
* delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
*/
static public void assertEquals(double actual, double expected, double delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
* @param message the assertion error message
*/
static public void assertEquals(float actual, float expected, float delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Float.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(actual, expected, message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) {
failNotEquals(actual, expected, message);
}
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
*/
static public void assertEquals(float actual, float expected, float delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(long actual, long expected, String message) {
assertEquals(Long.valueOf(actual), Long.valueOf(expected), message);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(long actual, long expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(boolean actual, boolean expected, String message) {
assertEquals( Boolean.valueOf(actual), Boolean.valueOf(expected), message);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(boolean actual, boolean expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(byte actual, byte expected, String message) {
assertEquals(Byte.valueOf(actual), Byte.valueOf(expected), message);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(byte actual, byte expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(char actual, char expected, String message) {
assertEquals(Character.valueOf(actual), Character.valueOf(expected), message);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(char actual, char expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(short actual, short expected, String message) {
assertEquals(Short.valueOf(actual), Short.valueOf(expected), message);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(short actual, short expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(int actual, int expected, String message) {
assertEquals(Integer.valueOf(actual), Integer.valueOf(expected), message);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(int actual, int expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionError is thrown.
* @param object the assertion object
*/
static public void assertNotNull(Object object) {
assertNotNull(object, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNotNull(Object object, String message) {
if (object == null) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + "expected object to not be null");
}
assertTrue(object != null, message);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionError, with the given message, is thrown.
* @param object the assertion object
*/
static public void assertNull(Object object) {
assertNull(object, null);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNull(Object object, String message) {
if (object != null) {
failNotSame(object, null, message);
}
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertSame(Object actual, Object expected, String message) {
if(expected == actual) {
return;
}
failNotSame(actual, expected, message);
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertSame(Object actual, Object expected) {
assertSame(actual, expected, null);
}
/**
* Asserts that two objects do not refer to the same objects. If they do,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertNotSame(Object actual, Object expected, String message) {
if(expected == actual) {
failSame(actual, expected, message);
}
}
/**
* Asserts that two objects do not refer to the same object. If they do,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertNotSame(Object actual, Object expected) {
assertNotSame(actual, expected, null);
}
static private void failSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + ASSERT_LEFT2 + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT);
}
static private void failNotSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + ASSERT_LEFT + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT);
}
static private void failNotEquals(Object actual , Object expected, String message ) {
fail(format(actual, expected, message));
}
static String format(Object actual, Object expected, String message) {
String formatted = "";
if (null != message) {
formatted = message + " ";
}
return formatted + ASSERT_LEFT + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT;
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Collection<?> actual, Collection<?> expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Collection<?> actual, Collection<?> expected, String message) {
if(actual == expected) {
return;
}
if (actual == null || expected == null) {
if (message != null) {
fail(message);
} else {
fail("Collections not equal: expected: " + expected + " and actual: " + actual);
}
}
assertEquals(actual.size(), expected.size(), (message == null ? "" : message + ": ") + "lists don't have the same size");
Iterator<?> actIt = actual.iterator();
Iterator<?> expIt = expected.iterator();
int i = -1;
while(actIt.hasNext() && expIt.hasNext()) {
i++;
Object e = expIt.next();
Object a = actIt.next();
String explanation = "Lists differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEqualsImpl(a, e, errorMessage);
}
}
/** Asserts that two iterators return the same elements in the same order. If they do not,
* an AssertionError is thrown.
* Please note that this assert iterates over the elements and modifies the state of the iterators.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Iterator<?> actual, Iterator<?> expected) {
assertEquals(actual, expected, null);
}
/** Asserts that two iterators return the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* Please note that this assert iterates over the elements and modifies the state of the iterators.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Iterator<?> actual, Iterator<?> expected, String message) {
if(actual == expected) {
return;
}
if(actual == null || expected == null) {
if(message != null) {
fail(message);
} else {
fail("Iterators not equal: expected: " + expected + " and actual: " + actual);
}
}
int i = -1;
while(actual.hasNext() && expected.hasNext()) {
i++;
Object e = expected.next();
Object a = actual.next();
String explanation = "Iterators differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEqualsImpl(a, e, errorMessage);
}
if(actual.hasNext()) {
String explanation = "Actual iterator returned more elements than the expected iterator.";
String errorMessage = message == null ? explanation : message + ": " + explanation;
fail(errorMessage);
} else if(expected.hasNext()) {
String explanation = "Expected iterator returned more elements than the actual iterator.";
String errorMessage = message == null ? explanation : message + ": " + explanation;
fail(errorMessage);
}
}
/** Asserts that two iterables return iterators with the same elements in the same order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Iterable<?> actual, Iterable<?> expected) {
assertEquals(actual, expected, null);
}
/** Asserts that two iterables return iterators with the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Iterable<?> actual, Iterable<?> expected, String message) {
if(actual == expected) {
return;
}
if(actual == null || expected == null) {
if(message != null) {
fail(message);
} else {
fail("Iterables not equal: expected: " + expected + " and actual: " + actual);
}
}
Iterator<?> actIt = actual.iterator();
Iterator<?> expIt = expected.iterator();
assertEquals(actIt, expIt, message);
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
if (message != null) {
fail(message);
} else {
fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual));
}
}
assertEquals(Arrays.asList(actual), Arrays.asList(expected), message);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
failAssertNoEqual(
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
if (actual.length != expected.length) {
failAssertNoEqual(
"Arrays do not have the same size:" + actual.length + " != " + expected.length,
message);
}
List<Object> actualCollection = Lists.newArrayList();
for (Object a : actual) {
actualCollection.add(a);
}
for (Object o : expected) {
actualCollection.remove(o);
}
if (actualCollection.size() != 0) {
failAssertNoEqual(
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
}
private static void failAssertNoEqual(String defaultMessage, String message) {
if (message != null) {
fail(message);
} else {
fail(defaultMessage);
}
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object[] actual, Object[] expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected) {
assertEqualsNoOrder(actual, expected, null);
}
/**
* Asserts that two sets are equal.
*/
static public void assertEquals(Set<?> actual, Set<?> expected) {
assertEquals(actual, expected, null);
}
/**
* Assert set equals
*/
static public void assertEquals(Set<?> actual, Set<?> expected, String message) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
// Keep the back compatible
if (message == null) {
fail("Sets not equal: expected: " + expected + " and actual: " + actual);
} else {
failNotEquals(actual, expected, message);
}
}
if (!actual.equals(expected)) {
if (message == null) {
fail("Sets differ: expected " + expected + " but got " + actual);
} else {
failNotEquals(actual, expected, message);
}
}
}
/**
* Asserts that two maps are equal.
*/
static public void assertEquals(Map<?, ?> actual, Map<?, ?> expected) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
fail("Maps not equal: expected: " + expected + " and actual: " + actual);
}
if (actual.size() != expected.size()) {
fail("Maps do not have the same size:" + actual.size() + " != " + expected.size());
}
Set<?> entrySet = actual.entrySet();
for (Object anEntrySet : entrySet) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) anEntrySet;
Object key = entry.getKey();
Object value = entry.getValue();
Object expectedValue = expected.get(key);
assertEqualsImpl(value, expectedValue, "Maps do not match for key:" + key + " actual:" + value
+ " expected:" + expectedValue);
}
}
// assertNotEquals
public static void assertNotEquals(Object actual1, Object actual2, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
public static void assertNotEquals(Object actual1, Object actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(String actual1, String actual2, String message) {
assertNotEquals((Object) actual1, (Object) actual2, message);
}
static void assertNotEquals(String actual1, String actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(long actual1, long actual2, String message) {
assertNotEquals(Long.valueOf(actual1), Long.valueOf(actual2), message);
}
static void assertNotEquals(long actual1, long actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(boolean actual1, boolean actual2, String message) {
assertNotEquals(Boolean.valueOf(actual1), Boolean.valueOf(actual2), message);
}
static void assertNotEquals(boolean actual1, boolean actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(byte actual1, byte actual2, String message) {
assertNotEquals(Byte.valueOf(actual1), Byte.valueOf(actual2), message);
}
static void assertNotEquals(byte actual1, byte actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(char actual1, char actual2, String message) {
assertNotEquals(Character.valueOf(actual1), Character.valueOf(actual2), message);
}
static void assertNotEquals(char actual1, char actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(short actual1, short actual2, String message) {
assertNotEquals(Short.valueOf(actual1), Short.valueOf(actual2), message);
}
static void assertNotEquals(short actual1, short actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(int actual1, int actual2, String message) {
assertNotEquals(Integer.valueOf(actual1), Integer.valueOf(actual2), message);
}
static void assertNotEquals(int actual1, int actual2) {
assertNotEquals(actual1, actual2, null);
}
static public void assertNotEquals(float actual1, float actual2, float delta, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2, delta, message);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
static public void assertNotEquals(float actual1, float actual2, float delta) {
assertNotEquals(actual1, actual2, delta, null);
}
static public void assertNotEquals(double actual1, double actual2, double delta, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2, delta, message);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
static public void assertNotEquals(double actual1, double actual2, double delta) {
assertNotEquals(actual1, actual2, delta, null);
}
/**
* This interface facilitates the use of {@link #expectThrows} from Java 8. It allows
* method references to both void and non-void methods to be passed directly into
* expectThrows without wrapping, even if they declare checked exceptions.
* <p/>
* This interface is not meant to be implemented directly.
*/
public interface ThrowingRunnable {
void run() throws Throwable;
}
/**
* Asserts that {@code runnable} throws an exception when invoked. If it does not, an
* {@link AssertionError} is thrown.
*
* @param runnable A function that is expected to throw an exception when invoked
* @since 6.9.5
*/
public static void assertThrows(ThrowingRunnable runnable) {
assertThrows(Throwable.class, runnable);
}
/**
* Asserts that {@code runnable} throws an exception of type {@code throwableClass} when
* executed. If it does not throw an exception, an {@link AssertionError} is thrown. If it
* throws the wrong type of exception, an {@code AssertionError} is thrown describing the
* mismatch; the exception that was actually thrown can be obtained by calling {@link
* AssertionError#getCause}.
*
* @param throwableClass the expected type of the exception
* @param runnable A function that is expected to throw an exception when invoked
* @since 6.9.5
*/
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public static <T extends Throwable> void assertThrows(Class<T> throwableClass, ThrowingRunnable runnable) {
expectThrows(throwableClass, runnable);
}
/**
* Asserts that {@code runnable} throws an exception of type {@code throwableClass} when
* executed and returns the exception. If {@code runnable} does not throw an exception, an
* {@link AssertionError} is thrown. If it throws the wrong type of exception, an {@code
* AssertionError} is thrown describing the mismatch; the exception that was actually thrown can
* be obtained by calling {@link AssertionError#getCause}.
*
* @param throwableClass the expected type of the exception
* @param runnable A function that is expected to throw an exception when invoked
* @return The exception thrown by {@code runnable}
* @since 6.9.5
*/
public static <T extends Throwable> T expectThrows(Class<T> throwableClass, ThrowingRunnable runnable) {
try {
runnable.run();
} catch (Throwable t) {
if (throwableClass.isInstance(t)) {
return throwableClass.cast(t);
} else {
String mismatchMessage = String.format("Expected %s to be thrown, but %s was thrown",
throwableClass.getSimpleName(), t.getClass().getSimpleName());
throw new AssertionError(mismatchMessage, t);
}
}
String message = String.format("Expected %s to be thrown, but nothing was thrown",
throwableClass.getSimpleName());
throw new AssertionError(message);
}
}
|
package org.zeropage;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PathFinder pFinder;
/* Implement the detailed interaction, and instantiate pFinder
* From here, t'is only the simple implementation of the main method. */
pFinder = new SimplePathFinder(new MockLinkSource());
run(pFinder);
}
private static void run(PathFinder pFinder) {
Iterator<String> pIterator;
String from, to;
Scanner input = new Scanner(System.in);
System.out.print("From: ");
from = input.nextLine();
System.out.print("To: ");
to = input.nextLine();
try {
pIterator = pFinder.getPath(from, to).getPathIterator();
while(pIterator.hasNext()) {
System.out.print(pIterator.next());
if(pIterator.hasNext()) {
System.out.print("->");
}
}
System.out.println();
} catch(Exception e) {
System.out.println("Something is wrong. Check if your input is appropriate.");
}
}
}
|
package uac;
public class WildcardField extends IdentityField {
private static final String wildcard = "*";
public WildcardField(String name) {
super(name, wildcard);
}
@Override
public IdentityType getType() {
return IdentityType.Wildcard;
}
}
|
package org.opens.tgol.presentation.factory;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.opens.tanaguru.entity.audit.*;
import org.opens.tanaguru.entity.factory.audit.ProcessResultFactory;
import org.opens.tanaguru.entity.reference.Criterion;
import org.opens.tanaguru.entity.reference.Scope;
import org.opens.tanaguru.entity.reference.Test;
import org.opens.tanaguru.entity.reference.Theme;
import org.opens.tanaguru.entity.service.audit.AuditDataService;
import org.opens.tanaguru.entity.service.reference.CriterionDataService;
import org.opens.tanaguru.entity.service.reference.TestDataService;
import org.opens.tanaguru.entity.subject.WebResource;
import org.opens.tgol.entity.decorator.tanaguru.subject.WebResourceDataServiceDecorator;
import org.opens.tgol.presentation.data.RemarkInfos;
import org.opens.tgol.presentation.data.TestResult;
import org.opens.tgol.presentation.data.TestResultImpl;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author jkowalczyk
*/
public final class TestResultFactory {
private static final String NOT_TESTED_STR = "NOT_TESTED";
private final ResourceBundle representationBundle =
ResourceBundle.getBundle(TestResult.REPRESENTATION_BUNDLE_NAME);
private WebResourceDataServiceDecorator webResourceDataService;
@Autowired
public void setWebResourceDataService(WebResourceDataServiceDecorator webResourceDataServiceDecorator) {
this.webResourceDataService = webResourceDataServiceDecorator;
}
private AuditDataService auditDataService;
@Autowired
public void setAuditDataService(AuditDataService auditDataService) {
this.auditDataService = auditDataService;
}
private CriterionDataService criterionDataService;
@Autowired
public void setCriterionDataService(CriterionDataService criterionDataService) {
this.criterionDataService = criterionDataService;
}
private TestDataService testDataService;
@Autowired
public void setTestDataService(TestDataService testDataService) {
this.testDataService = testDataService;
}
private ProcessResultFactory processResultFactory;
@Autowired
public void setProcessResultFactory(ProcessResultFactory processResultFactory) {
this.processResultFactory = processResultFactory;
}
private String selectAllThemeKey;
public String getSelectAllThemeKey() {
return selectAllThemeKey;
}
public void setSelectAllThemeKey(String selectAllThemeKey) {
this.selectAllThemeKey = selectAllThemeKey;
}
/**
* The unique shared instance of TestResultFactory
*/
private static TestResultFactory testResultFactory;
/**
* Default private constructor
*/
private TestResultFactory(){}
public static synchronized TestResultFactory getInstance(){
if (testResultFactory == null) {
testResultFactory = new TestResultFactory();
}
return testResultFactory;
}
/**
*
* @return
*/
public TestResult getTestResult() {
return new TestResultImpl();
}
/**
*
* @param processResult
* @param test
* @param hasSourceCodeADoctype
* @param hasResultDetails
* @return
*/
public TestResult getTestResult(
ProcessResult processResult,
boolean hasSourceCodeWithDoctype,
boolean hasResultDetails) {
TestResult testResult = new TestResultImpl(hasSourceCodeWithDoctype);
testResult.setTestUrl(processResult.getTest().getDescription());
testResult.setTestShortLabel(processResult.getTest().getLabel());
testResult.setTestCode(processResult.getTest().getCode());
testResult.setLevelCode(processResult.getTest().getLevel().getCode());
testResult.setResult( processResult.getValue().toString());
testResult.setResultCode(setResultToLowerCase(processResult, testResult));
testResult.setRuleDesignUrl(processResult.getTest().getRuleDesignUrl());
testResult.setResultCounter(ResultCounterFactory.getInstance().getResultCounter());
testResult.setTestRepresentation(Integer.valueOf(representationBundle.
getString(testResult.getTestCode()+TestResult.REPRESENTATION_SUFFIX_KEY)));
testResult.setTest(processResult.getTest());
try {
testResult.setTestEvidenceRepresentationOrder(representationBundle.
getString(testResult.getTestCode()+TestResult.REPRESENTATION_ORDER_SUFFIX_KEY));
} catch (MissingResourceException mre) {
Logger.getLogger(this.getClass()).warn(mre);
}
if (hasResultDetails) {
setRemarkInfosMap(testResult, processResult);
}
return testResult;
}
public Map<Theme, List<TestResult>> getTestResultSortedByThemeMap(
WebResource webresource,
Scope scope,
boolean hasSourceCodeWithDoctype,
boolean hasResultDetails,
String theme,
Collection<String> testSolutionList){
Logger.getLogger(this.getClass()).error(" before getProcessResultListByWebResourceAndScope");
List<ProcessResult> netResultList = (List<ProcessResult>)
webResourceDataService.
getProcessResultListByWebResourceAndScope(webresource, scope, theme, testSolutionList);
Logger.getLogger(this.getClass()).error("after getProcessResultListByWebResourceAndScope");
// The not tested tests are not persisted but deduced from the testResultList
// If the not_tested solution is requested to be displayed, we add fake
// processResult to the current list.
if (testSolutionList.contains(NOT_TESTED_STR)) {
Logger.getLogger(this.getClass()).error("before add manually not tested results");
netResultList.addAll(addNotTestedProcessResult(getTestListFromWebResource(webresource), theme, netResultList));
Logger.getLogger(this.getClass()).error("after add manually not tested results");
}
Logger.getLogger(this.getClass()).error("start preparing ThemeResultMap");
return prepareThemeResultMap(
netResultList,
hasSourceCodeWithDoctype,
hasResultDetails);
}
/**
*
* @param netResultList
* @param hasSourceCodeWithDoctype
* @param hasResultDetails
* @return
*/
private Map<Theme, List<TestResult>> prepareThemeResultMap(
List<ProcessResult> netResultList,
boolean hasSourceCodeWithDoctype,
boolean hasResultDetails) {
// Map that associates a list of results with a theme
Map<Theme, List<TestResult>> testResultMap =
new LinkedHashMap<Theme, List<TestResult>>();
Logger.getLogger(this.getClass()).error("start sort netResultList");
sortCollection(netResultList);
Logger.getLogger(this.getClass()).error("after sort netResultList");
Logger.getLogger(this.getClass()).error("before extract remaks and evidenceElements for all process Result");
for (ProcessResult processResult : netResultList) {
if (processResult instanceof DefiniteResult) {
TestResult testResult = getTestResult(
processResult,
hasSourceCodeWithDoctype,
hasResultDetails);
Theme theme =
processResult.getTest().getCriterion().getTheme();
if (testResultMap.containsKey(theme)) {
testResultMap.get(theme).add(testResult);
} else {
List<TestResult> testResultList = new ArrayList<TestResult>();
testResultList.add(testResult);
testResultMap.put(theme, testResultList);
}
}
}
Logger.getLogger(this.getClass()).error("after extract remaks and evidenceElements for all process Result");
return testResultMap;
}
// /**
// * This methods prepare test results to be displayed
// * @param webresource
// * @param scope
// * @param hasSourceCodeADoctype
// * @param hasResultDetails
// * @return
// */
// public Map<Theme, List<TestResult>> getTestResultSortedByThemeMap(
// WebResource webresource,
// Scope scope,
// boolean hasSourceCodeWithDoctype,
// boolean hasResultDetails) {
// List<ProcessResult> netResultList = (List<ProcessResult>)
// webResourceDataService.
// getProcessResultListByWebResourceAndScope(webresource, scope);
// return prepareThemeResultMap(
// netResultList,
// getTestListFromWebResource(webresource),
// hasSourceCodeWithDoctype,
// hasResultDetails);
/**
*
* @param webresource
* @param scope
* @param hasSourceCodeWithDoctype
* @param hasResultDetails
* @param locale
* @return
* the test result list without user filter (used for the export function)
*/
public List<TestResult> getTestResultList(
WebResource webresource,
Scope scope,
boolean hasSourceCodeWithDoctype,
boolean hasResultDetails,
Locale locale) {
// Map that associates a list of results with a theme
List<TestResult> testResultList = new LinkedList<TestResult>();
List<ProcessResult> netResultList = (List<ProcessResult>)
webResourceDataService.
getProcessResultListByWebResourceAndScope(webresource, scope);
netResultList.addAll(
addNotTestedProcessResult(
getTestListFromWebResource(webresource),
selectAllThemeKey,
netResultList));
sortCollection(netResultList);
for (ProcessResult processResult : netResultList) {
if (processResult instanceof DefiniteResult) {
TestResult testResult = getTestResult(
processResult,
hasSourceCodeWithDoctype,
hasResultDetails);
testResultList.add(testResult);
}
}
return testResultList;
}
/**
*
* @param webresource
* @param scope
* @param hasSourceCodeWithDoctype
* @param hasResultDetails
* @param locale
* @return
* the test result list without user filter (used for the export function)
*/
public Map<Theme, List<TestResult>> getTestResultListFromCriterion(
WebResource webresource,
boolean hasSourceCodeWithDoctype,
Long criterionId) {
// Map that associates a list of results with a theme
List<TestResult> testResultList = new LinkedList<TestResult>();
Criterion crit = criterionDataService.read(criterionId);
List<ProcessResult> netResultList = (List<ProcessResult>)
webResourceDataService.
getProcessResultListByWebResourceAndCriterion(
webresource,
crit);
netResultList.addAll(
addNotTestedProcessResult(
testDataService.findAllByCriterion(crit),
crit.getTheme().getCode(),
netResultList));
sortCollection(netResultList);
for (ProcessResult processResult : netResultList) {
if (processResult instanceof DefiniteResult) {
TestResult testResult = getTestResult(
processResult,
hasSourceCodeWithDoctype,
true);
testResultList.add(testResult);
}
}
Map<Theme, List<TestResult>> testResultMap = new HashMap<Theme, List<TestResult>>();
testResultMap.put(crit.getTheme(), testResultList);
return testResultMap;
}
/**
* This method sorts the processResult elements
* @param processResultList
*/
private void sortCollection(List<? extends ProcessResult> processResultList) {
Collections.sort(processResultList, new Comparator<ProcessResult>() {
@Override
public int compare(ProcessResult o1, ProcessResult o2) {
return String.CASE_INSENSITIVE_ORDER.compare(
o1.getTest().getCode(),
o2.getTest().getCode());
}
});
}
/**
* This method sets the resultToLower attribute
* according to the result value and sets the element counter attribute
*/
private String setResultToLowerCase(
ProcessResult processResult,
TestResult testResult) {
if (testResult.getResult().equalsIgnoreCase(TestResult.FAILED)) {
if (processResult.getElementCounter() != 0) {
testResult.setElementCounter(processResult.getElementCounter());
}
return TestResult.FAILED_LOWER;
} else if (testResult.getResult().equalsIgnoreCase(TestResult.PASSED)) {
return TestResult.PASSED_LOWER;
} else if (testResult.getResult().equalsIgnoreCase(TestResult.NEED_MORE_INFO)) {
if (processResult.getElementCounter() != 0) {
testResult.setElementCounter(processResult.getElementCounter());
}
return TestResult.NEED_MORE_INFO_LOWER;
} else if (testResult.getResult().equalsIgnoreCase(TestResult.NOT_APPLICABLE)) {
return TestResult.NOT_APPLICABLE_LOWER;
} else if (testResult.getResult().equalsIgnoreCase(TestResult.NOT_TESTED)) {
return TestResult.NOT_TESTED_LOWER;
}
return null;
}
/**
* @param result
*/
@SuppressWarnings("unchecked")
public void setRemarkInfosMap(TestResult testResult, ProcessResult processResult) {
for (ProcessRemark remark : sortRemarkSet((Collection<ProcessRemark>)processResult.getRemarkSet())) {
RemarkInfos currentRemarkInfos =
getRemarkInfo(testResult, remark.getMessageCode(), extractRemarkTarget(remark), remark);
currentRemarkInfos.setRemarkResult(addElementToCounter(testResult,remark.getIssue()));
addElementsToRemark(testResult, currentRemarkInfos, remark);
}
}
/**
* This method sorts the processResult elements in ascending order
* @param processResultList
*/
private List<ProcessRemark> sortRemarkSet(Collection<ProcessRemark> processRemarkSet) {
List<ProcessRemark> processRemarkList = new ArrayList<ProcessRemark>();
processRemarkList.addAll(processRemarkSet);
Collections.sort(processRemarkList, new Comparator<ProcessRemark>() {
@Override
public int compare(ProcessRemark o1, ProcessRemark o2) {
if (o1.getId() < o2.getId()) {
return -1;
} else {
return 1;
}
}
});
return processRemarkList;
}
/**
*
* @param remark
* @return
*/
private String extractRemarkTarget(ProcessRemark remark) {
for (EvidenceElement evidenceElement :
remark.getElementList()) {
if (evidenceElement.getEvidence().getCode().
equalsIgnoreCase(TestResult.ELEMENT_NAME_KEY)) {
return "<code><"+evidenceElement.getValue().toLowerCase()+"></code>";
}
}
return null;
}
/**
* This methods converts raw processRemark data to displayable RemarkInfosImpl
* data
* @param messageCode
* @return
*/
private RemarkInfos getRemarkInfo(
TestResult testResult,
String messageCode,
String remarkTarget,
ProcessRemark remark) {
for (RemarkInfos remarkInfos : testResult.getRemarkInfosList()) {
if (remarkInfos.getMessageCode().equalsIgnoreCase(messageCode) &&
(
(remarkTarget != null && remarkInfos.getRemarkTarget() != null && remarkInfos.getRemarkTarget().equalsIgnoreCase(remarkTarget)) ||
(remarkTarget == null && remarkInfos.getRemarkTarget() == null)
)) {
return remarkInfos;
}
}
RemarkInfos newRemarkInfo;
if (remarkTarget != null) {
newRemarkInfo = RemarkInfosFactory.getInstance().getRemarksInfo(messageCode, remarkTarget);
} else {
newRemarkInfo = RemarkInfosFactory.getInstance().getRemarksInfo(messageCode);
}
if (remark.getIssue().equals(TestSolution.FAILED)) {
testResult.getRemarkInfosList().add(0, newRemarkInfo);
} else {
testResult.getRemarkInfosList().add(newRemarkInfo);
}
return newRemarkInfo;
}
/**
* @param testResult
* @param remarkResult
* @return
*/
private String addElementToCounter(TestResult testResult, TestSolution remarkResult) {
switch (remarkResult) {
case PASSED:
return TestResult.PASSED_LOWER;
case NOT_APPLICABLE:
return TestResult.NOT_APPLICABLE_LOWER;
case FAILED:
if (testResult.getResultCounter().getFailedCount() == -1) {
testResult.getResultCounter().setFailedCount(1);
} else {
testResult.getResultCounter().setFailedCount(testResult.getResultCounter().getFailedCount()+1);
}
return TestResult.FAILED_LOWER;
case NEED_MORE_INFO:
if (testResult.getResultCounter().getNmiCount() == -1) {
testResult.getResultCounter().setNmiCount(1);
} else {
testResult.getResultCounter().setNmiCount(testResult.getResultCounter().getNmiCount()+1);
}
return TestResult.NEED_MORE_INFO_LOWER;
case NOT_TESTED:
return TestResult.NOT_TESTED_LOWER;
default:
return "";
}
}
/**
*
* @param currentRemarkInfos
* @param remark
*/
private void addElementsToRemark(
TestResult testResult,
RemarkInfos currentRemarkInfos,
ProcessRemark remark) {
Map <String, String> elementMap = new HashMap<String, String>();
if (remark instanceof SourceCodeRemark) {
int lineNumber = computeLineNumber(testResult,(SourceCodeRemark)remark);
if (lineNumber > 0) {
elementMap.put(TestResult.LINE_NUMBER_KEY, String.valueOf(lineNumber));
}
}
for (EvidenceElement evidenceElement : remark.getElementList()) {
if (!evidenceElement.getEvidence().getCode().
equalsIgnoreCase(TestResult.ELEMENT_NAME_KEY)) {
elementMap.put(
evidenceElement.getEvidence().getCode(),
evidenceElement.getValue());
}
}
// Has to be removerd when decide to generalise to all representations
if (testResult.getTestRepresentationType() == TestResult.TABULAR_REPRESENTATION) {
elementMap = sortEvidenceElementMap(testResult,elementMap);
}
if (!elementMap.isEmpty()) {
currentRemarkInfos.addEvidenceElement(elementMap);
}
}
/**
*
* @param remark
* @param testResult
* @return
*/
private int computeLineNumber(
TestResult testResult,
SourceCodeRemark remark) {
int lineNumber;
// The doctype is added when the result is displayed.
// When the doctype is not null, each line remark has to be
// one-line-shifted
if (testResult.hasSourceCodeADoctype()) {
lineNumber = remark.getLineNumber() + 1;
} else {
lineNumber = remark.getLineNumber();
}
return lineNumber;
}
/**
*
* @param testResult
* @param evidenceElementMap
* @return
*/
private Map<String, String> sortEvidenceElementMap(
TestResult testResult,
Map<String, String> evidenceElementMap) {
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
String tmpKey;
for(int i=0;i<testResult.getTestEvidenceRepresentationOrder().length;i++){
tmpKey = testResult.getTestEvidenceRepresentationOrder()[i];
if (evidenceElementMap.containsKey(tmpKey)) {
sortedMap.put(tmpKey, evidenceElementMap.get(tmpKey));
} else {
Logger.getLogger(this.getClass()).info("The key " + testResult.getTestEvidenceRepresentationOrder()[i] +
" is expected for the representation but not present in the"
+ " result evidence elements");
return evidenceElementMap;
}
}
return sortedMap;
}
/**
* Some tests may have not ProcessResult, but are needed to be displayed
* as not tested test. For each test without ProcessResult, we create
* a new ProcessResult with NOT_TESTED as the result.
*
* @param testList
* @param themeCode
* @param netResultList
* @return
*/
private Collection<ProcessResult> addNotTestedProcessResult(
Collection<Test>testList,
String themeCode,
List<ProcessResult> netResultList) {
Collection<Test> testedTestList = new ArrayList<Test>();
for (ProcessResult pr : netResultList) {
testedTestList.add(pr.getTest());
}
Collection<ProcessResult> notTestedProcessResult = new ArrayList<ProcessResult>();
for (Test test : testList) {
// if the test has no ProcessResult and its theme is part of the user
// selection, a NOT_TESTED result ProcessRemark is created
if (!testedTestList.contains(test) && (
StringUtils.equalsIgnoreCase(test.getCriterion().getTheme().getCode(), themeCode) ||
themeCode == null ||
StringUtils.equalsIgnoreCase(selectAllThemeKey, themeCode))) {
ProcessResult pr = processResultFactory.createDefiniteResult();
pr.setTest(test);
pr.setValue(TestSolution.NOT_TESTED);
notTestedProcessResult.add(pr);
pr.setRemarkSet(new ArrayList<ProcessRemark>());
}
}
return notTestedProcessResult;
}
/**
* Return the list of tests for a given webResource. If the webresource has
* a parent, we pass through the parent linked with the audit to retrieve
* the test list.
* @param wr
* @return
*/
private Collection<Test> getTestListFromWebResource(WebResource wr) {
Audit audit;
if (wr.getParent() == null && wr.getAudit() != null) {
audit = wr.getAudit();
} else {
audit = wr.getParent().getAudit();
}
return auditDataService.getAuditWithTest(audit.getId()).getTestList();
}
}
|
package edu.northwestern.bioinformatics.studycalendar.web.admin;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole;
import edu.northwestern.bioinformatics.studycalendar.utils.editors.JsonArrayEditor;
import edu.northwestern.bioinformatics.studycalendar.web.PscAbstractCommandController;
import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.AccessControl;
import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.AuthorizedFor;
import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSessionFactory;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRole;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembershipLoader;
import gov.nih.nci.security.AuthorizationManager;
import gov.nih.nci.security.authorization.domainobjects.User;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
/**
* @author Rhett Sutphin
*/
@AccessControl(roles = Role.SYSTEM_ADMINISTRATOR)
@AuthorizedFor({ PscRole.SYSTEM_ADMINISTRATOR, PscRole.USER_ADMINISTRATOR })
public class AdministerUserController extends PscAbstractCommandController<ProvisionUserCommand> {
private AuthorizationManager authorizationManager;
private SuiteRoleMembershipLoader suiteRoleMembershipLoader;
private ProvisioningSessionFactory provisioningSessionFactory;
private SiteDao siteDao;
@Override
protected ProvisionUserCommand getCommand(HttpServletRequest request) throws Exception {
String userIdent = ServletRequestUtils.getRequiredStringParameter(request, "user");
User targetUser = authorizationManager.getUserById(userIdent);
return new ProvisionUserCommand(
targetUser,
suiteRoleMembershipLoader.getProvisioningRoleMemberships(targetUser.getUserId()),
provisioningSessionFactory.createSession(targetUser.getUserId()),
authorizationManager,
// TODO: implement authorization limits
Arrays.asList(SuiteRole.values()), siteDao.getAll(), true);
}
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(JSONArray.class, "roleChanges", new JsonArrayEditor());
}
@Override
protected ModelAndView handle(ProvisionUserCommand command, BindException errors, HttpServletRequest request, HttpServletResponse response) throws Exception {
if ("POST".equals(request.getMethod())) {
command.apply();
return new ModelAndView("redirectToUserList");
} else {
return new ModelAndView("admin/administerUser", errors.getModel());
}
}
////// CONFIGURATION
@Required
public void setAuthorizationManager(AuthorizationManager authorizationManager) {
this.authorizationManager = authorizationManager;
}
@Required
public void setProvisioningSessionFactory(ProvisioningSessionFactory provisioningSessionFactory) {
this.provisioningSessionFactory = provisioningSessionFactory;
}
@Required
public void setSiteDao(SiteDao siteDao) {
this.siteDao = siteDao;
}
@Required
public void setSuiteRoleMembershipLoader(SuiteRoleMembershipLoader suiteRoleMembershipLoader) {
this.suiteRoleMembershipLoader = suiteRoleMembershipLoader;
}
}
|
package com.hp.oo.execution.services;
import com.hp.oo.broker.entities.BranchContextHolder;
import com.hp.oo.broker.entities.RunningExecutionPlan;
import com.hp.oo.broker.services.RuntimeValueService;
import com.hp.oo.engine.execution.events.services.ExecutionEventService;
import com.hp.oo.enginefacade.execution.ExecutionEnums;
import com.hp.oo.enginefacade.execution.ExecutionEnums.ExecutionStatus;
import com.hp.oo.enginefacade.execution.ExecutionEnums.LogLevel;
import com.hp.oo.enginefacade.execution.ExecutionEnums.LogLevelCategory;
import com.hp.oo.enginefacade.execution.ExecutionSummary;
import com.hp.oo.enginefacade.execution.PauseReason;
import com.hp.oo.enginefacade.execution.StartBranchDataContainer;
import com.hp.oo.execution.ExecutionEventAggregatorHolder;
import com.hp.oo.execution.ExecutionLogLevelHolder;
import com.hp.oo.execution.gateways.EventGateway;
import com.hp.oo.execution.reflection.ReflectionAdapter;
import com.hp.oo.execution.services.dbsupport.WorkerDbSupportService;
import com.hp.oo.internal.sdk.execution.Execution;
import com.hp.oo.internal.sdk.execution.ExecutionConstants;
import com.hp.oo.internal.sdk.execution.ExecutionStep;
import com.hp.oo.internal.sdk.execution.OOContext;
import com.hp.oo.internal.sdk.execution.events.EventBus;
import com.hp.oo.internal.sdk.execution.events.EventWrapper;
import com.hp.oo.internal.sdk.execution.events.ExecutionEvent;
import com.hp.oo.internal.sdk.execution.events.ExecutionEventFactory;
import com.hp.oo.internal.sdk.execution.events.ExecutionEventUtils;
import com.hp.oo.orchestrator.services.CancelExecutionService;
import com.hp.oo.orchestrator.services.PauseResumeService;
import com.hp.oo.orchestrator.services.configuration.WorkerConfigurationService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@Component("agent")
public final class ExecutionServiceImpl implements ExecutionService {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private PauseResumeService pauseService;
@Autowired
private ReflectionAdapter reflectionAdapter;
@Autowired
private WorkerDbSupportService workerDbSupportService;
@Autowired
private EventGateway eventGateway;
@Autowired
private WorkerConfigurationService configurationService;
@Autowired
private ExecutionEventService executionEventService;
@Autowired
private CancelExecutionService cancelExecutionService;
@Autowired
private RuntimeValueService runtimeValueService;
@Autowired
private WorkerRecoveryManager recoveryManager;
@Autowired
private EventBus eventBus;
@Override
public Execution execute(Execution execution) {
try {
// sets thread local context with log level
storeCurrentLogLevel(execution);
// sets thread local context with a reference to the execution objects aggregated events list
storeAggregatedEvents(execution);
// handle flow cancellation
if (handleCancelledFlow(execution, isDebuggerMode(execution.getSystemContext()))) {
return execution;
}
ExecutionStep currStep = loadExecutionStep(execution);
//Check if this execution was paused
if (!isDebuggerMode(execution.getSystemContext()) && handlePausedFlow(execution)) {
return null;
}
if(execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_QUEUE) != null){
addExecutionEvent(execution);
dumpEvents(execution);
storeAggregatedEvents(execution);
}
//Run the execution step
executeStep(execution, currStep);
//Run the navigation
navigate(execution, currStep);
// currently handles groups and jms optimizations
postExecutionSettings(execution);
//If execution was paused in afl - to avoid delay of configuration
if (execution.getSystemContext().containsKey(ExecutionConstants.EXECUTION_PAUSED)) {
if (!isDebuggerMode(execution.getSystemContext()) && handlePausedFlowAfterStep(execution)) {
return null;
}
if (isDebuggerMode(execution.getSystemContext()) && handlePausedFlowForDebuggerMode(execution)) {
return null;
}
}
// add execution events
addExecutionEvent(execution);
//dum bus event
// dumpBusEvents(execution);
// dump execution events
dumpExecutionEvents(execution, true);
if (logger.isDebugEnabled()) {
logger.debug("End of step: " + execution.getPosition() + " in execution id: " + execution.getExecutionId());
}
return execution;
} catch (Exception ex) {
//In case this is execution of branch that failed - need special treatment
if (execution.getSystemContext().containsKey(ExecutionConstants.SPLIT_ID)) {
handleBranchFailure(execution, ex);
execution.setPosition(-1L); //finishing this branch but not finishing the entire flow
return execution;
} else {
logger.error("Error during execution: ", ex);
execution.getSystemContext().put(ExecutionConstants.EXECUTION_STEP_ERROR_KEY, ex.getMessage()); //this is done only fo reporting
execution.getSystemContext().put(ExecutionConstants.FLOW_TERMINATION_TYPE, ExecutionStatus.SYSTEM_FAILURE);
execution.setPosition(null); //this ends the flow!!!
return execution;
}
}
}
@Override
//returns null in case the split was not done - flow is paused or cancelled
public List<Execution> executeSplit(Execution execution) {
try {
// sets thread local context with log level
storeCurrentLogLevel(execution);
// sets thread local context with a reference to the execution objects aggregated events list
storeAggregatedEvents(execution);
ExecutionStep currStep = loadExecutionStep(execution);
//Run the split step
List<StartBranchDataContainer> newBranches = executeSplitStep(execution, currStep);
List<Execution> newExecutions = createChildExecutions(execution.getExecutionId(), newBranches);
//Run the navigation
navigate(execution, currStep);
// add execution events
addExecutionEvent(execution);
// dump execution events
dumpExecutionEvents(execution, true);
if (logger.isDebugEnabled()) {
logger.debug("End of step: " + execution.getPosition() + " in execution id: " + execution.getExecutionId());
}
return newExecutions;
} catch (Exception ex) {
logger.error("Exception during the split step!", ex);
throw ex;
}
}
private List<Execution> createChildExecutions(String executionId, List<StartBranchDataContainer> newBranches) {
List<Execution> newExecutions = new ArrayList<>();
String splitId = UUID.randomUUID().toString();
for (int i = 0; i < newBranches.size(); i++) {
StartBranchDataContainer from = newBranches.get(i);
Execution to = new Execution(Long.parseLong(executionId),
from.getExecutionPlanId(),
from.getStartPosition(),
from.getContexts(),
from.getSystemContext());
to.putSplitId(splitId);
to.putBranchId(splitId + ":" + (i + 1));
newExecutions.add(to);
}
return newExecutions;
}
@Override
public boolean isSplitStep(Execution execution) {
ExecutionStep currStep = loadExecutionStep(execution);
return currStep.isSplitStep();
}
protected boolean isExecutionTerminating(Execution execution) {
return (execution.getPosition() == null || execution.getPosition() == -1L || execution.getPosition() == -2L);
}
//This method deals with the situation when a branch execution was terminated because of a system failure - not execution exception
protected void handleBranchFailure(Execution execution, Exception exception) {
String splitId = (String) execution.getSystemContext().get(ExecutionConstants.SPLIT_ID);
String branchId = (String) execution.getSystemContext().get(ExecutionConstants.BRANCH_ID);
logger.error("Branch failed due to SYSTEM FAILURE! Execution id: " + execution.getExecutionId() + " Branch id: " + branchId, exception);
BranchContextHolder branchContextHolder = new BranchContextHolder();
branchContextHolder.setSplitId(splitId);
branchContextHolder.setBranchId(branchId);
branchContextHolder.setExecutionId((String) execution.getSystemContext().get(ExecutionConstants.EXECUTION_ID_CONTEXT));
Map<String, OOContext> context = new HashMap<>();
branchContextHolder.setContext(context);
branchContextHolder.setBranchException(exception.getMessage());
while (!recoveryManager.isInRecovery()) {
try {
workerDbSupportService.createBranchContext(branchContextHolder);
//todo - maybe add events like in endBranch action
try {
clearBranchLocks(execution);
} catch (Exception ex) {
logger.error("Failed to clear locks on execution " + execution.getExecutionId(), ex);
}
return;
} catch (Exception ex) {
logger.error("Failed to save branch failure. Retrying...", ex);
try {
Thread.sleep(5000L);
} catch (InterruptedException iex) {/*do nothing*/}
}
}
}
protected void clearBranchLocks(Execution execution) {
@SuppressWarnings("unchecked")
Set<String> acquiredLockIds = (Set<String>) execution.getSystemContext().get(ExecutionConstants.ACQUIRED_LOCKS);
if (acquiredLockIds != null) {
for (String lockId : acquiredLockIds) {
runtimeValueService.remove(ExecutionConstants.LOCK_PREFIX_IN_DB + lockId);
}
execution.getSystemContext().remove(ExecutionConstants.ACQUIRED_LOCKS);
}
}
protected boolean handleCancelledFlow(Execution execution, boolean isDebugMode) {
String executionId = execution.getExecutionId();
boolean executionIsCancelled;
// Different methods to see if the run is cancelled, and cancel it:
// in debug-mode we go to the DB (thru the service).
// in regular execution we don't want to ask the DB every step (expensive..), so we use the WorkerConfigurationService which goes to the DB every x seconds.
if (isDebugMode) {
executionIsCancelled = cancelExecutionService.isCanceledExecution(executionId); // in this case we already cancel the execution if needed
} else {
List<String> cancelledExecutions = configurationService.getCancelledExecutions(); // in this case - just check if need to cancel. It will set as cancelled later on QueueEventListener
executionIsCancelled = cancelledExecutions.contains(executionId);
}
//Another scenario of getting canceled - it was cancelled from the SplitJoinService (the configuration can still be not updated). Defect #:22060
if (ExecutionStatus.CANCELED.equals(execution.getSystemContext().get(ExecutionConstants.FLOW_TERMINATION_TYPE))) {
executionIsCancelled = true;
}
if (executionIsCancelled) {
// NOTE: an execution can be cancelled directly from CancelExecutionService, if it's currently paused.
// Thus, if you change the code here, please check CancelExecutionService as well.
execution.getSystemContext().put(ExecutionConstants.FLOW_TERMINATION_TYPE, ExecutionStatus.CANCELED);
execution.setPosition(null);
return true;
}
return false;
}
// check if the execution should be Paused, and pause it if needed
protected boolean handlePausedFlow(Execution execution) {
String branchId = (String) execution.getSystemContext().get(ExecutionConstants.BRANCH_ID);
PauseReason reason = findPauseReason(execution.getExecutionId(), branchId);
if (reason != null) { // need to pause the execution
pauseFlow(reason, execution);
return true;
} else {
return false;
}
}
// no need to check if paused - because this is called after the step, when the Pause flag exists in the context
private boolean handlePausedFlowAfterStep(Execution execution) {
String branchId = (String) execution.getSystemContext().get(ExecutionConstants.BRANCH_ID);
PauseReason reason = null;
ExecutionSummary execSummary = pauseService.readPausedExecution(execution.getExecutionId(), branchId);
if (execSummary != null && execSummary.getStatus().equals(ExecutionStatus.PENDING_PAUSE)) {
reason = execSummary.getPauseReason();
}
if (reason != null) { // need to pause the execution
pauseFlow(reason, execution);
return true;
} else {
return false;
}
}
private void pauseFlow(PauseReason reason, Execution execution) {
Map<String, Serializable> systemContext = execution.getSystemContext();
String executionId = execution.getExecutionId();
String branchId = (String) systemContext.get(ExecutionConstants.BRANCH_ID);
String flowUuid = (String) systemContext.get(ExecutionConstants.FLOW_UUID);
@SuppressWarnings({"unchecked"})
ArrayDeque<ExecutionEvent> eventsQueue = (ArrayDeque<ExecutionEvent>) systemContext.get(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
if (eventsQueue == null) {
eventsQueue = new ArrayDeque<>();
execution.getSystemContext().put(ExecutionConstants.EXECUTION_EVENTS_QUEUE, eventsQueue);
}
//If USER_PAUSED send such event
if (reason.equals(PauseReason.USER_PAUSED)) {
ExecutionEvent pauseEvent = ExecutionEventFactory.createPausedEvent(executionId, flowUuid, ExecutionEventUtils.increaseEvent(systemContext), systemContext);
eventsQueue.add(pauseEvent);
if (branchId != null) {
// we pause the branch because the Parent was user-paused (see findPauseReason)
pauseService.pauseExecution(executionId, branchId, reason); // this creates a DB record for this branch, as Pending-paused
}
}
ExecutionEvent stepLogEvent = ExecutionEventFactory.createStepLogEvent(executionId,ExecutionEventUtils.increaseEvent(systemContext), ExecutionEnums.StepLogCategory.STEP_PAUSED, systemContext);
eventsQueue.add(stepLogEvent);
//just dump events that were written in afl or just now
addExecutionEvent(execution);
dumpEvents(execution);
//Write execution to the db! Pay attention - do not do anything to the execution or its context after this line!!!
pauseService.writeExecutionObject(executionId, branchId, execution);
if (logger.isDebugEnabled()) {
logger.debug("Execution with execution_id: " + execution.getExecutionId() + " is paused!");
}
}
private boolean handlePausedFlowForDebuggerMode(Execution execution) {
Map<String, Serializable> systemContext = execution.getSystemContext();
String executionId = execution.getExecutionId();
String branchId = (String) systemContext.get(ExecutionConstants.BRANCH_ID);
//get the type of paused flow
PauseReason reason = pauseService.writeExecutionObject(executionId, branchId, execution);
if (reason == null) {
return false; //indicate that the flow was not paused
}
//just dump events that were written in afl
addExecutionEvent(execution);
dumpEvents(execution);
if (logger.isDebugEnabled()) {
logger.debug("Execution with execution_id: " + execution.getExecutionId() + " is paused!");
}
return true;
}
private PauseReason findPauseReason(String executionId, String branchId) {
// 1. Check the configuration according to branch (can be null or not null...)
if (configurationService.isExecutionPaused(executionId, branchId)) {
ExecutionSummary execSummary = pauseService.readPausedExecution(executionId, branchId);
if (execSummary != null && execSummary.getStatus().equals(ExecutionStatus.PENDING_PAUSE)) {
return execSummary.getPauseReason();
}
// 2. Check the parent if we're in branch (subflow or MI\Parallel lane).
// If the user pressed Pause on the Parent then we need to pause the branch (the parent is in the Suspended table).
} else if (branchId != null &&
configurationService.isExecutionPaused(executionId, null)) {
ExecutionSummary execSummary = pauseService.readPausedExecution(executionId, null);
if (execSummary != null && execSummary.getStatus().equals(ExecutionStatus.PENDING_PAUSE)) {
PauseReason reason = execSummary.getPauseReason();
// we only care about User-Paused here!
// we don't want to Pause if the parent is paused due to branch_paused! (other branch is paused for some reason (e.g. required_input), so the parent is paused as well).
if (PauseReason.USER_PAUSED.equals(reason)) {
return reason;
}
}
}
return null; // not paused
}
private void storeAggregatedEvents(Execution execution) {
if (execution.getAggregatedEvents() == null) {
execution.setAggregatedEvents(new ArrayList<ExecutionEvent>());
}
ExecutionEventAggregatorHolder.setAggregatedExecutionEvents(execution.getAggregatedEvents());
}
private void addExecutionEvent(Execution execution) {
// move all the events form the SystemContext into the event channel
@SuppressWarnings("unchecked") ArrayDeque<ExecutionEvent> eventsQueue = (ArrayDeque) execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
for (ExecutionEvent executionEvent : eventsQueue) {
eventGateway.addEvent(executionEvent);
}
eventsQueue.clear();
execution.getSystemContext().remove(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
// clean up thread local context to avoid memory leaks
ExecutionLogLevelHolder.removeExecutionLogLevel();
}
private void dumpExecutionEvents(Execution execution, boolean forceDump) {
boolean shouldDump = false;
long currTime = System.currentTimeMillis();
//Init it according system context (done in order to support parallel immediate events release of parent lane)
if (execution.getSystemContext().get(ExecutionConstants.MUST_RELEASE_EVENTS) != null) {
shouldDump = (boolean) execution.getSystemContext().get(ExecutionConstants.MUST_RELEASE_EVENTS);
execution.getSystemContext().remove(ExecutionConstants.MUST_RELEASE_EVENTS);
}
// timeout trigger
//noinspection ConstantConditions
shouldDump |= (execution.getLastEventDumpTime() != 0) &&
(currTime - execution.getLastEventDumpTime() >= ExecutionConstants.EVENT_AGGREGATION_TIME_THRESHOLD);
// amount trigger
shouldDump |= execution.getAggregatedEvents().size() >= ExecutionConstants.EVENT_AGGREGATION_AMOUNT_THRESHOLD;
// ending execution trigger (null for flow ending, -1L for mi/parralel, -2L for subflow)
shouldDump |= isExecutionTerminating(execution);
// force it ?
shouldDump |= forceDump;
// make sure we are actually sending something
shouldDump &= execution.getAggregatedEvents().size() > 0;
// in case we run with DEBUGGER MODE then dum events immediately
if (shouldDump || isDebuggerMode(execution.getSystemContext())) {
dumpEvents(execution);
}
// clean up thread local context to avoid memory leaks
ExecutionEventAggregatorHolder.removeAggregatedExecutionEvents();
}
private boolean isDebuggerMode(Map<String, Serializable> systemContext) {
Boolean isDebuggerMode = (Boolean) systemContext.get(ExecutionConstants.DEBUGGER_MODE);
if (isDebuggerMode == null) {
return false;
}
return isDebuggerMode;
}
private void dumpEvents(Execution execution) {
List<ExecutionEvent> executionEvents = execution.getAggregatedEvents();
for (ExecutionEvent executionEvent:executionEvents){
eventBus.dispatch(new EventWrapper(executionEvent.getType().name(), executionEvent));
}
List<ExecutionEvent> filteredExecutionEvents = new ArrayList<>();
for (ExecutionEvent executionEvent : executionEvents){
if(executionEvent.getType().equals(ExecutionEnums.Event.STEP_LOG)){
continue;
}
filteredExecutionEvents.add(executionEvent);
}
executionEventService.createEvents(filteredExecutionEvents);
execution.getAggregatedEvents().clear(); //must clean so we wont send it twice - once from here and once from the QueueListener onTerminated()
execution.setLastEventDumpTime(System.currentTimeMillis());
}
// private void dumpEvents(Execution execution) {
// List<ExecutionEvent> executionEvents = execution.getAggregatedEvents();
// executionEventService.createEvents(executionEvents);
// execution.getAggregatedEvents().clear(); //must clean so we wont send it twice - once from here and once from the QueueListener onTerminated()
// execution.setLastEventDumpTime(System.currentTimeMillis());
private void dumpBusEvents(Execution execution) {
@SuppressWarnings("unchecked") ArrayDeque<ExecutionEvent> eventsQueue = (ArrayDeque) execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
Iterator<ExecutionEvent> executionEvents = eventsQueue.iterator();
while(executionEvents.hasNext()){
ExecutionEvent executionEvent = executionEvents.next();
if(executionEvent.getType().equals(ExecutionEnums.Event.STEP_LOG)){
eventBus.dispatch(new EventWrapper(executionEvent.getType().name(), executionEvent));
executionEvents.remove();
}
}
}
private void storeCurrentLogLevel(Execution execution) {
String logLevelStr = (String) execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_LOG_LEVEL);
if (StringUtils.isNotEmpty(logLevelStr)) {
LogLevel logLevel;
try {
logLevel = LogLevel.valueOf(logLevelStr);
} catch (NullPointerException ex) {
logLevel = LogLevel.INFO;
}
ExecutionLogLevelHolder.setExecutionLogLevel(logLevel);
}
}
protected ExecutionStep loadExecutionStep(Execution execution) {
RunningExecutionPlan runningExecutionPlan;
if (execution != null) {
//Optimization for external workers - run the content only without loading the execution plan
if (execution.getSystemContext().get(ExecutionConstants.CONTENT_EXECUTION_STEP) != null) {
return (ExecutionStep) execution.getSystemContext().get(ExecutionConstants.CONTENT_EXECUTION_STEP);
} else {
Long position = execution.getPosition();
if (position != null) {
runningExecutionPlan = workerDbSupportService.readExecutionPlanById(execution.getRunningExecutionPlanId());
if (runningExecutionPlan != null) {
ExecutionStep currStep = runningExecutionPlan.getExecutionPlan().getStep(position);
if (logger.isDebugEnabled()) {
logger.debug("Begin step: " + position + " in flow " + runningExecutionPlan.getExecutionPlan().getFlowUuid() + " [" + execution.getExecutionId() + "]");
}
if (currStep != null) {
return currStep;
}
}
}
}
}
//If we got here - one of the objects was null
throw new RuntimeException("Failed to load ExecutionStep!");
}
protected void executeStep(Execution execution, ExecutionStep currStep) {
try {
Map<String, Object> stepData = new HashMap<>(currStep.getActionData());
//We add all the contexts to the step data - so inside of each control action we will have access to all contexts
addContextData(stepData, execution);
// put in Queue the ExecutionEvent
ArrayDeque<ExecutionEvent> eventsQueue = new ArrayDeque<>();
execution.getSystemContext().put(ExecutionConstants.EXECUTION_EVENTS_QUEUE, eventsQueue);
//now we run the exe step
reflectionAdapter.executeControlAction(currStep.getAction(), stepData);
} catch (RuntimeException ex) {
logger.error("Error occurred during operation execution. Execution id: " + execution.getExecutionId(), ex);
execution.getSystemContext().put(ExecutionConstants.EXECUTION_STEP_ERROR_KEY, ex.getMessage());
try {
ExecutionEvent logEvent = createLogEvent(execution, currStep, ex, "Error occurred during operation execution", LogLevelCategory.STEP_OPER_ERROR, execution.getSystemContext());
@SuppressWarnings("unchecked") Deque<ExecutionEvent> eventsQueue = (Deque<ExecutionEvent>) execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
eventsQueue.add(logEvent);
ExecutionEvent stepLogEvent = ExecutionEventFactory.createStepLogEvent(execution.getExecutionId(),ExecutionEventUtils.increaseEvent(execution.getSystemContext()),
ExecutionEnums.StepLogCategory.STEP_ERROR, execution.getSystemContext());
eventsQueue.add(stepLogEvent);
} catch (RuntimeException eventEx) {
logger.error("Failed to create event: ", eventEx);
}
}
}
protected List<StartBranchDataContainer> executeSplitStep(Execution execution, ExecutionStep currStep) {
try {
Map<String, Object> stepData = new HashMap<>(currStep.getActionData());
//We add all the contexts to the step data - so inside of each control action we will have access to all contexts
addContextData(stepData, execution);
// put in Queue the ExecutionEvent
ArrayDeque<ExecutionEvent> eventsQueue = new ArrayDeque<>();
execution.getSystemContext().put(ExecutionConstants.EXECUTION_EVENTS_QUEUE, eventsQueue);
//now we run the exe step
return (List<StartBranchDataContainer>) reflectionAdapter.executeControlAction(currStep.getAction(), stepData);
} catch (RuntimeException ex) {
logger.error("Error occurred during operation execution. Execution id: " + execution.getExecutionId(), ex);
execution.getSystemContext().put(ExecutionConstants.EXECUTION_STEP_ERROR_KEY, ex.getMessage());
try {
ExecutionEvent logEvent = createLogEvent(execution, currStep, ex, "Error occurred during operation execution", LogLevelCategory.STEP_OPER_ERROR, execution.getSystemContext());
@SuppressWarnings("unchecked") Deque<ExecutionEvent> eventsQueue = (Deque<ExecutionEvent>) execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
eventsQueue.add(logEvent);
ExecutionEvent stepLogEvent = ExecutionEventFactory.createStepLogEvent(execution.getExecutionId(),ExecutionEventUtils.increaseEvent(execution.getSystemContext()),
ExecutionEnums.StepLogCategory.STEP_ERROR, execution.getSystemContext());
eventsQueue.add(stepLogEvent);
} catch (RuntimeException eventEx) {
logger.error("Failed to create event: ", eventEx);
}
throw ex;
}
}
private ExecutionEvent createLogEvent(Execution execution, ExecutionStep currStep, RuntimeException ex, String logMessage, LogLevelCategory logLevelCategory, Map<String, Serializable> systemContext) {
Map<String, String> map = new HashMap<>();
map.put("error_message", ex.getMessage());
OOContext stepInputForEvent = new OOContext();
stepInputForEvent.put("error_message", map.get("error_message"), false);
String stepId = currStep.getExecStepId().toString();
return ExecutionEventFactory.createLogEvent(execution.getExecutionId(), stepId, logMessage, LogLevel.ERROR,
logLevelCategory, stepInputForEvent, ExecutionEventUtils.increaseEvent(systemContext), systemContext);
}
protected void navigate(Execution execution, ExecutionStep currStep) {
Long position;
try {
if (currStep.getNavigation() != null) {
Map<String, Object> navigationData = new HashMap<>(currStep.getNavigationData());
//We add all the contexts to the step data - so inside of each control action we will have access to all contexts
addContextData(navigationData, execution);
position = (Long) reflectionAdapter.executeControlAction(currStep.getNavigation(), navigationData);
execution.setPosition(position);
} else {
execution.setPosition(null); //terminate the flow - we got to the last step!
}
} catch (RuntimeException navEx) {
//If Exception occurs in navigation (almost impossible since now we always have Flow Exception Step) we can not continue since we don't know which step is the next step...
// terminating...
logger.error("Error occurred during navigation execution. Execution id: " + execution.getExecutionId(), navEx);
execution.getSystemContext().put(ExecutionConstants.EXECUTION_STEP_ERROR_KEY, navEx.getMessage()); //this is done only fo reporting
execution.getSystemContext().put(ExecutionConstants.FLOW_TERMINATION_TYPE, ExecutionStatus.SYSTEM_FAILURE);
execution.setPosition(null); //this ends the flow!!!
try {
ExecutionEvent logEvent = createLogEvent(execution, currStep, navEx, "Error occurred during navigation execution ", LogLevelCategory.STEP_NAV_ERROR, execution.getSystemContext());
@SuppressWarnings("unchecked") Deque<ExecutionEvent> eventsQueue = (Deque) execution.getSystemContext().get(ExecutionConstants.EXECUTION_EVENTS_QUEUE);
eventsQueue.add(logEvent);
ExecutionEvent stepLogEvent = ExecutionEventFactory.createStepLogEvent(execution.getExecutionId(),ExecutionEventUtils.increaseEvent(execution.getSystemContext()),
ExecutionEnums.StepLogCategory.STEP_ERROR, execution.getSystemContext());
eventsQueue.add(stepLogEvent);
} catch (RuntimeException eventEx) {
logger.error("Failed to create event: ", eventEx);
}
}
}
protected void postExecutionSettings(Execution execution) {
// Decide on Group
String group = (String) execution.getSystemContext().get(ExecutionConstants.ACTUALLY_OPERATION_GROUP);
if (StringUtils.isEmpty(group) || ExecutionConstants.DEFAULT_GROUP.equals(group)) {
execution.setGroupName(null);
} else {
execution.setGroupName(group);
}
if (isDebuggerMode(execution.getSystemContext())) {
@SuppressWarnings("unchecked") Set<String> groups = (Set<String>) execution.getSystemContext().get("ALL_ACTIVE_RUNNING_GROUPS");
if (!StringUtils.isEmpty(group) && !groups.contains(group)) {
execution.setGroupName(null);
}
}
// Decide Whether should go to jms or perform an internal agent recursion
Boolean mustGoToQueue = (Boolean) execution.getSystemContext().get(ExecutionConstants.MUST_GO_TO_QUEUE);
mustGoToQueue = (mustGoToQueue == null) ? Boolean.FALSE : mustGoToQueue;
// execution.mustGoToQueue is the value checked upon return
execution.setMustGoToQueue(mustGoToQueue);
// reset the flag in the context
execution.getSystemContext().put(ExecutionConstants.MUST_GO_TO_QUEUE, Boolean.FALSE);
}
private void addContextData(Map<String, Object> data, Execution execution) {
data.putAll(execution.getContexts());
data.put(ExecutionConstants.SYSTEM_CONTEXT, execution.getSystemContext());
data.put(ExecutionConstants.SERIALIZABLE_SESSION_CONTEXT, execution.getSerializableSessionContext());
data.put(ExecutionConstants.EXECUTION, execution);
data.put(ExecutionConstants.RUNNING_EXECUTION_PLAN_ID, execution.getRunningExecutionPlanId());
}
}
|
package net.sf.taverna.t2.workflowmodel.processor.activity;
import java.net.URI;
import java.util.Set;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Factory for creating {@link Activity} instances.
*
* @author David Withers
*/
public interface ActivityFactory {
/**
* Creates a new <code>Activity</code> instance.
*
* @return a new <code>Activity</code> instance
*/
public Activity<?> createActivity();
/**
* Returns the type of the <code>Activity</code>s that this factory can create.
*
* @return the type of the <code>Activity</code>s that this factory can create
*/
public URI getActivityType();
/**
* Returns the JSON Schema for the configuration required by the <code>Activity</code>.
*
* @return the JSON Schema for the configuration required by the <code>Activity</code>
*/
public JsonNode getActivityConfigurationSchema();
/**
* Returns the <code>ActivityInputPort</code>s that the <code>Activity</code> requires to be
* present in order to execute with the specified configuration.
* <p>
* If the <code>Activity</code> does not require any input port for the configuration then an
* empty set is returned.
*
* @param configuration
* the configuration
* @return the <code>ActivityInputPort</code>s that the <code>Activity</code> requires to be
* present in order to execute
*/
public Set<ActivityInputPort> getInputPorts(JsonNode configuration) throws ActivityConfigurationException;
/**
* Returns the <code>ActivityOutputPort</code>s that the <code>Activity</code> requires to be
* present in order to execute with the specified configuration.
* <p>
* If the <code>Activity</code> does not require any output ports for the configuration then an
* empty set is returned.
*
* @param configuration
* the configuration
* @return the <code>ActivityOutputPort</code>s that the <code>Activity</code> requires to be
* present in order to execute
*/
public Set<ActivityOutputPort> getOutputPorts(JsonNode configuration) throws ActivityConfigurationException;
}
|
package sh.jay.xposed.whatsapp;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import java.util.HashMap;
import java.util.Map;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.RelativeLayout;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
/**
* Adds support for making the background color of group conversation rows
* grey in color.
*
* Note: this code has been written solely to be performant. This means some
* code is inlined (read: copy/pasted) that wouldn't normally be, and private
* classes are used in a cache without getters and setters - amongst other things.
* This is because we're hooking into android.view.View->setTag(java.lang.Object)
* which is quite a general method, so we want to be as fast as possible.
*/
public class HighlightGroups implements IXposedHookLoadPackage {
private static final Map<Object, Drawable> processedTags = new HashMap<Object, Drawable>();
private static final Map<View, View> conversationRows = new HashMap<View, View>();
/**
* This is initially called by the Xposed Framework when we register this
* android application as an Xposed Module.
*/
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
// This method is called once per package, so we only want to apply hooks to WhatsApp.
if (!Utils.WHATSAPP_PACKAGE_NAME.equals(lpparam.packageName)) {
return;
}
if (!Preferences.hasHighlightGroups()) {
Utils.debug("Ignoring call to setTag() due to the highlight groups feature being disabled");
return;
}
findAndHookMethod("android.view.View", lpparam.classLoader, "setTag", Object.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
final View thisView = (View) param.thisObject;
View conversationRow = conversationRows.get(thisView);
if (!conversationRows.containsKey(thisView)) {
final View contactPickerViewContainer = (View) ((View) param.thisObject).getParent();
if (null == contactPickerViewContainer) {
// Doesn't even have a parent.
conversationRows.put(thisView, null);
return;
}
conversationRow = (View) contactPickerViewContainer.getParent();
if (null == conversationRow || !(conversationRow instanceof RelativeLayout)) {
// We require that our conversationRow is a RelativeLayout
// (see the overall parent of res/layout/conversations_row.xml).
conversationRows.put(thisView, null);
return;
}
conversationRows.put(thisView, conversationRow);
} else if (null == conversationRow) {
return;
}
final Object tag = param.args[0];
if (processedTags.containsKey(tag)) {
// For performance, there are no debugging or trace lines here. Let's hope it always works!
conversationRow.setBackgroundDrawable(processedTags.get(tag));
return;
}
// We have never considered what color this conversation should be. Let's figure it out.
Utils.debug("Cache miss for " + tag + " so computing the correct color");
Drawable background = null;
if (tag.toString().contains("@g.us")) {
background = new ColorDrawable(Preferences.getHighlightGroupColor());
}
conversationRow.setBackgroundDrawable(background);
processedTags.put(tag, background);
Utils.debug("Set background to " + background + " for " + tag);
}
});
}
}
|
package org.knowm.xchange.bitfinex.v1.dto.trade;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonProperty;
public class BitfinexOrderStatusResponse {
private final double id;
private final String symbol;
private final String exchange;
private final BigDecimal price;
private final BigDecimal avgExecutionPrice;
private final String side;
private final String type;
private final BigDecimal timestamp;
private final boolean isLive;
private final boolean isCancelled;
private final boolean wasForced;
private final BigDecimal originalAmount;
private final BigDecimal remainingAmount;
private final BigDecimal executedAmount;
/**
* Constructor
*
* @param id
* @param symbol
* @param exchange
* @param price
* @param avgExecutionPrice
* @param side
* @param type
* @param timestamp
* @param isLive
* @param isCancelled
* @param wasForced
* @param originalAmount
* @param remainingAmount
* @param executedAmount
*/
public BitfinexOrderStatusResponse(@JsonProperty("id") double id, @JsonProperty("symbol") String symbol, @JsonProperty("exchange") String exchange,
@JsonProperty("price") BigDecimal price, @JsonProperty("avg_execution_price") BigDecimal avgExecutionPrice, @JsonProperty("side") String side,
@JsonProperty("type") String type, @JsonProperty("timestamp") BigDecimal timestamp, @JsonProperty("is_live") boolean isLive,
@JsonProperty("is_cancelled") boolean isCancelled, @JsonProperty("was_forced") boolean wasForced,
@JsonProperty("original_amount") BigDecimal originalAmount, @JsonProperty("remaining_amount") BigDecimal remainingAmount,
@JsonProperty("executed_amount") BigDecimal executedAmount) {
this.id = id;
this.symbol = symbol;
this.exchange = exchange;
this.price = price;
this.avgExecutionPrice = avgExecutionPrice;
this.side = side;
this.type = type;
this.timestamp = timestamp;
this.isLive = isLive;
this.isCancelled = isCancelled;
this.wasForced = wasForced;
this.originalAmount = originalAmount;
this.remainingAmount = remainingAmount;
this.executedAmount = executedAmount;
}
public BigDecimal getExecutedAmount() {
return executedAmount;
}
public BigDecimal getRemainingAmount() {
return remainingAmount;
}
public BigDecimal getOriginalAmount() {
return originalAmount;
}
public boolean getWasForced() {
return wasForced;
}
public String getExchange() {
return exchange;
}
public String getType() {
return type;
}
public String getSymbol() {
return symbol;
}
public boolean isCancelled() {
return isCancelled;
}
public BigDecimal getPrice() {
return price;
}
public String getSide() {
return side;
}
public BigDecimal getTimestamp() {
return timestamp;
}
public double getId() {
return id;
}
public boolean isLive() {
return isLive;
}
public BigDecimal getAvgExecutionPrice() {
return avgExecutionPrice;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BitfinexOrderStatusResponse [id=");
builder.append(id);
builder.append(", symbol=");
builder.append(symbol);
builder.append(", exchange=");
builder.append(exchange);
builder.append(", price=");
builder.append(price);
builder.append(", avgExecutionPrice=");
builder.append(avgExecutionPrice);
builder.append(", side=");
builder.append(side);
builder.append(", type=");
builder.append(type);
builder.append(", timestamp=");
builder.append(timestamp);
builder.append(", isLive=");
builder.append(isLive);
builder.append(", isCancelled=");
builder.append(isCancelled);
builder.append(", wasForced=");
builder.append(wasForced);
builder.append(", originalAmount=");
builder.append(originalAmount);
builder.append(", remainingAmount=");
builder.append(remainingAmount);
builder.append(", executedAmount=");
builder.append(executedAmount);
builder.append("]");
return builder.toString();
}
}
|
package com;
import java.util.Scanner;
public class Echode {
static Scanner scan;
private static String in;
/**
* @param args
*/
public static void main(String[] args) {
scan = new Scanner(System.in);
intro();
}
//i couldn't get the welcome message right, so thats why i made this
public static void intro() {
System.out.println("Welcome to ECHODE version 0.2");
mainLoop();
}
private static void mainLoop() {
while (true) {
System.out.print("->");
in = scan.nextLine();
parse(in);
}
}
private static void parse(String in2) {
if (in2.equalsIgnoreCase("about")) {
System.out.println("Echode version 0.2.2\nMade by Erik Konijn and Marks Polakovs");
} else {
if (in2.equalsIgnoreCase("kill")){
System.out.println("Echode shut down succesfully.");
System.exit(0);
}else{
System.out.println("Not implemented yet.");
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package depthPeeling.depthPeelingGL3;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;
import com.jogamp.newt.event.MouseEvent;
import com.jogamp.newt.event.MouseListener;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.GLBuffers;
import glutil.ViewData;
import glutil.ViewPole;
import glutil.ViewScale;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import jglm.Jglm;
import jglm.Mat4;
import jglm.Quat;
import jglm.Vec3;
/**
*
* @author gbarbieri
*/
public class DepthPeelingGL3 implements GLEventListener, KeyListener, MouseListener{
private boolean depthPeelingMode = false;
private int imageWidth = 1024;
private int imageHeight = 768;
private GLWindow glWindow;
private NewtCanvasAWT newtCanvasAWT;
private int[] depthTextureId;
private int[] colorTextureId;
private int[] fboId;
private int[] colorBlenderTextureId;
private int[] colorBlenderFboId;
private float FOVY = 30.0f;
private float zNear = 0.0001f;
private float zFar = 10.0f;
private int oldX, oldY, newX, newY;
private boolean rotating = false;
private boolean panning = false;
private boolean scaling = false;
private int geoPassesNumber;
private int passesNumber = 4;
private ProgramInit dpInit;
private ProgramPeel dpPeel;
private ProgramBlend dpBlend;
private ProgramFinal dpFinal;
private int[] queryId = new int[1];
private float[] pos = new float[]{0.0f, 0.0f, 2.0f};
private float[] rot = new float[]{0.0f, 0.0f};
private float[] transl = new float[]{0.0f, 0.0f, 0.0f};
private float scale = 1.0f;
private float opacity = 0.3f;
private float[] backgroundColor = new float[]{1.0f, 1.0f, 1.0f};
private int[] quadVBO;
private int[] quadVAO;
private int[] modelVBO;
private int[] modelVAO;
private ViewPole viewPole;
private int[] mvpMatrixesUBO;
private float[] modelVertexAttributes;
public DepthPeelingGL3() {
initGL();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
DepthPeelingGL3 depthPeeling = new DepthPeelingGL3();
Frame frame = new Frame("Depth peeling GL3");
frame.add(depthPeeling.getNewtCanvasAWT());
frame.setSize(depthPeeling.getglWindow().getWidth(), depthPeeling.getglWindow().getHeight());
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
frame.setVisible(true);
}
private void initGL() {
GLProfile gLProfile = GLProfile.getDefault();
GLCapabilities gLCapabilities = new GLCapabilities(gLProfile);
glWindow = GLWindow.create(gLCapabilities);
newtCanvasAWT = new NewtCanvasAWT(glWindow);
glWindow.setSize(imageWidth, imageHeight);
glWindow.addGLEventListener(this);
glWindow.addKeyListener(this);
glWindow.addMouseListener(this);
}
@Override
public void init(GLAutoDrawable glad) {
System.out.println("init");
glWindow.setAutoSwapBufferMode(false);
GL3 gl3 = glad.getGL().getGL3();
int projectionBlockBinding = 0;
ViewData initialViewData = new ViewData(new Vec3(0.0f, 0.0f, 0.0f), new Quat(0.0f, 0.0f, 0.0f, 1.0f), 50.0f, 0.0f);
ViewScale viewScale = new ViewScale(3.0f, 20.0f, 1.5f, 0.5f, 0.0f, 0.0f, 90.0f / 250.0f);
viewPole = new ViewPole(initialViewData, viewScale, ViewPole.Projection.orthographic);
initUBO(gl3, projectionBlockBinding);
initDepthPeelingRenderTargets(gl3);
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, 0);
readAsciiStl(gl3);
buildShaders(gl3, projectionBlockBinding);
initFullScreenQuad(gl3);
}
private void initUBO(GL3 gl3, int projectionBlockBinding) {
mvpMatrixesUBO = new int[1];
int size = 16 * 4;
gl3.glGenBuffers(1, mvpMatrixesUBO, 0);
gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, mvpMatrixesUBO[0]);
{
gl3.glBufferData(GL3.GL_UNIFORM_BUFFER, size * 2, null, GL3.GL_DYNAMIC_DRAW);
gl3.glBindBufferRange(GL3.GL_UNIFORM_BUFFER, projectionBlockBinding, mvpMatrixesUBO[0], 0, size * 2);
}
gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, 0);
}
private void initFullScreenQuad(GL3 gl3) {
initQuadVBO(gl3);
initQuadVAO(gl3);
Mat4 modelToClipMatrix = Jglm.orthographic2D(0, 1, 0, 1);
dpFinal.bind(gl3);
{
gl3.glUniformMatrix4fv(dpFinal.getModelToClipMatrixUnLoc(), 1, false, modelToClipMatrix.toFloatArray(), 0);
}
dpFinal.unbind(gl3);
dpBlend.bind(gl3);
{
gl3.glUniformMatrix4fv(dpBlend.getModelToClipMatrixUnLoc(), 1, false, modelToClipMatrix.toFloatArray(), 0);
}
dpBlend.unbind(gl3);
}
private void initQuadVAO(GL3 gl3) {
quadVAO = new int[1];
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, quadVBO[0]);
gl3.glGenVertexArrays(1, IntBuffer.wrap(quadVAO));
gl3.glBindVertexArray(quadVAO[0]);
{
gl3.glEnableVertexAttribArray(0);
{
gl3.glVertexAttribPointer(0, 2, GL3.GL_FLOAT, false, 0, 0);
}
}
gl3.glBindVertexArray(0);
}
private void initQuadVBO(GL3 gl3) {
float[] vertexAttributes = new float[]{
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f};
quadVBO = new int[1];
gl3.glGenBuffers(1, IntBuffer.wrap(quadVBO));
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, quadVBO[0]);
{
FloatBuffer buffer = GLBuffers.newDirectFloatBuffer(vertexAttributes);
gl3.glBufferData(GL3.GL_ARRAY_BUFFER, vertexAttributes.length * 4, buffer, GL3.GL_STATIC_DRAW);
}
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0);
}
private void buildShaders(GL3 gl3, int projectionBlockIndex) {
System.out.print("buildShaders... ");
String shadersFilepath = "/depthPeeling/depthPeelingGL3/shaders/";
dpInit = new ProgramInit(gl3, shadersFilepath, new String[]{"dpInit_VS.glsl"}, new String[]{"shade_FS.glsl", "dpInit_FS.glsl"}, projectionBlockIndex);
// dpInit = new ProgramInit(gl3, shadersFilepath, "dpInit_VS.glsl", "dpInit_FS.glsl", projectionBlockIndex);
dpPeel = new ProgramPeel(gl3, shadersFilepath, new String[]{"dpPeel_VS.glsl"}, new String[]{"shade_FS.glsl", "dpPeel_FS.glsl"}, projectionBlockIndex);
dpBlend = new ProgramBlend(gl3, shadersFilepath, "dpBlend_VS.glsl", "dpBlend_FS.glsl");
dpFinal = new ProgramFinal(gl3, shadersFilepath, "dpFinal_VS.glsl", "dpFinal_FS.glsl");
System.out.println("ok");
}
private void readAsciiStl(GL3 gl3) {
try {
FileReader fr;
int vertexLocal = 0;
int attributesGlobal = 0;
URL url = getClass().getResource("/depthPeeling/data/frontlader5.stl");
fr = new FileReader(new File(url.getPath()));
BufferedReader br = new BufferedReader(fr);
String line = "";
String values[];
float[] data = new float[3 * 3 * 2];
float[] vertex = new float[9];
float[] normal = new float[3];
// Count triangles
int triangles = 0;
while ((line = br.readLine()) != null) {
line = line.trim().toLowerCase();
if (line.startsWith("facet")) {
triangles++;
}
}
System.out.println("triangles: " + triangles);
// 3 Vertexes, 3 coordinates, 2 attributes
modelVertexAttributes = new float[triangles * 3 * 3 * 2];
br.close();
fr.close();
fr = new FileReader(new File(url.getPath()));
br = new BufferedReader(fr);
line = "";
// int triangles_read = 0;
while ((line = br.readLine()) != null) {
line = line.trim().toLowerCase();
// Read normals
if (line.startsWith("facet")) {
int normalLocal = 0;
values = line.split(" ");
for (int i = 2; i < values.length; i++) {
if (!values[i].isEmpty()) {
normal[normalLocal] = Float.parseFloat(values[i]);
normalLocal++;
}
}
}
// Read points
if (line.startsWith("vertex")) {
values = line.split(" ");
for (int i = 1; i < values.length; i++) {
if (!values[i].isEmpty()) {
vertex[vertexLocal] = Float.parseFloat(values[i]);
vertexLocal++;
}
}
}
if (vertexLocal == 9) {
// Fill vertex and normals interleaved
for (int i = 0; i < 3; i++) {
data[i * 6] = vertex[i * 3];
data[i * 6 + 1] = vertex[i * 3 + 1];
data[i * 6 + 2] = vertex[i * 3 + 2];
data[i * 6 + 3] = normal[0];
data[i * 6 + 4] = normal[1];
data[i * 6 + 5] = normal[2];
}
// System.out.print("data[" + attributesGlobal + "] ");
// for (int i = 0; i < data.length; i++) {
// System.out.print(data[i] + " ");
// System.out.println("");
System.arraycopy(data, 0, modelVertexAttributes, attributesGlobal * 3 * 3 * 2, data.length);
vertexLocal = 0;
attributesGlobal++;
}
}
br.close();
fr.close();
System.out.println("Done, number of triangles: " + modelVertexAttributes.length / 18);
} catch (FileNotFoundException ex) {
Logger.getLogger(DepthPeelingGL3.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DepthPeelingGL3.class.getName()).log(Level.SEVERE, null, ex);
}
initModelVBO(gl3);
initModelVAO(gl3);
}
private void initModelVAO(GL3 gl3) {
modelVAO = new int[1];
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, modelVBO[0]);
gl3.glGenVertexArrays(1, IntBuffer.wrap(modelVAO));
gl3.glBindVertexArray(modelVAO[0]);
{
gl3.glEnableVertexAttribArray(0);
{
gl3.glVertexAttribPointer(0, 3, GL3.GL_FLOAT, false, 6 * 4, 0);
}
}
gl3.glBindVertexArray(0);
}
private void initModelVBO(GL3 gl3) {
modelVBO = new int[1];
gl3.glGenBuffers(1, IntBuffer.wrap(modelVBO));
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, modelVBO[0]);
{
FloatBuffer buffer = GLBuffers.newDirectFloatBuffer(modelVertexAttributes);
gl3.glBufferData(GL3.GL_ARRAY_BUFFER, modelVertexAttributes.length * 4, buffer, GL3.GL_STATIC_DRAW);
}
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0);
}
private void initDepthPeelingRenderTargets(GL3 gl3) {
depthTextureId = new int[2];
colorTextureId = new int[2];
fboId = new int[2];
gl3.glGenTextures(2, depthTextureId, 0);
gl3.glGenTextures(2, colorTextureId, 0);
gl3.glGenFramebuffers(2, fboId, 0);
for (int i = 0; i < 2; i++) {
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, depthTextureId[i]);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_WRAP_S, GL3.GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_WRAP_T, GL3.GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_NEAREST);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_NEAREST);
gl3.glTexImage2D(GL3.GL_TEXTURE_RECTANGLE, 0, GL3.GL_DEPTH_COMPONENT32F, imageWidth, imageHeight, 0, GL3.GL_DEPTH_COMPONENT, GL3.GL_FLOAT, null);
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, colorTextureId[i]);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_WRAP_S, GL3.GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_WRAP_T, GL3.GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_NEAREST);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_NEAREST);
gl3.glTexImage2D(GL3.GL_TEXTURE_RECTANGLE, 0, GL3.GL_RGBA, imageWidth, imageHeight, 0, GL3.GL_RGBA, GL3.GL_FLOAT, null);
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, fboId[i]);
gl3.glFramebufferTexture2D(GL3.GL_FRAMEBUFFER, GL3.GL_DEPTH_ATTACHMENT, GL3.GL_TEXTURE_RECTANGLE, depthTextureId[i], 0);
gl3.glFramebufferTexture2D(GL3.GL_FRAMEBUFFER, GL3.GL_COLOR_ATTACHMENT0, GL3.GL_TEXTURE_RECTANGLE, colorTextureId[i], 0);
}
colorBlenderTextureId = new int[1];
gl3.glGenTextures(1, colorBlenderTextureId, 0);
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, colorBlenderTextureId[0]);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_WRAP_S, GL3.GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_WRAP_T, GL3.GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_NEAREST);
gl3.glTexParameteri(GL3.GL_TEXTURE_RECTANGLE, GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_NEAREST);
gl3.glTexImage2D(GL3.GL_TEXTURE_RECTANGLE, 0, GL3.GL_RGBA, imageWidth, imageHeight, 0, GL3.GL_RGBA, GL3.GL_FLOAT, null);
colorBlenderFboId = new int[1];
gl3.glGenFramebuffers(1, colorBlenderFboId, 0);
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, colorBlenderFboId[0]);
gl3.glFramebufferTexture2D(GL3.GL_FRAMEBUFFER, GL3.GL_COLOR_ATTACHMENT0, GL3.GL_TEXTURE_RECTANGLE, colorBlenderTextureId[0], 0);
gl3.glFramebufferTexture2D(GL3.GL_FRAMEBUFFER, GL3.GL_DEPTH_ATTACHMENT, GL3.GL_TEXTURE_RECTANGLE, depthTextureId[0], 0);
}
private void deleteDepthPeelingRenderTargets(GL3 gl3) {
gl3.glDeleteFramebuffers(2, fboId, 0);
gl3.glDeleteFramebuffers(1, colorBlenderFboId, 0);
gl3.glDeleteTextures(2, depthTextureId, 0);
gl3.glDeleteTextures(2, colorTextureId, 0);
gl3.glDeleteTextures(1, colorBlenderTextureId, 0);
}
@Override
public void dispose(GLAutoDrawable glad) {
System.out.println("dispose");
}
@Override
public void display(GLAutoDrawable glad) {
System.out.println("display, passesNumber " + passesNumber);
GL3 gl3 = glad.getGL().getGL3();
geoPassesNumber = 0;
// gl3.glMatrixMode(GL2.GL_MODELVIEW);
// gl3.glLoadIdentity();
// glu.gluLookAt(pos[0], pos[1], pos[2], pos[0], pos[1], 0.0f, 0.0f, 1.0f, 0.0f);
// gl3.glRotatef(rot[0], 1.0f, 0.0f, 0.0f);
// gl3.glRotatef(rot[1], 0.0f, 1.0f, 0.0f);
// gl3.glTranslated(transl[0], transl[1], transl[2]);
// gl3.glScalef(scale, scale, scale);
renderDepthPeeling(gl3);
// gl2.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
// gl2.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
// gl2.glColor3f(0.5f, 0.5f, 0.5f);
// drawModel(gl2);
glad.swapBuffers();
}
private void renderDepthPeeling(GL3 gl3) {
/**
* (1) Initialize min depth buffer.
*/
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, colorBlenderFboId[0]);
// gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, 0);
gl3.glDrawBuffer(GL3.GL_COLOR_ATTACHMENT0);
gl3.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl3.glClear(GL3.GL_COLOR_BUFFER_BIT | GL3.GL_DEPTH_BUFFER_BIT);
gl3.glEnable(GL3.GL_DEPTH_TEST);
dpInit.bind(gl3);
{
gl3.glUniform1f(dpInit.getAlphaUnLoc(), opacity);
drawModel(gl3);
}
dpInit.unbind(gl3);
/**
* (2) Depth peeling + blending.
*/
int layersNumber = (passesNumber - 1) * 2;
// System.out.println("layersNumber: " + layersNumber);
for (int layer = 1; layer < layersNumber; layer++) {
int currentId = layer % 2;
int previousId = 1 - currentId;
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, fboId[currentId]);
// gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, 0);
gl3.glDrawBuffer(GL3.GL_COLOR_ATTACHMENT0);
gl3.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl3.glClear(GL3.GL_COLOR_BUFFER_BIT | GL3.GL_DEPTH_BUFFER_BIT);
gl3.glDisable(GL3.GL_BLEND);
gl3.glEnable(GL3.GL_DEPTH_TEST);
{
dpPeel.bind(gl3);
{
gl3.glActiveTexture(GL3.GL_TEXTURE0);
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, depthTextureId[previousId]);
gl3.glUniform1i(dpPeel.getDepthTexUnLoc(), 0);
{
gl3.glUniform1f(dpPeel.getAlphaUnLoc(), opacity);
drawModel(gl3);
}
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, 0);
}
dpPeel.unbind(gl3);
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, colorBlenderFboId[0]);
gl3.glDrawBuffer(GL3.GL_COLOR_ATTACHMENT0);
}
gl3.glDisable(GL3.GL_DEPTH_TEST);
gl3.glEnable(GL3.GL_BLEND);
{
gl3.glBlendEquation(GL3.GL_FUNC_ADD);
gl3.glBlendFuncSeparate(GL3.GL_DST_ALPHA, GL3.GL_ONE, GL3.GL_ZERO, GL3.GL_ONE_MINUS_SRC_ALPHA);
dpBlend.bind(gl3);
// dpBlend.bindTextureRECT(gl3, "TempTex", colorTextureId[currentId], 0);
gl3.glActiveTexture(GL3.GL_TEXTURE0);
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, colorTextureId[currentId]);
gl3.glUniform1i(dpBlend.getTempTexUnLoc(), 0);
{
// gl3.glCallList(quadDisplayList);
drawFullScreenQuad(gl3);
}
dpBlend.unbind(gl3);
}
gl3.glDisable(GL3.GL_BLEND);
}
/**
* (3) Final pass.
*/
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, 0);
gl3.glDrawBuffer(GL3.GL_BACK);
gl3.glDisable(GL3.GL_DEPTH_TEST);
dpFinal.bind(gl3);
{
gl3.glUniform3f(dpFinal.getBackgroundColorUnLoc(), 1.0f, 1.0f, 1.0f);
// dpFinal.bindTextureRECT(gl3, "ColorTex", colorBlenderTextureId[0], 0);
gl3.glActiveTexture(GL3.GL_TEXTURE0);
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, colorBlenderTextureId[0]);
gl3.glUniform1i(dpFinal.getColorTexUnLoc(), 0);
{
// gl3.glCallList(quadDisplayList);
drawFullScreenQuad(gl3);
}
gl3.glBindTexture(GL3.GL_TEXTURE_RECTANGLE, 0);
}
dpFinal.unbind(gl3);
}
private void drawModel(GL3 gl3) {
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, modelVBO[0]);
gl3.glBindVertexArray(modelVAO[0]);
{
// Render, passing the vertex number
gl3.glDrawArrays(GL3.GL_TRIANGLES, 0, modelVertexAttributes.length / 6);
}
gl3.glBindVertexArray(0);
geoPassesNumber++;
}
private void drawFullScreenQuad(GL3 gl3) {
gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, quadVBO[0]);
gl3.glBindVertexArray(quadVAO[0]);
{
// Render, passing the vertex number
gl3.glDrawArrays(GL3.GL_QUADS, 0, 4);
}
gl3.glBindVertexArray(0);
}
@Override
public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) {
System.out.println("reshape");
GL3 gl3 = glad.getGL().getGL3();
if (imageWidth != width || imageHeight != height) {
imageWidth = width;
imageHeight = height;
deleteDepthPeelingRenderTargets(gl3);
initDepthPeelingRenderTargets(gl3);
gl3.glBindFramebuffer(GL3.GL_FRAMEBUFFER, 0);
}
gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, mvpMatrixesUBO[0]);
{
float base = 10000.0f;
float aspect = (float) width / (float) height;
int size = 16 * 4;
// Projection Matrix
// Mat4 projectionMatrix = Jglm.perspective(FOVY, imageWidth / imageHeight, zNear, zFar);
Mat4 projectionMatrix = Jglm.orthographic(-base * aspect, base * aspect, -base, base, -base, base);
gl3.glBufferSubData(GL3.GL_UNIFORM_BUFFER, 0, size, GLBuffers.newDirectFloatBuffer(projectionMatrix.toFloatArray()));
// Modelview Matrix
Mat4 modelviewMatrix = viewPole.calcMatrix();
gl3.glBufferSubData(GL3.GL_UNIFORM_BUFFER, 16 * 4, size, GLBuffers.newDirectFloatBuffer(modelviewMatrix.toFloatArray()));
}
gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, 0);
gl3.glViewport(0, 0, imageWidth, imageHeight);
}
public GLWindow getglWindow() {
return glWindow;
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
@Override
public void mouseClicked(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseMoved(MouseEvent me) {
}
@Override
public void mouseDragged(MouseEvent me) {
}
@Override
public void mouseWheelMoved(MouseEvent me) {
}
public NewtCanvasAWT getNewtCanvasAWT() {
return newtCanvasAWT;
}
}
|
package com.hackoeur.jglm;
import java.nio.FloatBuffer;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.hackoeur.jglm.support.Compare;
import com.hackoeur.jglm.support.FastMath;
import com.hackoeur.jglm.support.Precision;
/**
* @author James Royalty
*/
public class Vec3Test {
@Test
public void testMultiply() {
Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f).multiply(2.5f);
Assert.assertEquals(new Vec3(1810905856f, -821278656f, 5360670208f), v1);
}
@Test
public void testMultiplyMat() {
Mat3 m1 = new Mat3(
1f, 2f, 3f,
4f, 5f, 6f,
7f, 8f, 9f
);
Vec3 v1 = new Vec3(10.0f, 11.0f, 12.0f);
Vec3 result = v1.multiply(m1);
JglmTesting.assertFloatsEqualDefaultTol(68f, result.x);
JglmTesting.assertFloatsEqualDefaultTol(167f, result.y);
JglmTesting.assertFloatsEqualDefaultTol(266f, result.z);
}
@Test
public void testScale() {
Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f).scale(2.5f);
Assert.assertEquals(new Vec3(1810905856f, -821278656f, 5360670208f), v1);
}
@Test
public void testScaleVector() {
Vec3 scalar = new Vec3(2.0f, 2.5f, 1.0f);
Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f).scale(scalar);
Assert.assertEquals(new Vec3(1448724760f, -821278656f, 2144268067f), v1);
}
@Test
public void testGetLength() {
Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f);
float len = (float) StrictMath.sqrt(
v1.getX() * v1.getX()
+ v1.getY() * v1.getY()
+ v1.getZ() * v1.getZ()
);
Assert.assertEquals(len, v1.getLength(), JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testGetLengthSquared() {
Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f);
float len = v1.getX() * v1.getX()
+ v1.getY() * v1.getY()
+ v1.getZ() * v1.getZ();
Assert.assertEquals(len, v1.getLengthSquared(), JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testGetUnitVector() {
final Vec3 vec1 = new Vec3(1f, 2f, 3f);
final Vec3 norm1 = vec1.getUnitVector();
Assert.assertEquals(0.267261f, norm1.getX(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(0.534522f, norm1.getY(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(0.801784f, norm1.getZ(), JglmTesting.DEFAULT_EQUALS_TOL);
final Vec3 vec2 = new Vec3(-2652735904120045568f, 1379645337739722752f, 1107497449448013824f);
final Vec3 norm2 = vec2.getUnitVector();
Assert.assertTrue(Precision.equals(norm2.getLength(), 1f, Compare.VEC_EPSILON));
Assert.assertEquals(-0.831951, norm2.getX(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(0.432685, norm2.getY(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(0.347334, norm2.getZ(), JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testGetNegated() {
final Vec3 v1 = new Vec3(-2652735904120045568f, 1379645337739722752f, 1107497449448013824f);
final Vec3 neg = v1.getNegated();
Assert.assertEquals(-v1.getX(), neg.getX(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(-v1.getY(), neg.getY(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(-v1.getZ(), neg.getZ(), JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testDot() {
final Vec3 v1 = new Vec3(1f, 2f, 3f);
final Vec3 v2 = new Vec3(4f, 5f, 6f);
final float dot1 = v1.dot(v2);
Assert.assertEquals(32f, dot1, JglmTesting.DEFAULT_EQUALS_TOL);
final Vec3 v3 = new Vec3(724362380f, -328511470f, 2144268067f);
final Vec3 v4 = new Vec3(1151420018f, 1006737463f, 1503816073f);
final float dot2 = v3.dot(v4);
Assert.assertEquals(3727905169090805760f, dot2, JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testCross() {
final Vec3 v1 = new Vec3(1f, 2f, 3f);
final Vec3 v2 = new Vec3(4f, 5f, 6f);
final Vec3 cross1 = v1.cross(v2);
Assert.assertEquals(-3f, cross1.getX(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(6f, cross1.getY(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(-3f, cross1.getZ(), JglmTesting.DEFAULT_EQUALS_TOL);
final Vec3 v3 = new Vec3(724362380f, -328511470f, 2144268067f);
final Vec3 v4 = new Vec3(1151420018f, 1006737463f, 1503816073f);
final Vec3 cross2 = v3.cross(v4);
Assert.assertEquals(-2652735904120045568f, cross2.getX(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(1379645337739722752f, cross2.getY(), JglmTesting.DEFAULT_EQUALS_TOL);
Assert.assertEquals(1107497449448013824f, cross2.getZ(), JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testAngle() {
final Vec3 v1 = new Vec3(0f, 1f, 0f);
final Vec3 v2 = new Vec3(1f, 0f, 0f);
Assert.assertEquals(FastMath.toRadians(90d), v1.angleInRadians(v2), JglmTesting.DEFAULT_EQUALS_TOL);
}
@Test
public void testEquals() {
final Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f);
final Vec3 v2 = new Vec3(724362380f, -328511470f, 2144268067f);
Assert.assertEquals(v1, v2);
Assert.assertTrue(v1.equalsWithEpsilon(v2, JglmTesting.DEFAULT_EQUALS_TOL));
}
@Test
public void testBuffer() {
final Vec3 v1 = new Vec3(724362380f, -328511470f, 2144268067f);
final FloatBuffer buffer = v1.getBuffer();
JglmTesting.assertFloatsEqualDefaultTol(v1.getX(), buffer.get());
JglmTesting.assertFloatsEqualDefaultTol(v1.getY(), buffer.get());
JglmTesting.assertFloatsEqualDefaultTol(v1.getZ(), buffer.get());
}
@Ignore
public void testCreatePerformance() {
final long startTs = System.currentTimeMillis();
int x = 0;
int y = 0;
int z = 0;
Vec3 v1 = null;
Vec3 v2 = null;
for (long i=0; i<1000000000L; i++) {
v1 = new Vec3(x+i, y+i, z+i);
v2 = v1.multiply(i);
}
final long totalTime = System.currentTimeMillis() - startTs;
System.out.println("Time in ms : " + totalTime);
System.out.println("Time in sec: " + TimeUnit.MILLISECONDS.toSeconds(totalTime));
System.out.println("Time in min: " + TimeUnit.MILLISECONDS.toMinutes(totalTime));
System.out.println("v1: " + v1);
System.out.println("v2: " + v2);
}
}
|
package ev3dev.actuators;
import ev3dev.hardware.EV3DevFileSystem;
import ev3dev.hardware.EV3DevPlatform;
import ev3dev.utils.JarResource;
import fake_ev3dev.ev3dev.actuators.FakeSound;
import fake_ev3dev.ev3dev.sensors.FakeBattery;
import org.junit.*;
import org.junit.rules.ExpectedException;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class SoundTest {
private static final String defaultSound = "nod_low_power.wav";
private static final String nullSound = "myUnknownSong.wav";
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void beforeClass() {
System.setProperty(EV3DevFileSystem.EV3DEV_TESTING_KEY, FakeBattery.EV3DEV_FAKE_SYSTEM_PATH);
System.setProperty(Sound.EV3DEV_SOUND_KEY, FakeSound.EV3DEV_FAKE_SYSTEM_PATH);
}
@Before
public void resetTest() throws IOException, NoSuchFieldException, IllegalAccessException {
//Review for Java 9
//Field instance = Sound.class.getDeclaredField("instance");
//instance.setAccessible(true);
//instance.set(null, null);
FakeBattery.resetEV3DevInfrastructure();
//System.setProperty(EV3DevFileSystem.EV3DEV_TESTING_KEY, FakeBattery.EV3DEV_FAKE_SYSTEM_PATH);
//System.setProperty(Sound.EV3DEV_SOUND_KEY, FakeSound.EV3DEV_FAKE_SYSTEM_PATH);
}
@Test
public void singletonTest() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
Sound sound2 = Sound.getInstance();
assertThat(sound, is(sound2));
}
@Test
public void beepTest() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.beep();
}
@Ignore
@Test
public void beepBrickPiTest() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.BRICKPI);
Sound sound = Sound.getInstance();
sound.beep();
}
@Test
public void getVolumeTest() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
final FakeSound fakeSound = new FakeSound(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.setVolume(40);
assertThat(sound.getVolume(), is(40));
}
@Test
public void setVolumeTest() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
final FakeSound fakeSound = new FakeSound(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.setVolume(20);
assertThat(sound.getVolume(), is(20));
}
@Ignore("It is not running on Travis CI")
@Test
public void playSample() throws Exception {
String filePath = "nod_low_power.wav";
String result = JarResource.export(filePath);
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.playSample(new File(result));
}
@Ignore("It is not running on Travis CI")
@Test
public void playMultipleSamples() throws Exception {
String filePath = "nod_low_power.wav";
String result = JarResource.export(filePath);
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.setVolume(100);
sound.playSample(new File(result));
sound.setVolume(50);
sound.playSample(new File(result));
assertThat(sound.getVolume(), is(50));
}
@Test
public void playSampleKO() throws Exception {
thrown.expect(RuntimeException.class);
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.playSample(new File(nullSound));
}
@Ignore("It is not running on Travis CI")
@Test
public void playSampleWitVolume() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.playSample(new File(nullSound), 40);
assertThat(sound.getVolume(), is(40));
}
@Test
public void playTone() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
final FakeSound fakeSound = new FakeSound(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.playTone(100, 100);
}
@Test
public void playToneWithVolume() throws Exception {
final FakeBattery fakeBattery = new FakeBattery(EV3DevPlatform.EV3BRICK);
final FakeSound fakeSound = new FakeSound(EV3DevPlatform.EV3BRICK);
Sound sound = Sound.getInstance();
sound.playTone(100, 100, 60);
assertThat(sound.getVolume(), is(60));
}
}
|
package guitests;
import org.junit.Test;
import seedu.cmdo.testutil.TestTask;
import seedu.cmdo.testutil.TestUtil;
import static seedu.cmdo.logic.commands.DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS;
import static org.junit.Assert.assertTrue;
//@@author A0141128R
public class DeleteCommandTest extends ToDoListGuiTest {
@Test
public void delete() {
//delete the first in the list
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
assertDeleteSuccess(targetIndex, currentList);
currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
//delete the last in the list
targetIndex = currentList.length;
assertDeleteSuccess(targetIndex, currentList);
currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
//delete from the middle of the list
targetIndex = currentList.length/2;
assertDeleteSuccess(targetIndex, currentList);
currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
//invalid index
commandBox.runCommand("delete " + currentList.length + 1);
assertResultMessage("The task index provided is invalid");
//delete something from an empty list
commandBox.runCommand("clear");
targetIndex = 1;
commandBox.runCommand("delete " + targetIndex);
assertResultMessage("The task index provided is invalid");
}
/**
* Runs the delete command to delete the task at specified index and confirms the result is correct.
* @param targetIndexOneIndexed e.g. to delete the first task in the list, 1 should be given as the target index.
* @param currentList A copy of the current list of tasks (before deletion).
*/
private void assertDeleteSuccess(int targetIndexOneIndexed, final TestTask[] currentList) {
TestTask taskToDelete = currentList[targetIndexOneIndexed-1]; //-1 because array uses zero indexing
TestTask[] expectedRemainder = TestUtil.removeTaskFromList(currentList, targetIndexOneIndexed);
commandBox.runCommand("delete " + targetIndexOneIndexed);
//confirm the list now contains all previous tasks except the deleted task
assertTrue(taskListPanel.isListMatching(expectedRemainder));
//confirm the result message is correct
assertResultMessage(MESSAGE_DELETE_TASK_SUCCESS);
}
}
|
//@@author A0141052Y
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.task.testutil.TestTask;
public class SearchCommandTest extends TaskManagerGuiTest {
@Test
public void search() {
TestTask[] currentList = td.getTypicalTasks();
// test search no name
assertSearchResult("", currentList);
// test search full name
assertSearchResult(td.daniel.getName().taskName, td.daniel);
// test search partial name
assertSearchResult("Have lunch", td.daniel);
// test search no results
assertSearchResult("this does not exist");
}
private void resetCommandBox() {
commandBox.pressEnter();
}
private void assertSearchResult(String query, TestTask... expectedHits ) {
commandBox.runCommand("searchbox");
commandBox.enterCommand(query);
assertListSize(expectedHits.length);
assertTrue(taskListPanel.isListMatching(expectedHits));
commandBox.runCommand(query);
assertListSize(expectedHits.length);
assertTrue(taskListPanel.isListMatching(expectedHits));
resetCommandBox();
}
}
|
package org.noear.weed;
import java.sql.SQLException;
import java.util.ArrayList;
public class DbQuery extends DbAccess<DbQuery> {
public DbQuery(DbContext context)
{
super(context);
}
public DbQuery sql(SQLBuilder sqlBuilder) {
this.commandText = sqlBuilder.toString();
this.paramS.clear();
this._weedKey = null;
for (Object p1 : sqlBuilder.paramS) {
doSet("", p1);
}
return this;
}
@Override
protected String getCommandID() {
return this.commandText;
}
@Override
protected Command getCommand() {
Command cmd = new Command(this.context,_tran);
cmd.key = getCommandID();
cmd.paramS = this.paramS;
StringBuilder sb = new StringBuilder(commandText);
//1.schema
int idx=0;
while (true) {
idx = sb.indexOf("$",idx);
if(idx>0) {
sb.replace(idx, idx + 1, context.schema());
idx++;
}
else {
break;
}
}
cmd.text = sb.toString();
runCommandBuiltEvent(cmd);
return cmd;
}
}
|
package innovimax.mixthem;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.arguments.Rule;
import innovimax.mixthem.arguments.RuleParam;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* Provides different runs for testing a rule according to the additional parameters
* @author Innovimax
* @version 1.0
*/
public class RuleRuns {
final private static String DEFAULT_OUTPUT_FILE = "default";
/**
* Returns a list of test runs for the rule.
* @param url The URL of rule additional parameters file
* @return Returns a list of test runs for the rule
*/
public static List<RuleRun> getRuns(Rule rule, URL url) throws FileNotFoundException, IOException, NumberFormatException {
List<RuleRun> runs = new LinkedList<RuleRun>();
runs.add(new RuleRun(Collections.emptyMap()));
if (url != null) {
File file = new File(url.getFile());
BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8);
Stream<String> entries = reader.lines();
entries.forEach(entry -> {
String[] parts = entry.split("\\s");
if (parts.length > 1) {
String suffix = parts[0];
Map<RuleParam, ParamValue> params = new EnumMap<RuleParam, ParamValue>(RuleParam.class);
switch (rule) {
case RANDOM_ALT_LINE:
int seed = Integer.parseInt(parts[1]);
params.put(RuleParam.RANDOM_SEED, ParamValue.createInt(seed));
break;
case JOIN:
int col = Integer.parseInt(parts[1]);
params.put(RuleParam.JOIN_COL1, ParamValue.createInt(col));
if (parts.length > 2) {
col = Integer.parseInt(parts[2]);
params.put(RuleParam.JOIN_COL2, ParamValue.createInt(col));
} else {
params.put(RuleParam.JOIN_COL2, ParamValue.createInt(col));
}
break;
case ZIP_LINE:
case ZIP_CELL:
case ZIP_CHAR:
String sep = parts[1];
params.put(RuleParam.ZIP_SEP, ParamValue.createString(sep));
}
if (suffix.equals(DEFAULT_OUTPUT_FILE)) {
runs.add(new RuleRun(null, params));
} else {
runs.add(new RuleRun(suffix, params));
}
}
});
}
return runs;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.